Plugins: When to save userData?

I’m working on a tool that edits some data and should store it in GSLayer.userData when done.

I’m wondering how I should go on about saving the data. Right now I load the data from userData in the activate method and save it in the plugin’s deactivate method. That works fine when I activate the tool in the toolbar, edit, and activate another tool via toolbar. (The deactivate method seems to be called twice, even.)

It doesn’t work when I use the hand tool (space bar) in between. Then my edited data is lost.

Any insights on this?

What about storing the data when you calculated it? I would need to know more what you are actually doing.

The data is an NSImage, which can get quite large, so I would like to avoid saving it too often. It has to be converted to NSData everytime it is stored in userData, too.

https://twitter.com/jenskutilek/status/999716896919388166

Did you try? I would store it on mouseup. That also prevents problems with undo. there are several methods to convert to NSData. NSImage.TIFFRepresentation might be the simplest but may produce the biggest files. And maybe using a black and white image is enough?

Thanks, I will try it. I’m using NSImage.TIFFRepresentation right now. I think NSImage has always 24 bit color depth, perhaps it can be converted down to bitmap when storing it.

You can make a NSImage with all kinds of color spaces and bit depth. I found this (quite old): http://www.cocoabuilder.com/archive/cocoa/124402-creating-black-and-white-image.html

It seems saving after mouseUp is indeed fast enough, even if I apply a PNG compression to the image data.

I managed to build a NSImageRep in greyscale, though after reading it from userData, it becomes RGB again for some reason. Normally loading an image representation should set the properties matching those of the image data …

Blank image:

	# See https://developer.apple.com/documentation/appkit/nsbitmapimagerep/1395538-init
	img = NSBitmapImageRep.alloc().initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bitmapFormat_bytesPerRow_bitsPerPixel_(
		None,   # BitmapDataPlanes
		w,      # pixelsWide
		h,      # pixelsHigh
		8,      # bitsPerSample: 1, 2, 4, 8, 12, or 16
		1,      # samplesPerPixel: 1 - 5
		False,  # hasAlpha
		False,  # isPlanar
		NSDeviceWhiteColorSpace,  # colorSpaceName
		0,      # bitmapFormat
		0,      # bytesPerRow
		0,      # bitsPerPixel
	)

Loading from userData:

	# FIXME: The loaded image rep is not in the same format as the blank image.
	# It takes up twice the space as PNG. (RGB instead of grey?)
	data = NSBitmapImageRep.alloc().initWithData_(data)
1 Like

What happens if you save the data to a file a check the color space in Preview?

Ah, the image stays greyscale, but a color profile is assigned upon loading, which increases the file size on next save.