# 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)
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 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):
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)
# # 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()
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()
# # 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):
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 = []
# 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 = []
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,
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()
import AddressBook except ImportError: pass try: import PreferencePanes except ImportError: pass try: import InterfaceBuilder except ImportError: pass NibClassBuilder.extractClasses("ClassBrowser") def _sortClasses(classList): classes = [(cls.__name__, cls) for cls in classList] classes.sort() return [cls for name, cls in classes] # class defined in ClassBrowser.nib class ClassBrowserDelegate(NibClassBuilder.AutoBaseClass): # the actual base class is NSObject # The following outlets are added to the class: # browser # pathLabel # table
# 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/>. from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder from BTAppController import NoTorrentSelected from BitTorrent.ClientIdentifier import identify_client as client from utils import * NibClassBuilder.extractClasses("DetailView") f = open('/tmp/unknown_clients', 'wb') def spewval(d, v): if v == 'ip': return d['ip'] elif v == 'cl': return "%s %s" % client(d['id'], f) elif v == 'lr': return d['initiation'][0] elif v == 'ui': if d['completed'] == 1.0: return '-' elif d['upload'][2]:
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
from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder from appscript import * # 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 return self def getITunesInfo(self): try: track = app('iTunes.app').current_track.get() except Exception: NSRunAlertPanel( u'iTunes Communication Error', u'iTunes failed to return the current track',
See also the iClass demo. """ from PyObjCTools import NibClassBuilder, AppHelper import objc from objc import getClassList, objc_object from Foundation import * from AppKit import * import os myBundle = NSBundle.bundleWithPath_( os.path.dirname(os.path.dirname( os.environ['RESOURCEPATH'])).decode('utf8')) NibClassBuilder.extractClasses("ClassBrowser.nib", bundle=myBundle) def _sortClasses(classList): classes = [(cls.__name__, cls) for cls in classList] classes.sort() return [cls for name, cls in classes] # class defined in ClassBrowser.nib class ClassBrowserDelegate(NibClassBuilder.AutoBaseClass): # the actual base class is NSObject # The following outlets are added to the class: # browser # pathLabel # table
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()
# # 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()
STALLEDCOLOR_DEFAULT = NSArchiver.archivedDataWithRootObject_( NSColor.colorWithCalibratedHue_saturation_brightness_alpha_( .166, .3, 1.0, 1.0)) ERRORCOLOR_DEFAULT = NSArchiver.archivedDataWithRootObject_( NSColor.colorWithCalibratedHue_saturation_brightness_alpha_( 1.0, .10, 1.0, 1.0)) VERSIONCHECK_DEFAULT = 1 from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder import objc import os NibClassBuilder.extractClasses("Preferences") appDefaults = { IP: IP_DEFAULT, MINPORT: MINPORT_DEFAULT, MAXULS: MAXULS_DEFAULT, MINULS: MINULS_DEFAULT, MAXULRATE: MAXULRATE_DEFAULT, DIRASK: DIRASK_DEFAULT, DLDIR: DLDIR_DEFAULT, MAXINITIATE: MAXINITIATE_DEFAULT, MAXACCEPT: MAXACCEPT_DEFAULT, DOQUEUE: DOQUEUE_DEFAULT, QUEUESTOP: QUEUESTOP_DEFAULT, STOPRATIO: STOPRATIO_DEFAULT, STOPTIME: STOPTIME_DEFAULT, QUEUESTART: QUEUESTART_DEFAULT,
# 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
# # 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 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)
work = self.queue.get() if work is None or not self.working: break func, args, kwargs = work pool = NSAutoreleasePool.alloc().init() try: func(*args, **kwargs) finally: # delete all local references; if they are the last refs they # may invoke autoreleases, which should then end up in our pool del func, args, kwargs, work del pool from PyObjCTools import NibClassBuilder 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',
"""ASTranslate""" import AppKit from PyObjCTools import NibClassBuilder, AppHelper from Foundation import NSUserDefaults import MacOS import osascript, aem import eventformatter import rubyrenderer, objcrenderer NibClassBuilder.extractClasses("MainMenu") NibClassBuilder.extractClasses("ASTranslateDocument") _ci = osascript.Interpreter() ####### _userDefaults = NSUserDefaults.standardUserDefaults() if not _userDefaults.integerForKey_(u'defaultOutputLanguage'): _userDefaults.setInteger_forKey_(0, u'defaultOutputLanguage') ####### class ASApplicationDelegate(NibClassBuilder.AutoBaseClass): pass
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")
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()
# 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
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_(
from bisect import bisect import re import objc from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder from nodebox.util.PyFontify import fontify from nodebox.gui.mac.ValueLadder import ValueLadder whiteRE = re.compile(r"[ \t]+") commentRE = re.compile(r"[ \t]*(#)") NibClassBuilder.extractClasses("NodeBoxDocument") def findWhitespace(s, pos=0): m = whiteRE.match(s, pos) if m is None: return pos return m.end() stringPat = r"q[^\\q\n]*(\\[\000-\377][^\\q\n]*)*q" stringOrCommentPat = stringPat.replace("q", "'") + "|" + stringPat.replace( 'q', '"') + "|#.*" stringOrCommentRE = re.compile(stringOrCommentPat) def removeStringsAndComments(s): items = [] while 1:
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)
# Bookmarks # # Converted by u.fiedler on 10.02.05. # # The original version was written in Objective-C by Malcolm Crawford # at http://homepage.mac.com/mmalc/CocoaExamples/controllers.html import objc from PyObjCTools import NibClassBuilder from Foundation import * # BookmarksDocument defines this as it may be used for copy and paste # in addition to just drag and drop CopiedRowsType = u"COPIED_ROWS_TYPE" NibClassBuilder.extractClasses("BookmarksDocument") class BookmarksDocument(NibClassBuilder.AutoBaseClass): # the actual base class is NSDocument # The following outlets are added to the class: # window??? is connected in IB but can not be accessed? bookmarksArray = objc.ivar('bookmarksArray') def init(self): self = super(BookmarksDocument, self).init() if self is None: return None self.bookmarksArray = NSMutableArray.array() return self
from PyObjCTools import NibClassBuilder from CoreData import * from AppKit import * NibClassBuilder.extractClasses("MyDocument") prioritySortDescriptions = NSArray.arrayWithObject_( NSSortDescriptor.alloc().initWithKey_ascending_("value", True)) class MyDocument(NibClassBuilder.AutoBaseClass): def initWithType_error_(self, tp, error): self, error = super(MyDocument, self).initWithType_error_(tp, error) if self is None: return (None, error) managedObjectContext = self.managedObjectContext() for aPriorityValue in range(5): aPriority = NSEntityDescription.insertNewObjectForEntityForName_inManagedObjectContext_( "Priority", managedObjectContext) aPriority.setValue_forKey_(aPriorityValue + 1, "value") NSEntityDescription.insertNewObjectForEntityForName_inManagedObjectContext_( "Note", managedObjectContext) managedObjectContext.processPendingChanges() managedObjectContext.undoManager().removeAllActions() self.updateChangeCount_(NSChangeCleared) return (self, None)
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)
import PythonCAD.Generic.circle import PythonCAD.Generic.leader import PythonCAD.Generic.polyline import PythonCAD.Generic.segjoint import PythonCAD.Generic.conobject import PythonCAD.Generic.baseobject import PythonCAD.Generic.dimension import PythonCAD.Generic.units import PythonCAD.Interface.Cocoa.ImageDocument import PythonCAD.Interface.Cocoa.CADView import PythonCAD.Interface.Cocoa.AppController from PyObjCTools import NibClassBuilder, AppHelper #Initialize NIB NibClassBuilder.extractClasses("ImageDocument") # # set up global variables ... # PythonCAD.Generic.globals.prefs = PythonCAD.Generic.baseobject.LockedDict(str) PythonCAD.Generic.globals.colors = PythonCAD.Generic.baseobject.TypedDict( PythonCAD.Generic.color.Color, PythonCAD.Generic.color.Color) PythonCAD.Generic.globals.linetypes = PythonCAD.Generic.baseobject.TypedDict( PythonCAD.Generic.linetype.Linetype, PythonCAD.Generic.linetype.Linetype) PythonCAD.Generic.globals.styles = PythonCAD.Generic.baseobject.TypedDict( PythonCAD.Generic.style.Style, PythonCAD.Generic.style.Style) PythonCAD.Generic.globals.dimstyles = [] PythonCAD.Generic.globals.selectobj = PythonCAD.Generic.selections.Selection()
# # 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)
from AppKit import * from Foundation import * from PyObjCTools import NibClassBuilder, AppHelper NibClassBuilder.extractClasses('MainMenu.nib') NibClassBuilder.extractClasses('PreferenceWindow.nib') NibClassBuilder.extractClasses('MyDocument.nib') from PreferencesWindowController import * from MyDocument import * from LaunchServices import * PYTHON_EXTENSIONS = [u'py', 'pyw', u'pyc'] FILE_TYPE_BINDING_MESSAGE = u""" %s is not the default application for all Python script types. You should fix this with the Finder's "Get Info" command. See "Changing the application that opens a file" in Mac Help for details. """.strip() class MyAppDelegate(NibClassBuilder.AutoBaseClass): def init(self): self = super(MyAppDelegate, self).init() self.initial_action_done = False self.should_terminate = False return self def showPreferences_(self, sender): PreferencesWindowController.getPreferencesWindow() def applicationDidFinishLaunching_(self, aNotification):
import sys import traceback import sets import keyword import time 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 NibClassBuilder.extractClasses("PyInterpreter.nib") 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 def write(self, s):
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
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)
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()
# 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:
"""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):
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):
def draw_if_interactive(): if matplotlib.is_interactive(): figManager = Gcf.get_active() if figManager is not None: figManager.show() class FigureCanvasCocoaAgg(FigureCanvasAgg): def draw(self): FigureCanvasAgg.draw(self) def blit(self, bbox): pass 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
from PyObjCTools import NibClassBuilder, AppHelper NibClassBuilder.extractClasses('MainMenu.nib') import CGraphController AppHelper.runEventLoop()
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()
# 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
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
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',
""" 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): """
# # 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
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):
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])
# 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/>. from Foundation import * from AppKit import * from PyObjCTools import NibClassBuilder from BTAppController import NoTorrentSelected from time import asctime, localtime NibClassBuilder.extractClasses("MainMenu") class LogController(NibClassBuilder.AutoBaseClass): def awakeFromNib(self): NSNotificationCenter.defaultCenter().addObserver_selector_name_object_( self, self.incomingError, "DLControllerError", None) NSNotificationCenter.defaultCenter().addObserver_selector_name_object_( self, self.selectionChanged, "TorrentSelectionChanged", None) def selectionChanged(self, note): self.logView.reloadData() self.logView.sizeToFit() self.logView.scrollRowToVisible_(self.logView.numberOfRows() - 1) def incomingError(self, note):
"""TinyTinyEdit -- A minimal Document-based Cocoa application.""" import sys print 'PATH', sys.path import urllib import amiscore import os import sys from PyObjCTools import NibClassBuilder, AppHelper NibClassBuilder.extractClasses("AmisGuiDocument") # class defined in AmisGuiDocument.nib class AmisGuiDocument(NibClassBuilder.AutoBaseClass): # the actual base class is NSDocument # The following outlets are added to the class: # textView path = None def init(self): self.dtb = amiscore.Dtb() self.bmkdir = os.path.join(os.getenv("HOME"), "bmk") self.curphrase = None def windowNibName(self): return "AmisGuiDocument" def readFromFile_ofType_(self, path, tp): print 'readFromFile', path, tp
# This overrides PyObjC detection in ForgeryCommon, so that the # wxPython version can be used on a Mac. Set it to True to enable # the override, or False to disable it. __builtin__.preferWX = False from ForgeryCommon import * if usePyObjC: from PyObjCTools import NibClassBuilder, AppHelper from Foundation import NSBundle info = NSBundle.mainBundle().infoDictionary()[u'PyObjCXcode'] for nibFile in info[u'NIBFiles']: NibClassBuilder.extractClasses(nibFile) del nibFile for pythonModule in info[u'Modules']: __import__(pythonModule) del pythonModule del info import ForgeryApplication, ForgeryCursor def main(): if usePyObjC: ForgeryCursor.initCursors() AppHelper.runEventLoop()
""" Example showing screen saver in PyObjC Based on "Silly Balls.saver" by Eric Peyton <*****@*****.**> http://www.epicware.com/macosxsavers.html """ import objc from AppKit import NSBezierPath, NSColor from ScreenSaver import * from random import random, randrange from PyObjCTools import NibClassBuilder NibClassBuilder.extractClasses("SillyBalls") class SillyBalls (NibClassBuilder.AutoBaseClass): def animateOneFrame(self): # choose a random point. (x, y), (fw, fh) = self.frame() x, y = randrange(0.0, fw), randrange(0.0, fw) ballSize = randrange(10.0, 90.0) path = NSBezierPath.bezierPathWithOvalInRect_(((x, y), (ballSize, ballSize))) # make a random color. randomColor = NSColor.colorWithCalibratedRed_green_blue_alpha_(random(), random(), random(), random()) # set it. randomColor.set()