WebcamSnap Open Source Library Released

Teaser image
screenshot
The picture cropping sheet in action

Another month goes by, another little macOS component was released.

This time, I wanted to have a very simple drop-in view component that takes pictures with the iSight camera of MacBooks or any other connected USB camera device. And if the user wants to crop the picture, I wanted to add that as post-processing.

Thought this would be a common need, but Google wasn’t helping much. So I coded this thing myself.

Have a look: https://github.com/CleanCocoa/WebcamSnap

How Taking Pictures with AVFoundation Works

Before I got it working, all the AVFoundation code looked pretty scary. But it’s simple, really, when you think about the possibilities of audio and video capturing and processing.

These are the requirements to take a photo with a USB camera using AVFoundation:

  1. you need a AVCaptureSession that controls the lifetime of the audio and/or video input and/or output;
  2. you specify output ports of type AVCaptureOutput, like the AVCaptureStillImageOutput I use here to grab a single image (instead of video or audio);
  3. you specify input ports of type AVCaptureInput, like the AVCaptureDeviceInput that takes a AVCaptureDevice, which in this case is of type AVMediaTypeVideo;
  4. you add a Core Animation layer (CALayer) to a preview view using AVCaptureVideoPreviewLayer(session:) so users see what the camera is showing before they hit the “Take Picture” button.

If things work out well, you have a session that can read video data from your camera device and streams the video signal to the preview. You can shoot photos, also known as “request still images” from the video stream, using captureStillImageAsynchronously on your AVCaptureStillImageOutput.

All of this setup is encapsulated in the Webcam object of my library. (links to the version of v1.0.0, no the latest, to prevent dead links in the future).

Hope it helps!

Do You Need to Use Action Creators in ReSwift to Conditional Action Dispatching? (No)

This is an answer to a StackOverflow question titled “When, why and how to use Action Creators in redux?” that is really targeted at ReSwift. The real question is phrased a bit differently, though:

For example, I have a button, after user pressed it I want to start some process if I’m in state A. So, I have to write an action creator, which will check current state and then return correct action, or not action at all. Then dispatch this action from the same place.

Redux.js and ReSwift behave quite differently. Redux recommendations may not apply in all cases.

Clearing up Redux.js/ReSwift confusions

Action Creators in ReSwift

“Action creators” is a rather specialized term in Redux.js, but the type is defined like this in ReSwift as of v4:

public typealias ActionCreator = (_ state: State, _ store: Store) -> Action?

So contrary to general advice, you do have access to the state at the point of dispatching the action. You don’t need a Thunk implementation, although Thunks or Epics can help in more complex cases.

“Action Creators help encapsulate action creation details”

A common benefit of Action Creators in Redux is their function as a factory.

Redux.js actions are object literals. Redux actions, if you were to write them in Swift, would be more like Dictionarys. If you come from an Objective-C background, you know both the good and bad of dictionaries: they are flexible, but you can cause trouble with typos, and the compiler won’t catch changes to values or keys if they are stringified. That’s how Action Creators in Redux.js provide the convenience of factories (as in “Factory”, the Gang of Four design pattern).

Here’s one as an example:

function addTodo(text) {
    return {
        type : "ADD_TODO",
        text
    }
}

// Somewhere else
dispatch(addTodo(text))

The ReSwift.Action type is usually implemented in custom value types (structs), though. ReSwift does not suffer from that problems of Redux.js actions. That means by creating a custom action type in ReSwift, the benefit of centralizing action creation in one function goes away. The initializer of your type does provide this already.

That paints a totally different picture.

And that’s probably why ReSwift.Store.ActionCreator passes in the state: to provide any benefit at all. At the cost of a different kind of API than Redux.

Application to the Question

Recall the question:

For example, I have a button, after user pressed it I want to start some process if I’m in state A. So, I have to write an action creator, which will check current state and then return correct action, or not action at all. Then dispatch this action from the same place.

There are a couple of ways to achieve that.

If you have access to the store variable to call dispatch, you also have access to its current state property. You can ask the store for the state the app is in and act accordingly. Usually, you’d write store subscribers to get “push notifications” of store changes, but in cases like this you can also ask the store.

That means the following would be a totally valid implementation:

let currentState = store.state
let action: Action = {
    if currentState.someSubstate == "A" {
        return ActionWhenInStateA()
    } else {
        return ActionWhenNotInStateA()
    }
}
store.dispatch(action)

Since ReSwift Stores are not supposed to receive dispatch commands from different threads, you can rely on the state from line 1 to be the same in the last line, where you dispatch.

TL;DR: you do not need ActionCreator to achieve this. But you can if you like to write “east-oriented” code, leaning on callbacks instead of property queries:

store.dispatch { state, _ in
    if state.someSubstate == "A" {
        return ActionWhenInStateA()
    } else {
        return ActionWhenNotInStateA()
    }
}

Adding RxSwift Ports to Resolve UI Inconsistencies

I am currently struggling to write my user interface layer (Mac) in a way that works well with RxSwift (the reactive library). Meanwhile, the whole app’s state is maintained by ReSwift (the unidirectional data flow library). Both work well together, but I made some weird choices initially. For example, I’d write Presenters to subscribe to store changes, assemble a static View Model, then pass that on to the View. That’s all nice and imperatively object-oriented.

Continue reading …

ReSwift v4 Released

I totally forgot to bring this up: ReSwift version 4 was released 13 days ago!

The coolest part (in my opinion) is to skip duplicate states in subscriptions if you want to. The state has to be equatable somehow to do this with the default subscription measurements. But then again you’re using this anyway right now with ReSwift 3.x, only for every subscriber.

store.subscribe(subscriber) {
  $0.select {
    ($0.testValue, $0.otherState?.name)
  }.skipRepeats {
    return $0 == $1
  }
}

The skipRepeats in the subscription builder/configuration block will be used automatically if the selected state conforms to Equatable. But you can use your own skipRepeats implementation if needed.

In theory, you could add map and filter and whatnot to the underlying Subscription type that’s being configured in the block you pass to subscribe(), though I don’t see much value in this at the moment.

Drawing Custom Alternating Row Backgrounds in NSTableViews with Swift

This is an old hat in Cocoa: when you change the appearance of NSTableRowViews, they will indeed look different – but the enclosing table view itself will still draw the system default background to fill the space below the last row. Similarly, when you have scrolling elasticity enabled and scroll above the topmost row, whatever is being drawn there won’t match your custom styled rows, either.

Continue reading …