book covers

Indie macOS Dev Bundle, Swift 3 Ed..

Design solid applications and own your distribution process. Learn software architecture principles to make your Swift apps easier to maintain and extend. Set up your app for sale, with a trial mode and license generation all set. Including fully functional sample projects and code templates for your app.

The Archive Is Available Now

My next macOS app project has launched: It’s a note-taking app for macOS to help writers write more. In our typical German stoic way, we just call it The Archive.

Check out The Archive!

Its choice of features is closely tied to a few core principles: the user is more important than your app; plain text comes first, so avoid proprietary features and vendor lock-in, thus furthering replicability of the workflow in other apps. I guess we’ll write more about that in the future.

I’m collecting reactions from all around the web already on Pinboard.

Backstage Info

A few details of potential interest to programmers, taken from our Press Kit:

NSTextView’s Default Insertion Point and Selected Text Colors

NSTextView can be customized to display different colors for the insertion point (aka caret, aka text cursor) and for selected text. This is especially useful when you add themes to your editor and the default settings don’t fit anymore.

3 theme settings visualized

The default values are not exposed anywhere, so I had to log them and reconstruct convenient accessors to reset a text view if needed:

extension NSTextView {
    static var defaultInsertionPointColor: NSColor { 
        return NSColor.controlTextColor 

    static var defaultSelectedTextAttributes: [NSAttributedStringKey : Any] {
        return [
            .foregroundColor: NSColor.selectedTextColor,
            .backgroundColor: NSColor.selectedTextBackgroundColor

Launch of My Next App, The Archive

screenshot of The Archive

I spent the last 15 or so months developing this beast. If you follow my ramblings, you will know that I get to work every day at about 7 a.m. and work until about 5:30 p.m., including workouts and breaks. Since I didn’t use a time tracker like Timing for most of the time, I cannot say how many hours I really spent coding, sadly.

Anyway. The launch. The Archive will go live March 15th. I’ll publicize the app info page, soon.

And then I’ll spend some leisure time writing a postmortem. The beta testers have been a pleasure to work with, as always. It’s amazing how much love strangers are willing to give for carefully crafted products.

This closes a weird circle for me: my first Cocoa coding experience was adding Markdown preview to Notational Velocity in 2010, which I barely managed, having had zero understanding of Objective-C and how Xcode worked. Now I am able to create an app that exceeds NV’s capabilities all on my own. I’m very happy about this coding journey, and oh boy do I have a lot of cool stuff I am going to add after v1.0 goes live!

How I Avoided Over-Architecting a Simple Event Handler with ReSwift, Cheating with Existing Reactive Code

I am using ReSwift in my app. I like ReSwift because I can create a representation of my app in a “State” Swift module without any UIKit/AppKit dependency. There, I put all the data that the app is supposed to represent at any given moment in time.

To get a feeling for this, have a look at two apps of mine:

Screenshot of TableFlip
A document in TableFlip with a single table in it

In case of my app TableFlip, this means, simplified: the two-dimensional tabular data of all tables in the current document; a pointer to the currently visible table (i.e., which tab is active); and the user selection measured in rows and columns.

Screenshot of The Archive
The Archive in its pre-release form

In my more recent project, The Archive, the state includes: user preferences, including the path to the directory of notes; a list of all files that match the current search, to be shown in the list to the list; the text of the currently displayed note; the contents of the Omnibar (the search field at the top); temporary pending file changes, like saving, if any.

You see, part of the app state is a representation of what the user is supposed to be looking at. Not every static label description, but the changing parts.

To change the state, you dispatch actions. I like to phrase them in effect form: CreatingNote, ChangingArchiveDirectory, AddingTableRow, etc. The ReSwift framework expects you to write reducers that take in actions and the current state and update the state accordingly. It’s pretty simple input–output, really. In the end, your app fires these actions and your state subscribers receive a state update.

This is all fine and dandy. But sometimes I catch myself adding actions only to enqueue side-effects. I wrote about enqueuing file changes last year. I’m still not unhappy with that approach, but I am having doubts now. In essence, I figured that storing a string to a URL is part of the backstage state of the app. “The app is saving a file” sounds like a good sub-state description to me.

Why do I doubt that now?

Yesterday, I added a pretty simple functionality. The Archive is a macOS app, so it has a main menu. From the main menu, you should be able to insert a date-time string like 201803041008 for “2018-03-04 10:08”, which is supposed to be an identifier for a note. This would be a simple UI helper concern to set up and use a DateFormatter. But I want to avoid duplicates. You get 1 ID per minute with this setting. To keep them unique, the app should figure out if you used the ID to permanently identify a note already. If you are too quick and want to assign multiple IDs to notes in one minute, the app should take care of giving you a different, unused number. This requires knowledge about the state, though: which ID is free?

I do have services outside the UI layer that take care of this. They determine if an ID is taken in the archive of notes, and I can obtain a fixed ID in return. Easy.

But how should I wire the menu item to this service and then insert it at the current cursor position in the editor’s NSTextView? The UI layer is not allowed to reach outside its confines.

The way my app architecture is handles all user events is through ReSwift actions. The UI, treated as a I/O black box, exposes a list of events an event handler subscribes to. Like the existing “Save Note Changes” and “Select Note”, this new event would be called “Request Identifier”. Only this time, it doesn’t affect the state at all. Requesting an identifier is a process that depends on the state to figure out which ID is free, but it does not modify the state. Its only effect is “Typing ‘201803041008’ Into The Text Field”. This effect is not a great candidate for ReSwift states, though. I do not route key presses from the user through state updates. They remain enclosed in the UI layer. Only periodically do changes to the text get propagated. I didn’t want to write a terminal emulator, I want to use the Cocoa framework to build an app, so this still sounds reasonable to me. To enqueue typing an unused ID into the text field in the state makes no sense.

Still, I was tempted. After all, the state module is the trustworthy, functional, well-tested core of the app’s operation. This is an event that takes place. Why not put the request and its result into the state like all the other events?

Keep in mind that both request and response need to be put into the ReSwift state if you use the state object as your message bus: store the user-originated event as a request object (RequestingTypingID), subscribe to these somewhere, send back a completion to delete the pending request (CompletingIDRequest), and send a the result that’s supposed to be typed into the text field (TypingText("201803041008")) which another subscriber processes, only this time it’s operating like a presenter and knows the UI. Mixing both subscribers and both processes into one would work but that’s not good factoring.

Instead of all this, I realized I have another event queue at my disposal apart from ReSwift: RxSwift. I use this reactive library to wire components together and use it a lot inside the UI (or “Presentation”) layer. There’s a lot less overhead in exposing event streams with RxSwift, as it is designed exactly for this purpose, while ReSwift is more concerned with the state representation through events.

The benefit of event queues, both through the monolithic state update of ReSwift or the individual observable sequences of Rx, is decoupling.

event queue illustration
The event queue decouples event origins from event effects

That’s the basic proposition of the Observer pattern. It’s what makes NSNotification so useful sometimes. I want to emit an event from the menu item (Presentation layer) to be processed by a service object with access to knowledge about existing identifiers (Application layer) so that the result gets typed into the editor. Since I do not inject delegates or other event handlers into the UI in this app but instead expose observable streams, continuing on this path was the natural choice:

  • The UI exposes requestIdentifier: Observable<Void>; this could work the same way but non-reactively using a delegate. Note it doesn’t pass any info around, it’s just a signal.
  • I inject something like a GenerateIdentifier service into my wireframe object. That’s the thing that connects presenters to the UI, and the UI to action dispatchers. This GenerateIdentifier is just a new dependency it expects.
  • The wireframe thingie subscribes GenerateIdentifier.generateID(), which returns a string, to requestIdentifier events. Now each request is transformed into a string, if the request didn’t produce errors, that is.
  • I can consume these and forward them to the UI through the TypesText protocol. It is implemented, in shortened form, as: (window?.firstResponder as? NSText)?.insertText(string).

What did I do here?

  1. I maintained the strict separation of UI and knowledge about the note repository through an Application Service: GenerateIdentifier.
  2. I extended the wireframe to perform another wiring of action and response, building on top of the existing set-up.
  3. I did not use ReSwift as a general purpose message bus.

This case made me re-think my approach to saving note changes, too. Please note that I don’t say file changes, because a file is not part of my application’s problem domain. It’s only the final representation of the data through the persistence layer. One thing I do find useful, though, is that I can configure my ReSwift setup to react to note changes with more side-effects, like updating the displayed contents. I have to think about the cost and payoff some more.

I’m happy that I did figure out how to not increase the core State module’s capabilities for such a mundane task. It’s a mere side-effect that’s not affecting the state at all. In my book, it’s good to keep the core small and push all the bloat out into the less pure layers of the app. They’re easier to replace and modify since they don’t affect other modules.

I’m also happy with this particular solution because I avoided over-engineering a simple UI event as a series of actions and transient state updates.

I’m not happy about the diversion in event handling processes, though. This is a precedence for future code to look the same. Will I avoid dispatching ReSwift actions because of the overhead and because, well, there’s this one thing that doesn’t use it, either? Probably. This indicates I have to re-think this pretty old core concept of my app. It’ll be time for a serious refactoring, now that I know better how to approach the problem the app is trying to solve.

Behind the Scenes of Programming ‘The Archive’: How Much Coffee Did I Consume?

When I announced the imminent launch of my latest app project, The Archive, a beta tester asked how many jars of coffee I consumed while coding.

Jar” is no mistake. I drink from a 750ml glass jar, full to the brim. That’s one portion of cowboy coffee, or is it turkish coffee? – I’m not quite sure what to call it: grind the beans, pour water, stir from time to time, let it settle, then drink.

I can tell you the theoretical maximum of jars of coffee during development since I only allow myself 1 jar on Wednesdays and Saturdays, if I drink coffee at all on these days.

  • 15 months of development
  • 4.25 weeks per month
  • max 2 days per week where 1 jar of coffee is allowed

Thats 127.5 jars of coffee.

A jar holds a bit more than 0.75 liters. That results in ~95 liters over 15 months. For each jar, I grind about 1 1/2 tablespoons of coffee beans. I did drink coffee at about 7 a.m. on days of intermittent fasting: I don’t eat before 6 p.m. on these days, so the strong brew strikes hard and has a long-lasting effect.

At the moment, I don’t need the crazy energy to amp up my programming. I’m just wrapping up the release, so I switched to decaf. Because I don’t always allow myself hot beverages, but when I do, it should be strong and bitter.

NSTextView: When Did the Find Bar Disappear?

For whatever reason, my current app project’s find bar does not make the text view firstResponder again when you hit Escape or click the “Done” button to close it. This is very uncomfortable for users: they type away, hit ⌘F to find a phrase, then hit Esc – and now they’re in limbo.

To my astonishment, the NSTextFinderAction called hideFindInterface is not triggered when you make the find bar disappear. Its opposite, showFindInterface, is triggered when the find bar slides back in, though. Intercepting in NSTextView.performTextFinderAction(_:) does not help, then.

I embed my text view in a NSScrollView, which conforms to NSTextFinderBarContainer. There, you have a mutable (!) isFindBarVisible property. Since it’s mutable, you can write a Swift property observer in a subclass:

class MyScrollView: NSScrollView {
    override var isFindBarVisible: Bool {
        didSet {
            if oldValue == false && isFindBarVisible == true {
                // find bar is closed

You can also use key–value-observation for this property if you want to avoid the subclass.

I am also using RxSwift in this project, so writing a KVO property observer is as “simple” as this:

class AmazingViewController: NSViewController {

    @IBOutlet var textView: NSTextView!
    @IBOutlet var scrollView: NSScrollView!

    fileprivate let disposeBag = DisposeBag()

    override func viewDidLoad() {

    fileprivate func wireFindBarDisappearanceToCursorFocus() {

        scrollView.rx.observe(Bool.self, "findBarVisible")
            .filterNil()  // from RxOptional
            .skip(1)      // Don't need the initial value
            .map { !$0 }  // So I don't have to write `!didBecomeVisible`
            .asDriver(onErrorJustReturn: false)
            .drive(onNext: { [weak self] didDisappear in
                guard didDisappear else { return }
            .disposed(by: disposeBag)

// I was tired of unwrapping all the view?.window?.makeFirstResponder(view) calls:
extension NSView {
    func makeFirstResponder() {

This helps. But I don’t trust all this NSTextFinder related stuff, I admit. It’s a bit too finicky for my taste, overall.

Exposing the MultiMarkdown 6 Library to Swift, Part 1: Swifty Enums

During the time between Christmas and New Year, which we tend to call the time “between the years” where I live in Germany, I wanted to do something fun, but not too fun so I don’t get spoiled.

That’s how I turned up experimenting to use libMultiMarkdown from within a Swift app. The amount of fun I have when reading and writing C code is negligible, which made it a perfect fit.

And, frankly, I think using the official MultiMarkdown library is a good approach to perform proper syntax highlighting in an editor. Much better than my home-brewed stuff can ever be. While writing a “minimum viable” Markdown highlighter yourself is pretty easy, the edge cases are aplenty, and the long term maintenance overhead is too big for my taste. So I really don’t want to bother making my own highlighter useful much longer and switch to a better, more performant solution.

Getting the current MultiMarkdown 6 project to generate an Xcode project with a local build directory and output the library header file in the first place was a bit of a chore. More about that some other day.

Exposing the token types as enums

In the wild west of C code, you end up with a header file with free functions. Calling these from Swift is straightforward. More bewildering to use are the enums which you need to do anything with the resulting tokens. They look innocent enough, like this:

enum token_types {
    DOC_START_TOKEN = 0,    //!< DOC_START_TOKEN must be type 0

    BLOCK_BLOCKQUOTE = 50,        //!< This must start *after* the largest number in parser.h
    BLOCK_HEADING,                //!< Placeholder for theme cascading
    BLOCK_H1,                    //!< Leave H1, H2, etc. in order
    // ...

But the resulting Swift code is very noisy because these C enum cases are exported as root-level constants, and the resulting types don’t even match Swift’s expectations, so you have tons of type casts:

let token: UnsafeMutablePointer<token> = // ...
switch token.pointee.type {
case UInt16(BLOCK_BLOCKQUOTE.rawValue): // ...
case UInt16(BLOCK_DEFLIST.rawValue): // ...
default: break

We get useful Swift enums when we use NS_ENUM in Objective-C. Since libMultiMarkdown is not a Swift module but a C library, I think a proper NS_ENUM in Objective-C is a good start. With that in place, you can use it from both Objective-C and Swift.

The expected code would look like this:

typedef NS_ENUM(NSUInteger, MMD6TokenType) {
    MMD6TokenTypeDocStartToken = DOC_START_TOKEN,
    MMD6TokenTypeBlockBlockquote = BLOCK_BLOCKQUOTE,
    MMD6TokenTypeBlockCodeFenced = BLOCK_CODE_FENCED,
    MMD6TokenTypeBlockCodeIndented = BLOCK_CODE_INDENTED,
    MMD6TokenTypeBlockDeflist = BLOCK_DEFLIST,
    MMD6TokenTypeBlockDefinition = BLOCK_DEFINITION,
    MMD6TokenTypeBlockDefAbbreviation = BLOCK_DEF_ABBREVIATION,
    MMD6TokenTypeBlockDefCitation = BLOCK_DEF_CITATION,
    MMD6TokenTypeBlockDefGlossary = BLOCK_DEF_GLOSSARY,
    MMD6TokenTypeBlockDefFootnote = BLOCK_DEF_FOOTNOTE,
    MMD6TokenTypeBlockDefLink = BLOCK_DEF_LINK,
    MMD6TokenTypeBlockEmpty = BLOCK_EMPTY,
    MMD6TokenTypeBlockHeading = BLOCK_HEADING,
    MMD6TokenTypeBlockH1 = BLOCK_H1,
    MMD6TokenTypeBlockH2 = BLOCK_H2,
    MMD6TokenTypeBlockH3 = BLOCK_H3,
    MMD6TokenTypeBlockH4 = BLOCK_H4,
    // ...
} NS_SWIFT_NAME(TokenType);

I wrote a Ruby script to generate the header file code for this.

Note about type names: In C, it makes sense to pluralize the enum’s name, as in token_types, because it reads like a grouping; when you prefix the NS_ENUM cases with the type name, you drop it, because you address the case individually, not like a collection: MMD6TokenTypeBlockHeading, not MMD6TokenTypesBlockHeading. In Swift, you don’t pluralize enum type names, either, using TokenType.blockHeading and passing tokenType: TokenType parameters around, not tokenTypes: TokenTypes, which again read like collections. So the plural S needs to be dropped. The script has brittle hard-coded depluralization built in.

Get the code generator as a Gist.

Run the generator like this to generate the NS_ENUM code:

ruby cocoaconv.rb path/to/libMultiMarkdown.h

You can also generate better readable Swift enum case descriptions:

ruby cocoaconv.rb -m swift path/to/libMultiMarkdown.h

The latter will print out code like the following:

extension TokenType: CustomStringConvertible {
    public var description: String {
        switch self {
            case .docStartToken: return "TokenType.docStartToken"
            case .blockBlockquote: return "TokenType.blockBlockquote"
            case .blockCodeFenced: return "TokenType.blockCodeFenced"
            case .blockCodeIndented: return "TokenType.blockCodeIndented"
            case .blockDeflist: return "TokenType.blockDeflist"
            case .blockDefinition: return "TokenType.blockDefinition"
            case .blockDefAbbreviation: return "TokenType.blockDefAbbreviation"
            case .blockDefCitation: return "TokenType.blockDefCitation"
            case .blockDefGlossary: return "TokenType.blockDefGlossary"
            case .blockDefFootnote: return "TokenType.blockDefFootnote"
            case .blockDefLink: return "TokenType.blockDefLink"
            case .blockEmpty: return "TokenType.blockEmpty"
            case .blockHeading: return "TokenType.blockHeading"
            // etc.

Maybe this’ll make its way into the code repository. I’m working on a series of Pull Requests right now to make the library more accessible for Cocoa developers, both Objective-C and Swift.

Using the new enums in a Cocoa project

With the power of my script, these are the steps you need to perform:

  1. Generate the NS_ENUM code,
  2. Store it in a .h file in your project (e.g. MMD6Enums.h),
  3. Add the following to the top of the file:
#import <Foundation/Foundation.h>
#import <libMultiMarkdown/libMultiMarkdown.h>
#import <libMultiMarkdown/token.h>
#import <libMultiMarkdown/d_string.h>

If you’re not coding in Objective-C, you then need to import the MMD6Enums.h in your TARGETNAME-Bridging-Header.h file to expose the results to Swift.

You can then use it like so:

func applyHighlightingForTokenTree(_ token: UnsafeMutablePointer<token>) {
    let tokenType = TokenType(rawValue: UInt(token.pointee.type))!

    switch tokenType {
    case .blockBlockquote: // highlight blockquote block
    case .pairEmph: // highlight emphasized span
    case .emphStart, .emphStop: // highlight the asterisks or underscores differently
    // ...

All of this is still too much work for my taste. Nobody wants to do that. When I figure out what else I want to change to make libMultiMarkdown usable in Swift, I’ll create a wrapper library for Swift PM, Carthage, CocoaPods and whatnot. I’m not certain if that should be part of the MMD6 project itself or a separate repository, though, but I think Fletcher, the author of MultiMarkdown, will come up with a plan. Meanwhile, I’ll keep making PRs.

Month 13 Is Out Of Bounds

Month 13 is out of bounds” appeared in my Xcode console logs today. But I don’t do date arithmetics.

When you create an empty macOS Cocoa app from the template, the message shows, too. It’s emitted before applicationWillFinishLaunching(_:) is called.

Looking at the output of other processes, I saw this was all over the place. TextMate, loginwindow, User Event Agent – every app is triggering this message.

Rdar or GTFO, right? – rdar://35792221

Let’s hope this does not indicate any important framework part is broken.

This is both humbling and worrying. Humbling, because Apple engineers make just the same silly mistakes as us app developers. Worrying, because having a working macOS is rather important to a lot of people around the globe, and while this message does not prevent me from using my Mac or any apps so far, bugs like these could have people killed in other contexts (think aerospace or autonomous cars).

Getting Worse

Update 2017-11-06: (Yes, I’m back on Nov. 6th! :) Seriously, it’s now Monday, Dec 4th.) Like some other people I was suddenly suffering from 100% CPU usage by the process UserEventAgent which also consumed RAM at a rate of about 4GB/ every 3 minutes. Disk swapping galore, my Mac turned unusable quickly. Only way I found to get rid of this:

  1. Deactivate automatic date and time setting
  2. Reset the date back to something in November
  3. Force quit the UserEventAgent process

Note that this only happened after rebooting. So if you can, do not shut down your Mac for a while just to make sure.

→ Blog Archive