Developing on Staxmanade

Debugging iOS AutoLayout Issues

(Comments)

This tip may not be news to you, but it was to me so I'll put this up here to help you, but more to help myself when I get stuck down the road and forget how to do this.

Background

I just stumbled upon a way to help when debugging and diagnosing issues around ambiguous auto layout constraints (you know the kind where iOS just picks the one it feels like to remove?).

Today I was researching why I was receiving the following output in my debugger console:

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0x7fc82d3e18a0 H:[UIView:0x7fc82aba1210(768)]>",
    "<NSLayoutConstraint:0x7fc82d6369e0 H:[UIView:0x7fc82aba1210]-(0)-|   (Names: '|':UIView:0x7fc82d6b9f80 )>",
    "<NSLayoutConstraint:0x7fc82d636a30 H:|-(0)-[UIView:0x7fc82aba1210]   (Names: '|':UIView:0x7fc82d6b9f80 )>",
    "<NSLayoutConstraint:0x7fc82d3e7fd0 'UIView-Encapsulated-Layout-Width' H:[UIView:0x7fc82d6b9f80(50)]>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7fc82d3e18a0 H:[UIView:0x7fc82aba1210(768)]>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

Now, I can tell from the above that theres an issue with the height constraint(s), but looking at this, I have no idea what view is being referenced which makes it quite difficult to jump to XCode and inspect the view's constraints.

But I worked through it, and learned the following along the way. Hope this helps you.

How to set auto layout breakpoint in Xcode debugger

Using this text Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. I found this great post on stack overflow on How to trap on UIViewAlertForUnsatisfiableConstraints but have copied below for reference.

You'll want to add a Symbolic Breakpoint. Apple provides an excellent guide on how to do this.

  1. Open the Breakpoint Navigator cmd+7
  2. Click the Add button in the lower left
  3. Select Add Symbolic Breakpoint...
  4. Where it says Symbol just type in UIViewAlertForUnsatisfiableConstraints

You can also treat it like any other breakpoint, turning it on and off, adding actions, or log messages.

But that's only the first step. Once you've run the app and hit the breakpoint, you're left staring at assembly code and memory addresses, for example:

UIKit`UIViewAlertForUnsatisfiableConstraints:
->  0x1131cc4a2 <+0>:   pushq  %rbp
    0x1131cc4a3 <+1>:   movq   %rsp, %rbp
    0x1131cc4a6 <+4>:   pushq  %r15
    0x1131cc4a8 <+6>:   pushq  %r14
    0x1131cc4aa <+8>:   pushq  %rbx
    0x1131cc4ab <+9>:   pushq  %rax
    0x1131cc4ac <+10>:  movq   %rsi, %r14
    0x1131cc4af <+13>:  movq   %rdi, %r15
    0x1131cc4b2 <+16>:  cmpq   $-0x1, 0x778796(%rip)     ; _UIConstraintBasedLayoutPlaySoundOnUnsatisfiable.result + 7
    0x1131cc4ba <+24>:  jne    0x1131cc529               ; <+135>
    0x1131cc4bc <+26>:  cmpb   $0x0, 0x778785(%rip)      ; _UIConstraintBasedLayoutPlaySoundWhenEngaged.__once + 7
    0x1131cc4c3 <+33>:  je     0x1131cc4ed               ; <+75>
    0x1131cc4c5 <+35>:  movq   0x73cd8c(%rip), %rdi      ; (void *)0x0000000113925248: UIDevice
    0x1131cc4cc <+42>:  movq   0x7108e5(%rip), %rsi      ; "currentDevice"
    0x1131cc4d3 <+49>:  movq   0x4d7aee(%rip), %rbx      ; (void *)0x0000000114598000: objc_msgSend
    0x1131cc4da <+56>:  callq  *%rbx
    0x1131cc4dc <+58>:  movq   0x71e375(%rip), %rsi      ; "_playSystemSound:"
    0x1131cc4e3 <+65>:  movl   $0x3ee, %edx
    0x1131cc4e8 <+70>:  movq   %rax, %rdi
    0x1131cc4eb <+73>:  callq  *%rbx
    0x1131cc4ed <+75>:  cmpq   $-0x1, 0x77877b(%rip)     ; _UIConstraintBasedLayoutLogUnsatisfiable.result + 7
    0x1131cc4f5 <+83>:  jne    0x1131cc541               ; <+159>
    0x1131cc4f7 <+85>:  cmpb   $0x0, 0x77876a(%rip)      ; _UIConstraintBasedLayoutVisualizeMutuallyExclusiveConstraints.__once + 7
    0x1131cc4fe <+92>:  je     0x1131cc51e               ; <+124>
    0x1131cc500 <+94>:  leaq   0x53ba89(%rip), %rdi      ; @"Unable to simultaneously satisfy constraints.\n\tProbably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) \n%@\n\nWill attempt to recover by breaking constraint \n%@\n\nMake a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.\nThe methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful."
    0x1131cc507 <+101>: xorl   %eax, %eax
    0x1131cc509 <+103>: movq   %r14, %rsi
    0x1131cc50c <+106>: movq   %r15, %rdx
    0x1131cc50f <+109>: addq   $0x8, %rsp
    0x1131cc513 <+113>: popq   %rbx
    0x1131cc514 <+114>: popq   %r14
    0x1131cc516 <+116>: popq   %r15
    0x1131cc518 <+118>: popq   %rbp
    0x1131cc519 <+119>: jmp    0x11331930c               ; symbol stub for: NSLog
    0x1131cc51e <+124>: addq   $0x8, %rsp
    0x1131cc522 <+128>: popq   %rbx
    0x1131cc523 <+129>: popq   %r14
    0x1131cc525 <+131>: popq   %r15
    0x1131cc527 <+133>: popq   %rbp
    0x1131cc528 <+134>: retq   
    0x1131cc529 <+135>: leaq   0x778720(%rip), %rdi      ; _UIConstraintBasedLayoutPlaySoundOnUnsatisfiable.__once
    0x1131cc530 <+142>: leaq   0x4fdb59(%rip), %rsi      ; __block_literal_global68
    0x1131cc537 <+149>: callq  0x11331a2a8               ; symbol stub for: dispatch_once
    0x1131cc53c <+154>: jmp    0x1131cc4bc               ; <+26>
    0x1131cc541 <+159>: leaq   0x778728(%rip), %rdi      ; _UIConstraintBasedLayoutLogUnsatisfiable.__once
    0x1131cc548 <+166>: leaq   0x4fdbc1(%rip), %rsi      ; __block_literal_global76
    0x1131cc54f <+173>: callq  0x11331a2a8               ; symbol stub for: dispatch_once
    0x1131cc554 <+178>: jmp    0x1131cc4f7               ; <+85>

What next?

We can use the Xcode debug console output to gather more information than we see it initially provides.

In the above example I'm going to take the following output:

Will attempt to recover by breaking constraint <NSLayoutConstraint:0x7fc82d3e18a0 H:[UIView:0x7fc82aba1210(768)]>

Pull out the UIView's memory address 0x7fd8fe59a440 and use the XCode console to get dig deeper and try to get a better understanding.

Printing views from memory addresses

The memory address 0x7fd8fe59a440 is a pointer to a UIView. Since we know that a UIView has other selectors we can query, we can begin to use these to dig deeper into the object and get a better understanding of which part of our view have auto layout constraints that are not playing nicely.

First we try to look at just the UIView and see if that helps us get a grasp as to which view is causing our troubles.

po 0x7fc82aba1210

If this doesn't provide enough info as the below sample output shows (not very helpful).

(lldb) po 0x7fc82aba1210
<UIView: 0x7fc82aba1210; frame = (0 0; 768 359); autoresize = RM+BM; layer = <CALayer: 0x7fc82d338960>>

Maybe printing it's recursiveDescription will help out and in my case gives me a better idea of which component I'm actually trying to look at.

(lldb) po [0x7fc82aba1210 recursiveDescription] 
<UIView: 0x7fc82aba1210; frame = (0 0; 768 359); autoresize = RM+BM; layer = <CALayer: 0x7fc82d338960>>
   | <MYAPPButton: 0x7fc82d61c800; baseClass = UIButton; frame = (0 0; 768 359); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x7fc82ab96570>>
   |    | <UIImageView: 0x7fc82d3f7b10; frame = (0 0; 0 0); clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x7fc82d6e7020>>
   | <UIImageView: 0x7fc82d54a1c0; frame = (314 110; 140 140); autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x7fc82d52def0>>

Or if that's not enough context, then we can look at the view's superview and potentially even walk up the view's tree, printing out a different levels trying to understand which component is having trouble with auto layout.

po [[0x7fc82aba1210 superview] recursiveDescription]

Once you've narrowed down which view inside which component is causing you trouble, now it's up to digging and finding the problematic constraint...

Fix it

This part I can't add much color to help you, except to start by looking in your storyboard, xib or code wherever the constraints are being added to the particular view we diagnosed above.

Hopefully this walk-through helps at least a little in diagnosing your auto layout constraint issues.

Happy debugging!

(Comments)

Running in-app mocha tests within WinJS

(Comments)

I described a while back a scenario about running in-app unit tests. So if you'd like some background on the subject have a look there before reading here.

This post is going to give some specifics about how to run MochaJS tests within a Microsoft Windows JavaScript application (WinJS).

Prerequisites

These steps assume you already have a WinJS application, possibly using the universal template or other. In the end it doesn't matter. As long as you have a project that probably has a default.html file and the ability to add js & css files to.

Get Mocha

You can acquire the mocha library however you want, Bower, Npm, or download it manually from the site (mochajs.org).

Reference Mocha Within Project & App

However you get the mocha source, you need to both add references to the mocha js and css files into your project file either in a *.jsproj file or if using a universal shared app, in the shared project.

Then you need to include a reference to the code in your default.html file.

In my example below you can see I used bower to download the MochaJS library.

The mocha.setup('bdd') tells mocha to use the BDD style of tests which defines the describe(...), it(...), etc functions.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>MyApp.Windows</title>

    <!-- WinJS references -->
    <link href="/js/bower_components/winjs/css/ui-light.css" rel="stylesheet" />
    <script src="/js/bower_components/winjs/js/base.js"></script>
    <script src="/js/bower_components/winjs/js/ui.js"></script>

    <!-- TESTS-->
    <link href="/js/bower_components/mocha/mocha.css" rel="stylesheet" />
    <script src="/js/bower_components/mocha/mocha.js"></script>
    <script>
        mocha.setup('bdd');
    </script>

    <!-- My Project js/css files below... -->

...Rest of default.html file excluded

Create a WinJS Control for hosting Mocha reporting.

Below is a sample WinJS control that can be used to host the mocha html report.

<!DOCTYPE html>
<html>
<head>
    <style>
        #mocha {
            height: 800px;
            width: 600px;
            overflow: scroll;
        }
    </style>
</head>
<body>
    <div class="fragment section1page">
        <section aria-label="Main content" role="main">

            <!-- define a button that we can use to manually run or re-run tests -->
            <button id="mochaTestsRun">Run Tests</button>

            <!-- define a checkbox that allow us to toggle auto-run 
                 of the tests when we start up the app -->
            Auto start <input type="checkbox" id="mochaTestsRunOnStart" />


            <!-- this is a blank div we use to inject U.I. related tests -->
            <div id="testElementContainer"></div>

            <!-- mocha throws the html output in the below div -->
            <div id="mocha"></div>
        </section>
    </div>
</body>
</html>
(function () {
    "use strict";

    var runMochaTests = function() {
        // clear any current test results since mocha just appends.
        element.querySelector('#mocha').innerHTML = "";
    
        // If you want your tests to verify nothing is leaked globally...
        mocha.checkLeaks();

        // specify any globals that you are OK with your tests leaking
        mocha.globals([
            'someGlobalIAmExpecting'
        ]);

        // start the test run
        mocha.run();
    }

    var ControlConstructor = WinJS.UI.Pages.define("/js/tests/tests.html", {
        // This function is called after the page control contents 
        // have been loaded, controls have been activated, and 
        // the resulting elements have been parented to the DOM. 
        ready: function (element, options) {
            options = options || {};

            // get our possibly already cached value of whether to run the tests on startup.
            var runOnStart = (JSON.parse(localStorage.getItem("mochaTestsRunOnStart") || "true"));

            // checkbox to manage auto-run state
            var runOnStartCheckbox = element.querySelector('#mochaTestsRunOnStart');
            runOnStartCheckbox.addEventListener('change', function () {
                localStorage.setItem("mochaTestsRunOnStart", runOnStartCheckbox.checked);
            });

            // button to manually trigger a test run
            var mochaTestsRunButton = element.querySelector('#mochaTestsRun');
            mochaTestsRunButton.addEventListener('click', function(){
                runMochaTests();
            })
            runOnStartCheckbox.checked = runOnStart;

            if (runOnStart && !window.hasRunMochaTestsAtLeastOnce) {
                // this value is used to avoid extra test runs as we navigation around the app.
                // EX: if the test control is on a home pivot - we nav away and come back home
                // we probably don't want to auto-run the tests again. (use the menu button 
                // instead if you want another test run)
                window.hasRunMochaTestsAtLeastOnce = true;
                runMochaTests();
            }

        },
    });

    // The following lines expose this control constructor as a global. 
    // This lets you use the control as a declarative control inside the 
    // data-win-control attribute. 

    WinJS.Namespace.define("MyApp.Testing.Controls", {
        TestsControl: ControlConstructor
    });
})();

Handle global exceptions

If you write any async code (difficult not to these days) an exception or assertion failure will not be trapped by the internal try/catch mechanism's of Mocha in a Windows WinJS environment.

We have to give Mocha a hint on how to hook into global exceptions.

Mocha tries to attach to the browser's global window.onerror method, and since a WinJS app doesn't use this same handler, we have to forward the exceptions and to mocha's attached window.onerror handler.

In you're default.js or wherever you configure the app you can attach to the WinJS.Application.onerror and after some exception massaging we can hand the exceptions to mocha so when a test fails it can be reported correctly.

    WinJS.Application.onerror = function (ex) {

        var errorMessage, errorLine, errorUrl;
        if (ex.detail.errorMessage) {
            errorMessage = ex.detail.errorMessage;
            errorLine = ex.detail.errorLine;
            errorUrl = ex.detail.errorUrl;
        } else if (ex &&
            ex.detail &&
            ex.detail.exception &&
            ex.detail.exception.stack) {
            errorMessage = ex.detail.exception.stack;
            errorLine = null;
            errorUrl = null;
        }

        // if window.onerror exists, assume mochajs is here and call it's error handler
        // This may be a poor assumption because 3rd party libraries could also attach
        // their handlers, but it's working for me so far...
        if (window.onerror && errorMessage) {
            window.onerror(errorMessage, errorLine, errorUrl);
            
            // return true signalling that the error's been 
            // handled (keeping the whole app from crashing)
            return true;
        }

        // if we get here, assuming mochajs isn't running
        // let's log out the errors...
        try {
            var exMessage = JSON.stringify(ex, null, '  ');
            console.error(exMessage);
        } catch (e) {
            // can't JSON serialize exception object here (probably circular reference)
            // log what we can...
            console.error(ex);
            console.error(e);
        }

        // I like to be stopped while debugging to possibly
        // poke around and do further inspection
        debugger;
    }

Reference the test control.

While developing out the application, I like to throw it front and center in the first hub of my apps home page hub control.

Here's an example of how to reference the above control:

<head>
    <meta charset="utf-8" />
    <title>hubPage</title>

    <link href="/pages/hub/hub.css" rel="stylesheet" />
    <script src="/js/tests/tests.js"></script>
</head>

...page details trimmed for brevity...

            <div class="hub" data-win-control="WinJS.UI.Hub">

                <div class="sectionTests"
                     data-win-control="WinJS.UI.HubSection"
                     data-win-options="{ isHeaderStatic: true }"
                     data-win-res="{ winControl: {'header': 'TestSection'} }">
                    <div id="sectionTestscontenthost" data-win-control="MyApp.Testing.TestsControl"></div>
                </div>
            </div>

...rest of page details trimmed for brevity...

If you manage to get everything wired up correctly above, when you run the app (F5) your mocha tests should be all set and run automatically. Oh wait, let's not forget to add a mocha test :)...

describe('Mocha test spike', function(){

    it("should report a passing test", function(){
      // doing nothing should be a passing test
    });

    it("should fail on a synchronous exception", function(){
        throw new Error("Some test error to make sure mocha reports a test failure")
    });

    it("should fail on an asynchronous exception", function(done){
        setTimeout(function(){
            throw new Error("Some test error to make sure mocha reports an async test failure")
            done();
        }, 100);
        throw new Error("Some test error to make sure mocha reports a test failure")
    });

});

Save the above as your first test file, include it so it runs on startup and verify your tests run and report correctly within the test control.

Happy testing!

(Comments)

Look at where DefinitelyTyped is Now

(Comments)

A Little Wondering

I installed Visual Studio 2015 the other night and was just poking around and stumbled upon the Cordova Project Template that is provided. This not necessarily that new, but is new to me as I spend most of my time these days working on a Mac doing iOS, Docker (for server-side stuff) and other projects. Though, I miss and still enjoy the benefits of Visual Studio for some projects.

While looking over the project template, I was surprised to see a familiar folder structure typings/cordova/* in the project.

Why is this folder structure familiar?

Because I created it almost 2 years ago when I threw together a PowerShell script that chucks DefinitelyTyped TypeScript definitions up onto NuGet.

Another example of the folder structure, while I can't say for certain, but I can only guess that when the winjs started converting over to TypeScript that they chose to put their type definitions into the same structure. I won't claim to have inspired it, but would be cool to say I did.

It was a bit surprising and humbling to discover Microsoft had in one of their default templates a reference to some TypeScript type definitions that (while I didn't have anything to do with the creation of the definitions, nor DefinitelyTyped) I did created the simple little utility that runs continuously up on TeamCity.CodeBetter.com and tirelessly updates NuGet packages as they change over on DefinitelyTyped.

This reminded me, that I hadn't checked up on the NuGet user account for DefinitelyTyped in quite a while so I decided to head over to the NuGet.org, take a glance at the account and check out how many downloads there had been?

DefinitelyTyped NuGet account

** HOLY Typings **, there've been over 2 million DT type definitions?

This little ditty was neat to find. I haven't done a ton with TypeScript in a while, but it's quite amazing to see the traction it is starting to gain.

This means that the TeamCity over at CodeBetter has pretty much been cranking out new and updated DefinitelyTyped TypeScript definitions for almost the last two years, but it's time to re-visit...

Thanks TeamCity @ CodeBetter

Before all of the new, cool, and hip online continuous integration systems came to be, one of the only free options for open source was an instance of JetBrains TeamCity over at CodeBetter and I'd like to throw out a big thank you for those at CodeBetter who put the time and effort into hosting this service for many of the .Net OSS projects out there.

Hello AppVeyor

I recently ported this job to an AppVeyor build for the DT project and after a quick round of using their wonderful support to work through a hurdle, I completed a new build at AppVeyor that replicated the one originally hosted on the TeamCity server.

So a HUGE thanks to AppVeyor for creating such great product, and offering free builds to the OSS community.

I'll keep an eye on the new build for a while (before I forget about it) and hopefully it'll run for another long time to come.

Happy TypeScripting!

(Comments)

Starting to build an Xbox One Podcast Player

(Comments)

I'm writing this email to announce an early sneak peek into a project I've recently started to put some of my free time towards. Here's a preview from a small landing page I've recently put together.

If you, like myself, felt like the Xbox One platform was missing an essential Podcast player app, then you have come to the right place.

Have any interest in following along with me in this journey?

At the bottom of this page is a form, if you share your name and email, you'll get early access and an insider's view of the process of building an Xbox One application.

Learn More here...

(Comments)

In-App Unit Tests

(Comments)

How often do you run your unit tests? Do you even have a test project? Is running your test suite automatic or does it only run when you choose to run them? If the latter is true, then how often do you run them?

For most, running tests is a simple command line tool like gulp test or rake test or a builtin function in your IDE. You may even have your system covered by a Continuous Integration server, or if you want to catch issues earlier possibly even a git pre-commit hook.

One thing we all probably know is the more difficult it is to run your tests, the less often they get run.

What if you're building in an environment that does not allow for easy test automation? What if there are no current command line task runners for the environment you're developing in?

You could spend way too much of your free time/life building a tool that can get the job done for you (cough - long live StatLight/Silverlight - cough). I would not necessarily recommend this approach unless you have the spare cycles to contribute a project like this to the broader community.

So, given that there are no external tools to rely on, and you don't want to spend however long it will take to create one for the development environment you are in, how about finding a way to integrate some sort of test run within your existing application?

I have always wanted to setup some unit tests that could run inside of an existing application. If you developed an app that had to ship on lots of devices (thinking android or iOS) and you could ask your users out in the wild to go to the settings page of your app and press a "run tests" button, how awesome would it be if this test run could collect data and send the test results back to you?

This is not a new idea, nor terribly unique, but I've pondered this for quite some time and until recently have not had a project were I was forced to execute on it, until now...

I'm playing with an app that is currently living inside a WinJS (Windows 8) (Metro - err do they call it that anymore?) environment and there are not any CLI tools out there that can be used to automate tests. However, it was easy enough to get Mocha running within the app.

With MochaJS in place, I proceeded to setup a WinJS Hub in my hub-based application, after make this testing hub the first hub in my project I now have test that run after every F5 (run) of the application.

This will eventually have to be something I move out of the main landing U.I. when I get closer to shipping my app, but I'm liking the idea of being able to toggle my test U.I. and have them run right within my application, instantly on startup.

A few benefits of this approach:

  • It allows me to actually write tests in an application that doesn't natively support a testing runner.
  • Fewer test gotch-ya's because of environmental reasons
  • Instant feedback on each run
  • It's an easy reminder to keep using and driving my development through tests, because the workflow is enabling it (and encouraging it).
  • (this could be considered a down side but...) since the tests are living within the actual application, I have to be careful to construct my components no to depend too heavily on the environment or configuration as we wouldn't want unit tests to mess up the running application. While it could be seen as a bit of a pain, I'm really liking how this is forcing me to write loosely coupled, highly compossable components that can be easy to swap in/out.

Will I Actually Ship In-App Tests?

This one is up in the air, but so far I'm of the mind-set that I'll hide the unit-test run from the main hub, place a button deep in some about or setting page and modify the reporter to send send any failed test results, along with some metadata about the environment or system it's running on, like versions, screen size, or whatever is needed...

Happy Testing!

(Comments)

Build Command with Auditory Feedback

(Comments)

Here's a short and fun little ditty I'm going to throw up here so I can find it later... (because why would I try to memorize something so simple when I can put it here and share with you all?).

My Builds Are Speaking to Me

Running this command from my Mac command line window gives a nice audio feedback when builds are complete.

(gulp && say 'super!') || say "what the what?" -v Albert

Some Context

While doing some project work on my Mac lately I'm in the situation where I am constantly running gulp at the command line. This workflow could apply to any CLI build tool like gulp, rake, make, etc and ya I know I need to spend the time getting gulp watch to work but let's not worry about that for now...

The build is not slow, but it's not fast (taking about 6) seconds. That's just enough time for me to see a squirrel and by the time I realize the build is done, I've forgotten if I actually recently kicked off the build or if the most recent run is out of date from the latest code I've worked on...

So I searched for a quick way to get some auditory feedback when my build was done so I could more efficiently continue the development flow...

I first stumbled upon this gist which has a NodeJS implementation console.log("\007");, but this produces the same beep I get when my unit tests fail - which I don't want when everything's good to go.

Then I found someone mention the mac say command which is WAY better for my needs and I settled on the following little command.

(gulp && say 'super!') || say "what the what?" -v Albert

Whats cool about this pattern is I can replace gulp with any other build tool on other projects like rake, grunt, make, etc...

(Comments)

Mac Equivalent of the Windows Registry - ish

(Comments)

If you're a long time Windows power user and are recently switching over to the Mac, you may have wondered if there was something analogous to the Windows Registry .

However, if you've always been more of a Mac user, don't run away just yet as you may learn something.

In case you don't know what the Windows Registry is, here is a short definition from our good ol' friend Wikipedia.

Windows Registry is a hierarchical database that stores configuration settings and options on Microsoft Windows operating systems. It contains settings for low-level operating system components and for applications running on the platform that have opted to use the Registry.

You have probably already figured that since it's called the Windows Registry that there is likely not a Mac Registry that looks/operates the same way.

You are correct; however, where do all of the system and applications settings get stored if there is no registry?

If the Windows Registry is a place where system and application settings are stored, then the Mac equivalent of the Windows Registry would be a series of .plist files in several preferences folder on the Mac.

While researching how to automate bootstrapping my Mac development computer, I stumbled upon large number of .plist files in several folders that correlate to the installed applications and system settings. And BOOM just like that I discovered the holy grail of my Mac's system and application settings - kind of like the first time lift up the curtain and discover the Windows Registry.

What are .plist files?

A .plist file is a configuration file that contains a list of properties in either plain text or binary format. I'll go into more later about how to read and update values in these files later in the post.

For more info on plist files, check out the Wikipedia page...

Where can I find plist files?

I know of at least 2 locations that host the common system and application .plist files.

The first one is user specific and is in the following location:

~/Library/Preferences/

In my case (since my user name is jason)

/Users/jason/Library/Preferences/

The second location one is at the root of the system:

/Library/Preferences/

If you look into these folders you'll see a large number of plist files that follow reverse domain name convention (like com.apple.sample).

Here are some (not all) examples of system configuration plist files:

com.apple.ActivityMonitor.plist
com.apple.AddressBook.plist
com.apple.finder.plist
com.apple.preference.general.plist
com.apple.TextEdit.plist
com.apple.Safari.plist

In the same folder as the sample configuration files listed above are where you can find plist files that are associated to applications installed on the system.

com.apple.dt.Xcode.plist
com.google.Chrome.plist
org.herf.Flux.plist
com.skype.skype.plist

Now that we can find system and application configuration plist files, if you try to open them in a text editor you may notice that many of them are in a binary format which would be challenging to read and understand, let alone edit.

How do I read these files?

The Mac comes with a command line utility called defaults for reading and writing to these .plist files.

If you take an example from the above list of plist files, you can, at the command prompt type the following:

defaults read com.apple.fin<tab> (where <tab> is the tab key that allows tab completion of the rest of the property list format) and be sure to exclude the .plist of the end so:

defaults read com.apple.finder

will print out all of the properties to the console so you can inspect what's there.

You can pipe this output to grep and filter for a setting name when doing searches. Once you've found a property name you want to look at you can pass it into the defaults read command to get the value of that specific property.

Example reading a single property:

defaults read com.apple.finder AppleShowAllExtensions

How to change property list settings?

warning WARNING warning

Just like modifying the Windows Registry can mess up your system, you need to take care modifying system or application plist settings.

warning WARNING warning

Most of these settings can be changed by navigating to the application or system's respective preferences U.I. and just changing settings manually. However, the whole reason I ran down this path was to learn how to automate these setting changes.

When I first tried to change the settings I tried manually modifying the plist files with a GUI tool built into the Xcode developer tools.

However, and I have yet to understand the internals of this, after I made the changes to the plist file they would automatically get overwritten after a few seconds. So it seems that there is some official source of these values somewhere that for some reason overwrite the ones in these folder. I probably have that all wrong - but was an observation I had.

So if my understanding above is somewhat correct, how did I update the source?

Similar to reading property list values you can use the defaults command line tool to write changes back to the .plist files.

As an example, here's how I update Finder to show file extensions.

defaults write com.apple.finder AppleShowAllExtensions -boolean true

The configuration options are now endless.

In summary:

Using my new knowledge that app and system settings can be found in both /Library/Preferences and ~/Library/Preferences and I can use the command line tool defaults to read/write to understand and update settings.

I can now create a simple .sh script that allows me to pre-configure a new development machine with all of the settings I would like.

Now, each time I catch myself trying to use an application's preferences U.I. I stop myself and try to find that setting in a plist file and create a CLI command that I can save into my development setup script.

Happy Mac Settings Hacking!

(Comments)

Fail Fast With iOS Images

(Comments)

Problem: iOS app has unwieldy, unorganized and poorly named images

I've been working on a team that took over a good sized legacy iOS project where it's usage of images became a little unwieldy. Between the various app clones (targets), shared images, and images that aren't even used we'd like to reorganize, rename and just clean up the app in general.

But, one thing that makes me nervous is how easy it is to rename an image, forget or miss a magic-string that tries to load that image and now we've introduced a bug that may be difficult to diagnose or even discover that we introduced it.

Let's fail fast?

Failing fast in this context means, how can we, during development and testing time quickly fail when running the app to determine where an image attempting to be loaded does not.

Ideally we wouldn't even have these magic-strings to deal with. Using some tool to automatically generate a compile-time safe construct that we can use to load images. However until both A) I find the darn tool that I once-upon stumbled across that does this (please leave a comment to remind me if you find it before I do...) and B) we get sed tool integrated, I threw this little helper to quickly fail fast and help us find broken image references within our iOS applications.

How does it work?

It's a simple little Category that overrides the imageNamed: selector of UIImage and if the original cannot load an image (returns nil) then it will fail with a helpful assertion message.

This utility allowed us to quickly find images that were missing while doing our big clean sweep.

How to integrate?

It should be as simple as adding the .h & .m files to your project and their respective targets and you should be off to the races.

For DEBUG mode only...

If you look closely you'll notice #if DEBUG wraps the implementation so when we ship to the app store we don't end up causing a crash in production if a missing image sneaks by.

Happy Missing Image Bashing!

(Comments)

How to Diff Two Xcode Targets

(Comments)

If you've ever used different Xcode targets to manage different version or clones of a similar app and then had to debug why one target builds while another doesn't, finding a way to diff two targets was always challenging.

Sometimes it's because you forgot to check a box including a new class in multiple targets, or maybe you've integrated a new framework with targetA but forgot to include the framework reference in the Build Phases for targetB.

I'm actually hoping that I just haven't learned the obvious way to resolve these problems and you (dear reader) will leave a comment telling me how simple it is to do with the built in tools. Until then, here's something that I hope will help others that are trying to see what two Xcode targets have different between them.

How about a little CLI tool: diffXcodeTargets

diffXcodeTargets is a command line utility I threw together that allows you to visualize the differences between two Xcode project targets using a diff tool.

Install it with npm

npm install -g diffxcodetargets

How to use it?

You can first call it by passing in the path to your project file and no targets and it will print out what targets are available.

> diffXcodeTargets ./myProject.xcodeproj/project.pbxproj

Could not find TargetA ''. Possible targets are:
  - targetA
  - targetB

Now you know your available targets and you can call it with the two targets you want to diff:

diffXcodeTargets ./myProject.xcodeproj/project.pbxproj targetA targetB

How does it work?

If you're curious how this tool does it's job it is actually quite simple and would love to hear any feedback...

diffXcodeTargets uses the xcode npm module to read/parse xcode projects and then approvals to show a difftool with two different files.

What's missing?

I threw this together quickly to help diagnose some issues with a project I was working on. It does not yet support all of the various scenarios that may be needed when diffing two Xcode targets, but if you have any suggestions or ideas feel free to leave a github issue.

Happy Diffing!

(Comments)

How to Remove Files in Git that Should Have Been Ignored

(Comments)

If sometimes come upon existing applications that use Git where files were added to the repository that should have originally been ignored. Sometimes this is because the .gitignore file is missing, or because certain rules were not include that probably should have been from the start.

There are ways in git to completely rewrite history to remove all traces of the file, however most of the time, it's good to leave a commit saying removed files that should have originally been ignored as a good starting point (depending on the project/repo).

Here is a small workflow I've found to be pretty effective in helping to clean up a repository, or at least let you know what files would have originally been ignored had you setup a .gitignore file with some project standards...

Create a well meaning .gitignore file

You can go to gitignore.io and type some words like xcode, node, osx, or whatever platform/IDE you use for development and generate a pretty good .gitignore base file.

Create or Update local .gitignore

Once you've update your local .gitignore file with the rules you'd like to use, you can use the below to commit your changes;

git add .gitignore
git commit -m 'updating .gitignore'

Remove the files that should have originally been ignored.

Now we want to figure out what files may have been added originally that shouldn't be there. You can run the following two commands to see which files to find this out.

git rm --cached -r .
git add .

Now if you git status you can see what files should probably be deleted from the git repo and using the newly updated .gitignore file will now be ignored going forward.

Go ahead an commit these changes (assuming you're happy with what is being deleted and ignored).

Happy Gitting!

(Comments)