TinyTinyEdit

A minimal document-based text editor application.

Sources

TinyTinyEdit.py

"""TinyTinyEdit -- A minimal Document-based Cocoa application."""

import objc
import Cocoa
from PyObjCTools import Signals
from PyObjCTools import AppHelper

class TinyTinyDocument(Cocoa.NSDocument):
    textView = objc.IBOutlet()
    path = None

    def windowNibName(self):
        return "TinyTinyDocument"

    def readFromFile_ofType_(self, path, tp):
        if self.textView is None:
            # we're not yet fully loaded
            self.path = path
        else:
            # "revert"
            self.readFromUTF8(path)
        return True

    def writeToFile_ofType_(self, path, tp):
        with open(path, "w") as f:
            text = self.textView.string()
            if sys.version_info[0] == 2:
                text = text.encode('utf-8')
            f.write(text)
        return True

    def windowControllerDidLoadNib_(self, controller):
        if self.path:
            self.readFromUTF8(self.path)

    def readFromUTF8(self, path):
        with open(path, 'r') as f:
            text = f.read()

        if sys.version_info[0] == 2:
            text = text.decode('utf-8')
        self.textView.setString_(text)


if __name__ == "__main__":
    AppHelper.runEventLoop()

setup.py

"""
Script for building the example.

Usage:
    python3 setup.py py2app
"""
from setuptools import setup

plist = dict(
    CFBundleDocumentTypes = [
        dict(
            CFBundleTypeExtensions=["txt", "text", "*"],
            CFBundleTypeName="Text File",
            CFBundleTypeRole="Editor",
            NSDocumentClass="TinyTinyDocument",
        ),
    ]
)

setup(
    name="Tiny Tiny Edit",
    app=["TinyTinyEdit.py"],
    data_files=["MainMenu.nib", "TinyTinyDocument.nib"],
    options=dict(py2app=dict(plist=plist)),
    setup_requires=[
        "py2app",
        "pyobjc-framework-Cocoa",
    ]
)

Resources