Gieta Laksmana
  • Blog
  • Profile
  • Projects
    • VR World Arcade
    • Punch For Fun
    • Spectrum
    • Dimension Battle
  • Resume

CoreData on macOS Mojave (10.14.0) shenanigans

9/26/2018

0 Comments

 
UPDATE (10/16/2018): Apple has closed my bug report about this as resolved. So hopefully the fix will be out on Mojave 10.14.1

tldr: overwriting a binary blob greater than 100kb will unnecessarily create extra files on each save with CoreData on macOS Mojave (10.14.0)
​Hookay, I was pretty excited to try out macOS Mojave and their dark mode. Instead I found a bug in CoreData

If you'd like to follow along the code, the code is available at my github:
https://github.com/gietal/AppleSandbox/tree/master/CoreData/CoreDataPlayground

Quick overview of CoreData, it stores your data in a sqlite database which live in your App's "Application Support" folder under ~/Library/<Your app bundle identifier> or ~/Library/Containers/<Your app bundle identifier>/Data/Library for sandboxed apps. You can store different types of data with CoreData such as string, int, float, bool, and even binary blob. When storing binary blob, you have an option to store it on an external storage:
Picture
​This is useful for bigger binary blob, as it’s less efficient to store and fetch a big binary blob form the sqlite database. If you try to store a big binary blob (bigger than 100kb), and you have that option enabled, CoreData will automatically decide to store your blob into a hidden folder called <Your DB name>_Support/_EXTERNAL_DATA
Picture
​The blob will be stored as a file named with a random UUID, and that UUID is what’s then stored in the sqlite database. You can examine your sqlite database content with DB Browser for SQLite (free from https://sqlitebrowser.org). You can see that the value for my binary blob attribute is the UUID of the file under _EXTERNAL_DATA. This is how CoreData manages your big binary blob.
Picture
Picture
The value of the binary attribute in the sqlite DB is actually the UUID name of the file on the _EXTERNAL_DATA folder
​When you update your binary blob from your code, then the blob file under _EXTERNAL_DATA is also overwritten with the new blob. However, this is not the case in macOS Mojave 10.14.0, which is demonstrated by my sample project

The sample project is quite simple, I have have an Entity with 2 simple attributes: an id (string) and an image (binary blob) with “Allows External Storage” selected. The id is so that I can fetch the same instance of the entity. When you run the app, you will see a window with a save button. 
Picture
Picture
Each time you hit the save button, it will try to save the displayed image as a binary blob to the entity’s instance in the sqlite database. Since the binary blob is greater than 100kb, it will store it under:
~/Library/Containers/com.gietal.sandbox.CoreDataPlayground/Data/Library/Application Support/CoreDataPlayground/.CoreDataPlayground_SUPPORT/_EXTERNAL_DATA

If you hit the save button multiple times, it will try to overwrite the binary blob with the same image every time. Now here’s where the problem lies. On macOS High Sierra (10.13.6) there is no issue with this, the binary blob is overwritten correctly. On macOS Mojave (10.14.0) however, this is not the case.

When you try running the same app on macOS Mojave, and start hitting the save button multiple times, you will observe that a new file keeps getting added under the _EXTERNAL_DATA folder. This is a serious problem as overtime the amount of useless files keep getting piled up inside this hidden folder. Normal non-savvy users would never know how their mac ran out of space so quickly due to this issue.

I submitted this issue to Apple’s Bug Reporter, and they acknowledged that it was a bug and are working on a fix. Hopefully macOS Mojave 10.14.1 come out soon with a fix for this.

A workaround you can do at the moment is to save the entity’s instance with a nil value for the binary attribute, and save it so that CoreData delete the external file. Then, you can save the instance again with the proper binary blob.
// magic functions to get the CoreData context and entity's instance
let context = getContext()
let entity = getEntity()

// nil out the binary blob, so CoreData erases the file in _EXTERNAL_DATA
entity.setValue(nil, forKey: "image")
context.save()

// then actually save your new blob
entity.setValue(blob, forKey: "image")
context.save()
0 Comments

custom NSOutlineView disclosure button

9/1/2018

1 Comment

 
NSOutlineView is a very nice template to create a Finder-like table view of your collection. However, as any other things Cocoa, it is very easy to create UI that looks "standard", but it's not that straight forward to customize it.

For instance, right out of the box, NSOutlineView already looks like the Finder app, complete with the collapse button (disclosure button is what they call it).
Picture
​This is great to start with, but now what if I don't like the default triangle disclosure button? What if I want to use my own image for the button? One would think that there must be an image/alternate attribute for the disclosure button or something, but no... there isn't.

So we have to devise a roundabout way to customize the button..

Here's how you can customize the disclosure button

​First, we have to add a new button to the expandable column of your outline view, usually the first (left-most) column. In my case, it's the "Hostname" column.
Picture

Change the button type to "Toggle"
Picture

Put your desired images on these fields:
  • Image: The image when the disclosure button is expanded (down arrow)
  • Alternate: The image when the disclosure button is closed (right arrow)
I'm using what the framework provides here, but you can put whatever image you want from your asset catalog
Picture

​Now, add an identifier to this button so that we can create this button with the identifier. Let's name it as "MyDisclosureButton".
Picture
​
​Now, NSOutlineView create its views by calling makeView(), providing the appropriate identifier for each elements on the table. In order to create our own button, we have to subclass NSOutlineView and override this function. When NSOutlineView is about to make the disclosure button, we can intercept this call by checking the identifier that it sent.
class GNLOutlineView: NSOutlineView {
  override func makeView(withIdentifier identifier: NSUserInterfaceItemIdentifier, owner: Any?) -> NSView? {

    // intercept disclosure button creation
    if identifier == NSOutlineView.disclosureButtonIdentifier {
      // then create our custom button
      let myView = super.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "MyDisclosureButton"), owner: owner) as! NSButton
      
      // we need to change the identifier so that the outline view knows to use this view as the disclosure button
      myView.identifier = identifier      
      return myView
    }

    // for everything else, use the default function
    return super.makeView(withIdentifier: identifier, owner: owner)
  }
}

​Change the outline view to use GNLOutlineView as the custom class from the interface builder. When we build and run we should get this:
Picture

​​Great! We can now display custom disclosure button for our outline view! 

But wait a second... when we click on our disclosure button, nothing happen! The group doesn't collapse, and the button doesn't change its image. It would seem like we didn't set the target+action properties on our button, so the button doesn't do anything when it's clicked. 

Where should we point the target+action of our button to? Let's cheat and take a look at where the original disclosure button's target+action pointed to. After all, they were already working without us explicitly modifying anything, so it must be pointing to the correct target+action!

We can create the original disclosure button by calling the super's implementation of the makeView function
// get the original disclosure button
let originalButton = super.makeView(withIdentifier: identifier, owner: owner) as! NSButton
If we stop the debugger after the creation of the original disclosure button, we can inspect the values of the button's target+action (if you drill down enough)
Picture
It would appear that the target is just our outline view, but the action is more interesting. The action points to a function called _outlineControlClicked. Since we don't see this function on NSOutlineView AND it starts with an underscore, it is highly likely that it is a private function (an Apple engineer I met at WWDC 2018 told me about the underscore prefixes on private functions and properties).

A simple solution to this is to assign our button's target+action to the target+action of the original button.
myView.target = originalButton.target
myView.action = originalButton.action

Now, after we hook our button's target+action, we can see that our disclosure button now works perfectly!
1 Comment

NSWindow positioning shenanigans

8/4/2018

0 Comments

 
You're playing around with NSWindow, and you find this function called setFrame, setFrameOrigin, and setFrameTopLeftPoint. You feel like you are the king of the world when the thought of being able to move your window anywhere programmatically consume you. Except that when you realized that Cocoa stops you from doing that.

Cocoa allows you to move the window anywhere using those functions, except when your window starts going above the menu bar.

For instance, consider the following scenario:
  • Screen Configuration:
    • Resolution at 1280 x 800
    • Menu bar height = 22 pixel
    • Which means, the menu bar starts at y = 778 (Cocoa coordinate start at the bottom left)
  • Your Window:
    • Size is 100 x 100

When you call window.setFrameTopLeftPoint with the position of (x: 100, y: 800) your window's top left will actually be positioned at (x: 100, y: 778), right under the menu bar.

Same goes with the other setFrame* variants, your window will be pushed down until no part of your window is above the menu bar.

This is of course unless your window is the size (or bigger) than the screen, in which case it has no choice.
0 Comments

NSPopUpButton shenanigans

7/8/2018

1 Comment

 
​action/value bound to NSPopupButton is only triggered when user changes the value from the UI. It doesnt get triggered when you change the value programmatically.

For example, if we bind the NSPopupButton's selected index property:
​
Picture
internal var selectedIndex: AnyObject! {
    didSet {
        let oldIndex = oldValue as? Int
        let newIndex = selectedIndex as? Int
        print("selectedIndex didSet, old: \(oldIndex), new: \(newIndex)")
    }
}
changing the selected value via the UI will trigger selectedIndex.didSet as expected
Picture
However, when we change the index programmatically such as this:
popUpButton.selectItem(at: 2)
Doing so will change the value in the UI, but it won't trigger selectedIndex.didSet as expected.

A bigger issue happens when we have this scenario:
  • ​User selects index 1 from the UI
  • We programmatically call popupButton.selectItem(at: 2), the UI changed to show that index 2 is selected
  • User reselects index 1 from the UI
  • selectedIndex.didset is not called for the user action!!
       
This happens because when we change the selected item programmatically to 2, selectedIndex's value doesn't actually change, it stayed at 1. So when the user change the index back to 1 via the UI, Cocoa realized that the value of selectedIndex is still the same (1), so it decided not to call the didset function.
1 Comment

UserDefaults shenanigans

9/7/2017

0 Comments

 
It seems like the UserDefaults or at least the shared group UserDefaults is being cached somewhere, and it can put you in a confused debugging state.

To highlight what I meant, create 2 sandboxed apps with the same app group, i.e: com.gietal.sandbox.group

On the first app, do the following:
// App 1
if let defaults = UserDefaults(suiteName: "com.gietal.sandbox.group") {
    defaults.set(123, forKey: "myKey")
}
When you run the first app, it should create this file ~/Library/Group Containers/com.gietal.sandbox.group/Library/Preferences/com.gietal.sandbox.group.plist where the setting "myKey = 123" is stored as xml.

​Now on the second app, try to read the value from the shared group UserDefaults. At this point, it should return the expected value of 123
// App 2
if let defaults = UserDefaults(suiteName: "com.gietal.sandbox.group") {
    let value = defaults.value(forKey: "myKey")
    print("value: \(value)")
}
Now delete the plist file ~/Library/Group Containers/com.gietal.sandbox.group/Library/Preferences/com.gietal.sandbox.group.plist

And try reading the value again from app 2. You would be surprised that it would still returns 123 instead of the expected nil.

However, if you reboot your mac and try reading the value of "myKey" from app 2 again, it will correctly returns nil this time!

So this made me believe that UserDefaults is being cached somewhere in the system and could get out of sync with the actual plist file where the values are stored.
0 Comments

Xcode 8.1 and Swift 3.0.1 shenanigans

11/29/2016

0 Comments

 
When upgrading my xcode from 8.0 to 8.1 and Swift to 3.0.1, I found that I can no longer compare type with implicitly unwrapped optional in a switch statement. I need to explicitly unwrap the optional
// this no longer works
let a: String! = "asd"
let b: String = "asd"
switch a {
case b: // error: expression pattern of type 'String' cannot match values of type 'String!'
    break
default:
    break
}
0 Comments

NSWindow.level shenanigans

11/18/2016

2 Comments

 
lately I had to deal with window layering and ordering is Swift. I had to make sure some windows are always on top of other windows. This can be done with window levels.

in objective-c I found that you can simply call [NSWindow setLevel] with defined values such as NSMainMenuWindowLevel. in Swift, these defines doesnt exist. we have to use CGWindowLevelKey enum

However, this enum is not a value we can use directly for NSWindow.level. We have to convert it to a usable value 
by using CGWindowLevelForKey(), which returned an Int32. Since NSWindow.level is an Int, we also have to cast it to Int.
    window.level = Int(CGWindowLevelForKey(.normalWindow))

Here's the list of the values of CGWindowLevelKey sorted from bottom to top. At the time of this writing, these values are generated with Swift 3.0.1 and macOS 10.12 SDK
​

baseWindow: -2147483648
minimumWindow: -2147483643
desktopWindow: -2147483623
desktopIconWindow: -2147483603
backstopMenu: -20
normalWindow: 0
floatingWindow: 3
tornOffMenuWindow: 3
modalPanelWindow: 8
utilityWindow: 19
dockWindow: 20
mainMenuWindow: 24
statusWindow: 25
popUpMenuWindow: 101
overlayWindow: 102
helpWindow: 200
draggingWindow: 500
numberOfWindowLevelKeys: 999
screenSaverWindow: 1000
assistiveTechHighWindow: 1500
cursorWindow: 2147483630
maximumWindow: 2147483631

2 Comments

MacOS Multi Monitor Shenanigans

10/25/2016

0 Comments

 
let's say you want your Mac app to have multiple windows, pretty reasonable request right? Now, lets say you have 2 monitor setup on your Mac, and you like to have each window on its own screen. Move one window to the first screen, and move the other window to the second screen, got it. Now what if you want both to be full screened on each screen?

if you have this setting under System Preferences > Mission Control enabled,
then you wont hit this problem. But if you're like me and have it disabled, you might be wondering why your secondary monitor stays black. keep on reading...
Picture
Displays? Spaces?

One of the key feature in MacOS is Spaces. It's that thing that you see at the top when you go to Mission Control (usually by pressing F3 in most Mac keyboard) that helps you organize and declutter apps windows.

The deal with the setting I mentioned in the beginning has to do with what happen when you attach a second, or third, or 'n'th monitor to your Mac. If you have the setting enabled, it will create a Space for each monitor. But if you disable it, all monitors will share the same space.

This isn't really an issue until you want your app to be fullscreened. When a window is changed to full screen, MacOS will create a new exclusive space for it and move the window there.

So when you make 1 of your window a fullscreen window, a new exclusive space will be created, and only your window will be placed there. To add your other windows to this fullscreen space, you need to do this to your window:
window.collectionBehavior.remove(.fullScreenPrimary)
window.collectionBehavior.insert(.fullScreenAuxiliary)
0 Comments

Xcode 8 Swift 3 compiler bug segmentation fault 11

9/21/2016

0 Comments

 
Recently I've had to go through the hellish task of upgrading my Swift 2 projects to Swift 3. tldr, 1000+ errors fixed later, I was left with 1 persistent error. command failed due to signal: Segmentation fault: 11

​I've never seen this compiler error before, and preliminary research suggested that it's a possible bug in the swift compiler itself.

Thankfully it tells me which file did the fault happened:
While type-checking declaration 0x7fc447c12e00 at /Users/gietal/dev/project/source/Extensions/FileManager+Extensions.swift:5:8
​
It doesn't tell me where in the file did it breaks, but at least I had a starting point. Luckily this file of mine is not that huge, so I'm able to brute force isolate each functions in the file and found that the culprit is a very specific function declaration.

This form of function declaration is the one that's causing the segmentation fault:
public extension FileManager {
  public func foo() throws -> URLRelationship {
    return URLRelationship.other
  }
}
I've found that omitting the throws keyword will avoid this error:
public extension FileManager {
  public func foo() -> URLRelationship {
    return URLRelationship.other
  }
}
This is a very weird behaviour, since if I mark the function with the throws keyword and have it return anything else EXCEPT URLRelationship it will compile just fine. This only happens if the function is marked throws and returns a URLRelationship.

I've filed a bug to Apple regarding this, as I've found someone else had had a similar issue like this with Swift 2.2 before:
​http://blog.bellebethcooper.com/xcode-bug.html

Anyway, this has been an annoying one to track. For now I will just have to workaround the issue by omitting the throws keyword and handle error thrown inside the function some other way.

I hope this post can help someone else who ran into the same issue. If this doesn't help, at least I hope this can give you some ideas into where to start isolating your code to find the offending piece of code.
0 Comments

Interesting Swift Lambda (closure) syntax

6/23/2016

0 Comments

 
Learning swift for iOS and macOS development. I was creating a closure to sort strings reversely this way:
let reversed = names.sorted(by: { 
    (s1: String, s2: String) -> Bool in 
    return s1 > s2 
})
The sort() function simply takes a function that takes 2 strings and returns a bool. What I didn't realize is the the "operator >" that I'm using on the closure is itself a function that takes 2 strings and return a bool.

So that chunk above can be reduced to:
let reversed = names.sorted(by: >)
0 Comments

    Archives

    September 2018
    August 2018
    July 2018
    September 2017
    July 2017
    November 2016
    October 2016
    September 2016
    June 2016
    May 2016
    March 2016

    Categories

    All
    Shenanigans
    Software Engineering
    Swift
    Vr
    Xcode

    RSS Feed

Powered by Create your own unique website with customizable templates.