"""ASTranslate""" import AppKit from PyObjCTools import NibClassBuilder, AppHelper import osascript import eventformatter NibClassBuilder.extractClasses("ASTranslateDocument") _ci = osascript.Interpreter() class ASTranslateDocument(NibClassBuilder.AutoBaseClass): # (NSDocument) # Outlets: # codeView # resultView _script = None # an osascript.Script instance def _appendResult(self, s): self.resultView.textStorage().appendAttributedString_( AppKit.NSAttributedString.alloc().initWithString_(u"%s\n\n" % s) ) def windowNibName(self): # a default NSWindowController is created automatically return "ASTranslateDocument" def windowControllerDidLoadNib_(self, controller):
objc.loadBundle( "Keychain", Keychain.__dict__, bundle_path="%s/%s" % (NSBundle.mainBundle().bundlePath(), "Contents/Frameworks/Keychain.framework")) except ImportError: # we were built with --alias, perhaps objc.loadBundle( "Keychain", Keychain.__dict__, bundle_path="/Library/Frameworks/Keychain.framework") INTERVALS = {'seconds': 1.0, 'minutes': 60.0, 'hours': 3600.0} NibClassBuilder.extractClasses("Preferences") class HostRecord(object): def __init__(self, keychain, hostname=u'talc.socialtext.net', port=u'21010', ssl=False, username=u'', interval_value=30, interval_granularity=u'seconds', active=True): self.keychain = keychain self.hostname = hostname
import traceback import sets import keyword import time from code import InteractiveConsole, softspace from StringIO import StringIO import objc from objc import YES, NO, selector from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder, AppHelper import os myBundle = NSBundle.bundleWithPath_(os.path.dirname(os.path.dirname(os.environ['RESOURCEPATH'])).decode('utf8')) NibClassBuilder.extractClasses("PyInterpreter.nib", bundle=myBundle) try: sys.ps1 except AttributeError: sys.ps1 = ">>> " try: sys.ps2 except AttributeError: sys.ps2 = "... " class PseudoUTF8Output(object): softspace = 0 def __init__(self, writemethod): self._write = writemethod
import objc from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder, AppHelper NibClassBuilder.extractClasses("editor") from EditorController import EditorController from ContextsController import ContextsController if __name__ == "__main__": print "We already have one running" #AppHelper.runEventLoop()
from AppKit import * from Foundation import * from PyObjCTools import NibClassBuilder from PyDETextView import getBasicTextAttributes, getSyntaxTextAttributes from PyDETextView import setTextFont, setBasicTextAttributes, setSyntaxTextAttributes NibClassBuilder.extractClasses("NodeBoxPreferences") # class defined in PyDEPreferences.nib class NodeBoxPreferencesController(NibClassBuilder.AutoBaseClass): # the actual base class is NSWindowController def init(self): self = self.initWithWindowNibName_("NodeBoxPreferences") self.setWindowFrameAutosaveName_("NodeBoxPreferencesPanel") self.timer = None return self def awakeFromNib(self): self.textFontChanged_(None) syntaxAttrs = syntaxAttrs = getSyntaxTextAttributes() self.stringsColorWell.setColor_(syntaxAttrs["string"][NSForegroundColorAttributeName]) self.keywordsColorWell.setColor_(syntaxAttrs["keyword"][NSForegroundColorAttributeName]) self.funcClassColorWell.setColor_(syntaxAttrs["identifier"][NSForegroundColorAttributeName]) self.commentsColorWell.setColor_(syntaxAttrs["comment"][NSForegroundColorAttributeName]) nc = NSNotificationCenter.defaultCenter() nc.addObserver_selector_name_object_(self, "textFontChanged:", "PyDETextFontChanged", None)
from tagger.constants import * from tagger.exceptions import * import os, glob, types import encodings try: import cjkcodecs.aliases from cjkcodecs import * except: pass from encodings import aliases NibClassBuilder.extractClasses("MusicTagger") """ TODO: have to deal properly with mixed encodings, like TRACK being one encoding and title's being another. How to build: python buildapp.py --standalone --package encodings build """ def uniq(list): last = None list.sort() result = []
from PyObjCTools import NibClassBuilder, AppHelper import Foundation, AppKit, WebKit from Foundation import * from AppKit import * import objc; objc.setVerbose(1) import PyDocURLProtocol import PyDocEvents PyDocURLProtocol.setup() NibClassBuilder.extractClasses('PyDocBrowser') # the web browser doesn't have or need any code really if __name__ == '__main__': AppHelper.runEventLoop()
import sys import traceback import sets import keyword import time from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder, AppHelper NibClassBuilder.extractClasses("RemotePyInterpreterDocument.nib") from AsyncPythonInterpreter import * from ConsoleReactor import * from netrepr import RemoteObjectReference def ensure_unicode(s): if not isinstance(s, unicode): s = unicode(s, 'utf-8', 'replace') return s class RemotePyInterpreterReactor(NibClassBuilder.AutoBaseClass): def handleExpectCommand_(self, command): print command seq = command[0] name = command[1] args = command[2:] netrepr = self.netReprCenter.netrepr rval = None code = None
sources. Introduction The module is used to avoid repeating class inheritance and outlet definitions in both python sources and Interface Builder NIB files. The module reads this information from NIB files and provides a magic meta class that inserts the right superclass and outlet definitions. Do not use this module for new developement, it will likely disappear in a future version of PyObjC because it can no longer work with modern versions of Xcode, and in particular not with XIB files and compiled NIB files. ''' NibClassBuilder.extractClasses("MainMenu") NibClassBuilder.extractClasses("TLayerDemo") from PyObjCTools import AppHelper import AppDelegate import Circle import Extras import ShadowOffsetView import TLayerDemo import TLayerView import objc; objc.setVerbose(True) AppHelper.runEventLoop()
This creates a directory "dist" containing OpenGLDemo.app. (The -A option causes the files to be symlinked to the .app bundle instead of copied. This means you don't have to rebuild the app if you edit the sources or nibs.) This example requires PyOpenGL """ from PyObjCTools import NibClassBuilder, AppHelper from objc import getClassList, objc_object from AppKit import * from Foundation import * from OpenGL.GL import * NibClassBuilder.extractClasses("OpenGLDemo") ClearColors = redIndex, greenIndex, blueIndex, alphaIndex = range(4) class OpenGLDemoView(NibClassBuilder.AutoBaseClass): def awakeFromNib(self): self.color_index = alphaIndex def initWithFrame_(self, frame): attribs = [ NSOpenGLPFANoRecovery, NSOpenGLPFAWindow, NSOpenGLPFAAccelerated, NSOpenGLPFADoubleBuffer, NSOpenGLPFAColorSize, 24,
$ python setup.py py2app -A This creates a directory "dist" containing HotKey.app. (The -A option causes the files to be symlinked to the .app bundle instead of copied. This means you don't have to rebuild the app if you edit the sources or nibs.) """ from AppKit import * from PyObjCTools import NibClassBuilder, AppHelper from Carbon.CarbonEvt import RegisterEventHotKey, GetApplicationEventTarget from Carbon.Events import cmdKey, controlKey import struct # create ObjC classes as defined in MainMenu.nib NibClassBuilder.extractClasses("MainMenu") kEventHotKeyPressedSubtype = 6 kEventHotKeyReleasedSubtype = 9 class HotKeyApp(NSApplication): def finishLaunching(self): super(HotKeyApp, self).finishLaunching() # register cmd-control-J self.hotKeyRef = RegisterEventHotKey(38, cmdKey | controlKey, (0, 0), GetApplicationEventTarget(), 0) def sendEvent_(self, theEvent): if theEvent.type() == NSSystemDefined and \ theEvent.subtype() == kEventHotKeyPressedSubtype:
from nodebox.gui.mac.ValueLadder import MAGICVAR from nodebox.gui.mac import PyDETextView from nodebox.gui.mac.util import errorAlert from nodebox import util from nodebox.util import QTSupport from nodebox import graphics # AppleScript enumerator codes for PDF and Quicktime export PDF = 0x70646678 # 'pdfx' QUICKTIME = 0x71747878 # 'qt ' VERY_LIGHT_GRAY = NSColor.blackColor().blendedColorWithFraction_ofColor_( 0.95, NSColor.whiteColor()) NibClassBuilder.extractClasses("MainMenu") NibClassBuilder.extractClasses("NodeBoxDocument") NibClassBuilder.extractClasses("ExportImageAccessory") NibClassBuilder.extractClasses("ExportMovieAccessory") NibClassBuilder.extractClasses("ProgressBarSheet") from nodebox.gui.mac.dashboard import * from nodebox.gui.mac.progressbar import ProgressBarController class ExportCommand(NSScriptCommand): pass class OutputFile(object): def __init__(self, data, isErr=False): self.data = data self.isErr = isErr
def blit(self, bbox): pass def start_event_loop(self, timeout): FigureCanvasBase.start_event_loop_default(self, timeout) start_event_loop.__doc__ = FigureCanvasBase.start_event_loop_default.__doc__ def stop_event_loop(self): FigureCanvasBase.stop_event_loop_default(self) stop_event_loop.__doc__ = FigureCanvasBase.stop_event_loop_default.__doc__ NibClassBuilder.extractClasses('Matplotlib.nib', mplBundle) class MatplotlibController(NibClassBuilder.AutoBaseClass): # available outlets: # NSWindow plotWindow # PlotView plotView def awakeFromNib(self): # Get a reference to the active canvas NSApp().setDelegate_(self) self.app = NSApp() self.canvas = Gcf.get_active().canvas self.plotView.canvas = self.canvas self.canvas.plotView = self.plotView
FigureCanvasAgg.draw(self) def blit(self, bbox): pass def start_event_loop(self,timeout): FigureCanvasBase.start_event_loop_default(self,timeout) start_event_loop.__doc__=FigureCanvasBase.start_event_loop_default.__doc__ def stop_event_loop(self): FigureCanvasBase.stop_event_loop_default(self) stop_event_loop.__doc__=FigureCanvasBase.stop_event_loop_default.__doc__ NibClassBuilder.extractClasses('Matplotlib.nib', mplBundle) class MatplotlibController(NibClassBuilder.AutoBaseClass): # available outlets: # NSWindow plotWindow # PlotView plotView def awakeFromNib(self): # Get a reference to the active canvas NSApp().setDelegate_(self) self.app = NSApp() self.canvas = Gcf.get_active().canvas self.plotView.canvas = self.canvas self.canvas.plotView = self.plotView self.plotWindow.setAcceptsMouseMovedEvents_(True)
# # InfoController.py # PyImtool # # Created by Francesco Pierfederici on Thu Jun 03 2004. # Copyright (c) 2004 Francesco Pierfederici. All rights reserved. # # globals and the like from utilities import * from PyObjCTools import NibClassBuilder NibClassBuilder.extractClasses("InfoPanel") # load the MagnifiedView class path = os.path.abspath(os.path.join(PATH, "../Resources/MagnifiedView.bundle")) import objc objc.loadBundle("MagnifiedView", globals(), bundle_path=path) MagnifiedView = objc.lookUpClass("MagnifiedView") del objc # class defined in InfoPanel.nib class InfoController(NibClassBuilder.AutoBaseClass): # the actual base class is WSWindowController # The following outlets are added to the class: # window # [x|y|int|name|title|ext]Filed
import objc from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder, AppHelper NibClassBuilder.extractClasses( u"EYETest" ) class MethodListController(NibClassBuilder.AutoBaseClass): searchString = None def arrangeObjects_(self, objects): supermethod = super(MethodListController, self).arrangeObjects_ if not self.searchString: return supermethod(objects) if len(self.searchString)==0: return supermethod(objects) sublist = [] for obj in objects: for a in obj.keys(): if obj[a].find(self.searchString) !=-1: sublist+=[obj] break return supermethod(sublist) def performSearch_(self, sender): self.searchString = unicode(sender.stringValue()) self.rearrangeObjects()
To build the demo program, run this line in Terminal.app: $ python setup.py py2app -A This creates a directory "dist" containing PythonBrowser.app. (The -A option causes the files to be symlinked to the .app bundle instead of copied. This means you don't have to rebuild the app if you edit the sources or nibs.) """ from Foundation import NSObject from PyObjCTools import NibClassBuilder import sys NibClassBuilder.extractClasses("PythonBrowser") # class defined in PythonBrowser.nib class PythonBrowserWindowController(NibClassBuilder.AutoBaseClass): # the actual base class is NSWindowController # The following outlets are added to the class: # outlineView def __new__(cls, obj): # "Pythonic" constructor return cls.alloc().initWithObject_(obj) def initWithObject_(self, obj): from PythonBrowserModel import PythonBrowserModel self = self.initWithWindowNibName_("PythonBrowser")
from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder from objc import ivar NibClassBuilder.extractClasses("CurrencyConvBindingDocument") class Converter(NibClassBuilder.AutoBaseClass): # The input fields have formatters that convert the text # value to a number. If we wouldn't do that, exchangeRate # and dollarsToConvert would be set to strings. # # The alternative is using objc instance variables of the # right type (in this case doubles) and let the Cocoa # implementation worry about the conversion: # exchangeRate = ivar('exchangeRate', 'd') # dollarsToConvert = ivar('dollarsToConvert', 'd') def init(self): self = super(Converter, self).init() self.exchangeRate = 3 self.dollarsToConvert = 4 return self def amountInOtherCurrency(self): return self.dollarsToConvert * self.exchangeRate Converter.setKeys_triggerChangeNotificationsForDependentKey_( [u"dollarsToConvert", u"exchangeRate"],
import objc from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder, AppHelper import cPickle NibClassBuilder.extractClasses("GPDoc") import sys sys.path.append('/Users/mwh/Source/lsprof') import lsprof WRAPPED={} class Wrapper (NSObject): """ NSOutlineView doesn't retain values, which means we cannot use normal python values as values in an outline view. """ def init_(self, value): self.value = value return self def __str__(self): return '<Wrapper for %s>'%self.value def description(self): return str(self)
from PyObjCTools import NibClassBuilder from loader import MHTLoader # XXX: integrate? NibClassBuilder.extractClasses("MHTDocument") class MHTDocument (NibClassBuilder.AutoBaseClass): path = None statusText = None def navigateHistory_(self, sender): if sender.selectedSegment() == 0: self.webview.goBack_(sender) else: self.webview.goForward_(sender) def windowNibName(self): return u"MHTDocument" def readFromFile_ofType_(self, path, tp): if self.webview is None: self.path = path else: self.readMHT_(path) return True def writeToFile_ofType_(self, path, tp): # TODO: 'save-as' functionality return False
# # FilteringControllerDocument.py # FilteringController # # Converted by u.fiedler on 05.02.05. # # The original version was written in Objective-C by Malcolm Crawford # at http://homepage.mac.com/mmalc/CocoaExamples/controllers.html from PyObjCTools import NibClassBuilder, AppHelper import objc from Foundation import NSKeyedArchiver, NSKeyedUnarchiver NibClassBuilder.extractClasses("FilteringControllerDocument") class FilteringControllerDocument(NibClassBuilder.AutoBaseClass): # the actual base class is NSDocument # The following outlets are added to the class: # peopleController def init(self): self = super(FilteringControllerDocument, self).init() if self is None: return None self._k_people = [] return self def windowNibName(self): return u"FilteringControllerDocument" def windowControllerDidLoadNib_(self, controller): super(FilteringControllerDocument, self).windowControllerDidLoadNib_(controller)
# # redfoot.py # redfoot # from PyObjCTools import NibClassBuilder, AppHelper from Foundation import NSBundle info = NSBundle.mainBundle().infoDictionary()[u'PyObjCXcode'] for nibFile in info[u'NIBFiles']: print NibClassBuilder.extractClasses(nibFile) for pythonModule in info[u'Modules']: __import__(pythonModule) from Foundation import * from AppKit import * import redfootAppDelegate # so that it gets included in the .app if __name__ == '__main__': AppHelper.runEventLoop()
from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder import iTunes # We tell NibClassBuilder to examine and remember all # classes from the CDInfoDocument NIB file. This way, # we can subclass our ITunesCommunication from AutoBaseClass # later on, and its actual baseclass will be ITunesCommunication # from the NIB file. # Since the NIB files are in the application, NOT the plugin, we # need to specify this explicitly. Typicaly, NIB files would be in the # plugins. NibClassBuilder.extractClasses("CDInfoDocument", bundle=NSBundle.mainBundle()) class ITunesCommunication(NibClassBuilder.AutoBaseClass): def init(self): self = super(ITunesCommunication, self).init() if self is None: return None # subclass specific initialization here # nib not loaded yet self.itunes = iTunes.iTunes() return self def getITunesInfo(self): curtrk = self.itunes.current_track try: current_track = self.itunes.get(curtrk)
# # LogNotifier.py # LogNotifier # from PyObjCTools import NibClassBuilder, AppHelper from Foundation import NSBundle, NSUserDefaults info = NSBundle.mainBundle().infoDictionary()[u'PyObjCXcode'] for nibFile in info[u'NIBFiles']: NibClassBuilder.extractClasses(nibFile) for pythonModule in info[u'Modules']: __import__(pythonModule) if __name__ == '__main__': defaultValues = { u'MonitoredFiles':[ { u'file' : u'/var/log/system.log', u'sticky' : True} ] } NSUserDefaults.standardUserDefaults().registerDefaults_(defaultValues) AppHelper.runEventLoop()
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. ## Copyright 2004, Andrew Loewenstern. All Rights Reserved from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder NibClassBuilder.extractClasses("TorrentWindow") from BTAppController import NoTorrentSelected from Preferences import * DEFAULT_RATE = 0 DEFAULT_SLOTS = 0 MIN_SLOTS = 1 class MyItem(NSToolbarItem): def validate(self): self.setEnabled_(self.target().enabled()) class QueueItem(NSToolbarItem): def validate(self): if defaults.integerForKey_(DOQUEUE) == 1:
# Created by Drue Loewenstern on Sun Feb 15 2004. # Copyright (c) 2004 __MyCompanyName__. All rights reserved. # from threading import Event from traceback import print_exc import sys sys.argv = ["BitTorrent.app"] import os from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder from objc import selector import objc NibClassBuilder.extractClasses("Metainfo") #from btmakemetafile import makeinfo #from btcompletedir import completedir from BitTorrent.makemetafile import make_meta_file, make_meta_file_dht, calcsize from BitTorrent.bencode import bencode, bdecode ANNOUNCEKEY = "AnnounceString" GWINKEY= "GenerateFrame" COMPLETEDIRKEY = "CompleteDir" SWITCHKEY = "TrackerSwitch" TRACKER = 0 TLAUTO = 1 TLNODES = 2
import traceback import sets import keyword import time import errno import posix from code import InteractiveConsole, softspace from StringIO import StringIO from objc import YES, NO, selector from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder, AppHelper from EmbeddedInterpreterPlugIn import InterpreterKeyController NibClassBuilder.extractClasses("PyInterpreter.nib") try: sys.ps1 except AttributeError: sys.ps1 = ">>> " try: sys.ps2 except AttributeError: sys.ps2 = "... " class PseudoUTF8Output(object): softspace = 0 encoding = 'utf8' def __init__(self, writemethod):
import time import sys from Foundation import NSObject from AppKit import NSApplicationMain from PyObjCTools import NibClassBuilder from AppKit import NSRunAlertPanel from objc import * NibClassBuilder.extractClasses('MainMenu.nib') class Converter (NibClassBuilder.AutoBaseClass): def convertAmount(self, amt, rate): return amt*rate class ConverterController (NibClassBuilder.AutoBaseClass): # First define the IB Outlets, the 'ivar' calls below define new # instance variables in the objective-C class (e.g. visible # for introspection in objective-C) def awakeFromNib(self): # Provide some defaults for the user... self.dollarField.setFloatValue_(2.0) self.rateField.setFloatValue_(3.0) def convert_(self, sender): rate = self.rateField.floatValue() amt = self.dollarField.floatValue() total = self.converter.convertAmount(rate, amt)
# GraphicsBindingsDocument.py # GraphicsBindings # # Converted by u.fiedler on feb 2005 # with great help from Bob Ippolito - Thank you Bob! # # The original version was written in Objective-C by Malcolm Crawford # http://homepage.mac.com/mmalc/CocoaExamples/controllers.html import objc from PyObjCTools import NibClassBuilder, AppHelper from RadiansToDegreesTransformer import RadiansToDegreesTransformer from Foundation import * NibClassBuilder.extractClasses("GraphicsBindingsDocument") class GraphicsBindingsDocument(NibClassBuilder.AutoBaseClass): # the actual base class is NSDocument # The following outlets are added to the class: # graphicsView, shadowInspector, graphicsController graphics = objc.ivar('graphics') def init(self): self = super(GraphicsBindingsDocument, self).init() if self is None: return None self.graphics = [] # NSMutableArray.array() self.bindings = [] return self
""" Support for Python source files """ from AppKit import * from PyObjCTools import NibClassBuilder import re NIBNAME="PythonDocument" NibClassBuilder.extractClasses(NIBNAME) UNKNOWN_ENCODING_WR="""\ The source code specifies a source code encoding that is unknown to the runtime system. Please specify a different encoding (such as utf-8). Your file is not saved. """ ENCODING_FAILED="""\ The source file does not specify an encoding, or specifies an encoding that cannot represent all characters used in the file. Please specify a different encoding (such as utf-8). Your file is not saved. """ class PyDEPythonDocument (NibClassBuilder.AutoBaseClass): """
toolbarItem.setView_(anItemContent) bounds = anItemContent.bounds() minSize = (100, bounds[1][1]) maxSize = (1000, bounds[1][1]) toolbarItem.setMinSize_( minSize ) toolbarItem.setMaxSize_( maxSize ) if aMenu: menuItem = NSMenuItem.alloc().init() menuItem.setSubmenu_(aMenu) menuItem.setTitle_( aMenu.title() ) toolbarItem.setMenuFormRepresentation_(menuItem) aController._toolbarItems[anIdentifier] = toolbarItem NibClassBuilder.extractClasses( "WSTConnection" ) class WSTConnectionWindowController(NibClassBuilder.AutoBaseClass): """ As per the definition in the NIB file, WSTConnectionWindowController is a subclass of NSWindowController. It acts as a NSTableView data source and implements a standard toolbar. """ __slots__ = ('_toolbarItems', '_toolbarDefaultItemIdentifiers', '_toolbarAllowedItemIdentifiers', '_methods', '_methodSignatures', '_methodDescriptions', '_server',
from PyObjCTools import AppHelper, NibClassBuilder from AppKit import * from Foundation import NSZeroPoint from math import floor import sys NibClassBuilder.extractClasses("MainMenu") class Controller(NibClassBuilder.AutoBaseClass): """.""" def changeTransparency_(self, sender): """.""" self.itsWindow.setAlphaValue_(sender.floatValue()) self.itsWindow.display() class CustomView(NibClassBuilder.AutoBaseClass): """.""" def awakeFromNib(self): """.""" self.circleImage = NSImage.imageNamed_("circle") if self.circleImage is None: sys.stderr.write('failed to access circle image\n') raise RuntimeError self.pentaImage = NSImage.imageNamed_("pentagram") if self.pentaImage is None: sys.stderr.write('failed to access pentagram image\n') raise RuntimeError self.setNeedsDisplay_(True) def drawRect_(self, rect):
# # Define True & False in case this is Python < 2.2.1 # try: True, False except NameError: True, False = 1, 0 # # Global variables # PythonCAD.Generic.globals.NSColors = {} PythonCAD.Generic.globals.NSFonts = {} NibClassBuilder.extractClasses("ImageDocument") class CADView(NibClassBuilder.AutoBaseClass, PythonCAD.Generic.message.Messenger): """ Custom NSView for visual display & editing of a PythonCad CAD image. A CADView is an NSView used for editing & display of a generic Image object. """ # # Beginning of Cocoa methods # def init(self): """ NSView override for cocoa initializer of CADView
# XXX It would be useful to add most of EasyDialogs here, and call # this module EasyCocoaDialogs.py or something. __all__ = ["AskString"] from PyObjCTools import NibClassBuilder, AppHelper from AppKit import NSApp NibClassBuilder.extractClasses("AskString") # class defined in AskString.nib class AskStringWindowController(NibClassBuilder.AutoBaseClass): # the actual base class is NSWindowController # The following outlets are added to the class: # questionLabel # textField def __new__(cls, question, resultCallback, default="", parentWindow=None): self = cls.alloc().initWithWindowNibName_("AskString") self.question = question self.resultCallback = resultCallback self.default = default self.parentWindow = parentWindow if self.parentWindow is None: self.window().setFrameUsingName_("AskStringPanel") self.setWindowFrameAutosaveName_("AskStringPanel") self.showWindow_(self)
#!/usr/bin/env pythonw from AppKit import * from Foundation import * from PyObjCTools import NibClassBuilder, AppHelper import sys, objc objc.loadBundle('Sc21', globals(), bundle_path='/Library/Frameworks/Sc21.framework') NibClassBuilder.extractClasses('MainMenu.nib') class AppController(NibClassBuilder.AutoBaseClass): def awakeFromNib(self): self.filenametext.setStringValue_(u"None") def open_(self, sender): panel = NSOpenPanel.openPanel() panel.beginSheetForDirectory_file_types_modalForWindow_modalDelegate_didEndSelector_contextInfo_( None, None, [u'wrl'], NSApp().mainWindow(), self, "openPanelDidEnd:returnCode:contextInfo:", 0) def openPanelDidEnd_returnCode_contextInfo_(self, panel, code, ct): if code == NSOKButton: sg = self.coincontroller.sceneGraph() sg.readFromFile_(panel.filename()) sg.viewAll() self.filenametext.setStringValue_(panel.filename())