<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>ejdraper.com</title>
        <link>https://ejdraper.com/</link>
        <description>Latest posts from ejdraper.com</description>
        <lastBuildDate>Fri, 05 Jun 2026 00:00:00 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <atom:link href="https://ejdraper.com/rss.xml" rel="self" type="application/rss+xml"/>
        <item>
            <title><![CDATA[In Rust We Trust]]></title>
            <link>https://ejdraper.com/2026/06/05/in-rust-we-trust</link>
            <guid isPermaLink="false">https://ejdraper.com/2026/06/05/in-rust-we-trust</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>I’ve been using Rust for around the last 18 months, for some work &#x26; personal projects, after bouncing off of it a few times before that. It’s been a lot of fun, and something about it really suits the way I’m thinking about building software at the minute.</p>
<p>main.rs</p>
<pre><code class="language-rust">fn main() {
  println!("Welcome to Rust.")
}
</code></pre>
<p>After around two decades working mostly with Ruby, I’d come to enjoy a lot about the expressive nature of writing code in a dynamic language. But having shipped a lot of production code that then needs maintaining, updating, features adding etc, the pitfalls of building entire applications with a dynamic language become apparent. With no concrete contracts defining interfaces, it can affect your ability to truly reason about the expected outcome of application logic. You know the sort of thing I mean, the “it <em>should</em> work so long as this is always a String…” etc. Of course tests can be used to help define &#x26; then enforce those expectations, but once the application &#x26; test suite reaches a certain size, the tests themselves can feel like a burden that need to be managed, rather than a solid safety net against regressions.</p>
<p>Enter Rust. Having shipped production code with it, I can say that the majority of the time, when it compiles without errors, it works. Sure, you might have a logic issue, or something that is a design related problem to resolve - but capturing inputs, processing and returning an output (for an API, or a CLI etc) has well-defined boundaries that are validated cleanly by the nature of the compiler. It’s no silver bullet of course, but a successful build is already a confidence marker even before unit or integration tests, QA, etc.</p>
<p>So I’m liking writing with Rust a lot - refactoring becomes easier, making changes that in Ruby might not be worth the risk of missing something or introducing a subtle regression (or refactoring the test suite alongside the change), now are worthwhile doing as the risk of those kinds of regressions are almost zero. It results in a more confident design process for the software architecture. And while I’m still learning the ropes in terms of the features and constructs available within Rust, as well as some of the best practice ways to do things, it doesn’t feel punitive to not know all of that already. I’m still working with Ruby too, but am very much enjoying trusting in Rust.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[It's Coming Home]]></title>
            <link>https://ejdraper.com/2018/07/14/its-coming-home</link>
            <guid isPermaLink="false">https://ejdraper.com/2018/07/14/its-coming-home</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>I’ve been watching England a long time now - I don’t remember Italia ’90 first hand, I do remember USA ’94 as my first World Cup, even though England hadn’t qualified. Euro ’96 was special, and I vividly remember the semi-final against Germany, the elation, the agony, the heartbreak. Gazza sliding in at the back post. The first time I cried after an England result (not the last). Beckham red card and losing to Argentina in ’98, being 1-0 up against Brazil in ’02 and losing 2-1, penalties to Portugal in ’06. After that, England seemed to be in the footballing wilderness, the so-called Golden Generation had come and gone, nothing to show for it. Overpaid and not really caring, the last decade has been tough to watch. Superstars picked based on reputation not form, and not delivering for country like they did for club. And so it comes full circle, watching this World Cup with my kids, the first World Cup where they were old enough to understand it, to be excited by it. Living vicariously through them, nervous for them, as they learn the highs and lows of being an England fan. Ultimately, perhaps inexperience delivered the final blow, but in doing so, has given these young, energetic and hungry players experience they can use in the future. In two years for the Euros, in four years for the next World Cup. Many of these players will play in 2 or maybe even 3 more World Cups if they stay fit and consistent, and this experience, this team unity, the exuberance they’ve shown together will count for so much. They’ve set themselves a high bar for future years, and in doing so have inspired my kids, and kids up and down the country. Keep the faith, because eventually, It’s Coming Home.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Announcing Dotplan]]></title>
            <link>https://ejdraper.com/2018/02/18/announcing-dotplan</link>
            <guid isPermaLink="false">https://ejdraper.com/2018/02/18/announcing-dotplan</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>I’ve re-focused how I keep track of notes and thoughts for ideas and plans, and in so doing, given an update to an old concept.</p>
<p>In <a href="https://en.wikipedia.org/wiki/Masters_of_Doom">Masters of Doom</a>, it details how John Carmack, genius programmer at id software, used.plan files to keep track of his todos and work plans when building out classic games like Wolfenstein 3d, Doom, and Quake. He eventually started to make these public, as a way of feeding back to his community and fanbase, exactly what he was up to.</p>
<p>Introducing Dotplan, a very simple content system based upon the excellent Middleman framework used for Ruby content management. It’s a default Middleman blog style setup, allowing unlimited plans to be created. You can simply clone it and hit the ground running, and write all your plans in Markdown - build the site into HTML, and ship to your favourite static host or CDN. Or keep it all to yourself, and simply run it locally as a journal to keep you sane!</p>
<p>There are two ways of utilising Dotplan - if you like the idea of just writing, then clone the repository and do just that. All the plans content is by default excluded from the source control, meaning you can continue to pull down Dotplan updates as it changes, and you won’t have to worry about merging or conflicts. Just make sure to back up your content through some other means - perhaps using Dropbox or another similar solution. It’s a clean separation of the code to power the tool, and your content.</p>
<p>Alternatively, fork the repo and clone your fork, then feel free to remove the line in.gitignore which stops plans from being included. You can then check them into source control to make sure they are safe. The advantage is you can more easily track changes to your content, roll things back etc - the downside is it may make it slightly harder to pull down upstream Dotplan changes going forward.</p>
<p>However you do it, Dotplan is a simple way to start getting organised - or at the least, get all of those creative thoughts out of your head and down somewhere. That gives you the headspace to prioritize and focus, and makes sure you can always refer back to them in the coming weeks or months.</p>
<p>Check out Dotplan <a href="https://github.com/ejdraper/dotplan">here</a>.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tic-Tac-Toe with Vue.js]]></title>
            <link>https://ejdraper.com/2018/01/17/tic-tac-toe-with-vuejs</link>
            <guid isPermaLink="false">https://ejdraper.com/2018/01/17/tic-tac-toe-with-vuejs</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>Following on from our <a href="https://ejdraper.com/2018/01/08/frontend-fun-with-rails-5-1-and-webpacker/">look at setting up the Vue.js and React frameworks in Rails 5.1</a>, this post will look at building a small little component in Vue.js, strictly on the client-side (just HTML, JS and CSS, no backend Rails app!).</p>
<p>We’re going to implement our own little version of the classic Tic-Tac-Toe game, called Tic-Tac-Vue.</p>
<h3>Setup</h3>
<p>We’ll start by creating our structure - create a folder, an HTML page, a JS file, and a stylesheet.</p>
<pre><code class="language-plaintext">mkdir tic-tac-vue
cd tic-tac-vue
touch index.html
touch app.js
touch app.css
</code></pre>
<p>Our HTML file is going to be very basic, let’s run through our initial markup:</p>
<pre><code class="language-plaintext">&#x3C;html>
  &#x3C;head>
    &#x3C;title>Tic Tac Vue&#x3C;/title>
    &#x3C;script src="http://unpkg.com/vue">&#x3C;/script>
    &#x3C;link rel="stylesheet" href="./app.css" />
  &#x3C;/head>
  &#x3C;body>
    &#x3C;script src="./app.js" type="text/javascript">&#x3C;/script>
  &#x3C;/body>
&#x3C;/html>
</code></pre>
<p>This sets up our page, brings in Vue.js, our CSS and our own JS file (both currently empty).</p>
<p>Next up, we’re going to add a root element for our app to live - this goes in our HTML <code>body</code>, above our script reference to our JS file:</p>
<pre><code class="language-plaintext">&#x3C;div id="app">&#x3C;/div>
</code></pre>
<p>And now we need the markup for our game grid itself, which we’re going to put in a script tag with a special template type - this too goes in our <code>body</code>, and above our JS file script ref:</p>
<pre><code class="language-plaintext">&#x3C;script type="text/x-template" id="grid">
  &#x3C;div class="grid">
    &#x3C;div class="row" v-for="row in rows">
      &#x3C;div class="column" v-for="column in row">
        {{column}}
      &#x3C;/div>
    &#x3C;/div>
  &#x3C;/div>
&#x3C;/script>
</code></pre>
<p>Let’s run through that so it’s clear - our grid is made up of rows and columns, fairly simple. It’ll be based on a 2D array representing that data, and so we’re looping through our rows data, which is an array of arrays, and then looping through each individual array, which contains the values for our individual columns. We’ll be expecting three rows, and three columns for Tic-Tac-Toe of course. The column values will either be blank (unplayed), or an <em>x</em> or an <em>o</em> if someone has played in that space. That’s it!</p>
<p><em>Quick note</em>: Why do we separate the markup like this? You could include that markup within the <code>#app</code> div directly when the app is so simple, however there are still a couple of downsides to this. The first is that you have to then be careful which markup you’re using - the browser will process that as HTML within the DOM long before Vue gets to it, meaning that if you then start to use any markup specific to how Vue works (like referencing components with tags) that isn’t HTML5 compliant, the browser could end up stripping it out, or doing odd things with it that’ll affect how your app works. Additionally, most apps are going to have enough complexity to have at least one component (rather than defining the app as just a root Vue app), so it makes sense to define that as such from the beginning, as it’s neater and clearer to follow, as well as more cleanly allowing for expansion as the need arises. We’ve separated our page container markup (to host our client-side app) from the app itself, which is comprised of our specific Vue markup template, and the JavaScript we’ll be writing to implement the functionality itself.</p>
<p>With our HTML out of the way, let’s format our grid so it looks like one - here is our CSS:</p>
<pre><code class="language-plaintext">.row {
  clear: both;
}
.column {
  border: 1px solid #000;
  width: 50px;
  height: 35px;
  float: left;
  text-align: center;
  padding-top: 15px;
}
</code></pre>
<p>Fairly simple - we’re floating each column and having them on the same row, with each row clearing the float to move on to the next row - we setup a border for the grid itself, set a specific height and width, and make sure that if a text value is shown (<em>x</em> or <em>o</em>) it looks nice within the box for that space on the game grid.</p>
<p>Now we get to the fun part - our JavaScript! We have two tasks now to get our initial grid functional - we have to create and define our grid as a component, and we then have to create our Vue app with our grid component being rendered into our <code>#app</code> empty div above.</p>
<p>First, we define our grid component:</p>
<pre><code class="language-plaintext">var Grid = Vue.component('grid', {
  template: '#grid'
});
</code></pre>
<p>This is easy enough to follow - we define a component, named Grid, using the template with id <em>grid</em>, and store it as <code>Grid</code> for reference elsewhere.</p>
<p>We’re going to need to set our initial data for the component though - the rows and columns that the template renders:</p>
<pre><code class="language-plaintext">data: function() {
    return {
      rows: [
        ['', '', ''],
        ['', '', ''],
        ['', '', '']
      ]
    };
  }
</code></pre>
<p>As we described above for our template, rows is a 2D array, an array of arrays, each array representing a row, and each value within representing a column in that row - and we’re starting with them all blank and unplayed.</p>
<p>Next up, let’s define our App:</p>
<pre><code class="language-plaintext">var App = new Vue({
  el: '#app',
  components: {
    Grid
  },
  render: function(createElement) {
    return createElement(Grid);
  }
});
</code></pre>
<p>Here we specify the element our app will reside in, so <code>#app</code>, and then the components we need to use - we just have one, our <code>Grid</code> component. Lastly, as we don’t have any markup within our <code>#app</code> element to tell our app how and what to render, we do it with a custom render method, referencing our game grid component.</p>
<p>Open up <code>index.html</code> now in a browser and you’ll see our grid! That’s great, but it doesn’t do a lot. Let’s start making it so we can play the spaces, and get a game going!</p>
<h3>Game on</h3>
<p>First of all, we want the user to be able to select a space, and if it’s empty, it’ll place an <em>x</em> or an <em>o</em> in it, depending upon whose turn it is. Let’s add a variable to our data to determine whose go it is, and which one is next:</p>
<pre><code class="language-plaintext">data: function() {
  return {
    rows: [
      ['', '', ''],
      ['', '', ''],
      ['', '', '']
    ],
    next: 'x'
  };
},
</code></pre>
<p>So we’ve just added that <code>next</code> attribute with a default value of <em>x</em> to our component data.</p>
<p>Now we’ll add a method to our component definition, that’ll handle when a space is tapped:</p>
<pre><code class="language-plaintext">methods: {
  tap: function(e) {
    if (e.target.innerText == '') {
      e.target.innerText = this.next;
      this.next = (this.next == 'x' ? 'o' : 'x');
    }
  }
}
</code></pre>
<p>So it only works if the space is free, sets the space, and then toggles which player is next. Reload our page, tap a space, and… nothing. That’s because we have one final step - we need to hook up tapping on the game grid spaces to that method we just wrote!</p>
<p>Change the markup in our <code>#grid</code> component template, so it’s like this:</p>
<pre><code class="language-plaintext">&#x3C;div class="column" v-for="column in row" v-on:click="tap">
  {{column}}
&#x3C;/div>
</code></pre>
<p>The <code>v-on:click</code> attribute is added, which adds an event handler for the <code>click</code> event to the component, pointing at the <code>tap</code> method. Try reloading again now, et voila! Tapping on spaces sets the next player character in the space, with no overwriting involved. Pretty neat, and not a lot of code either!</p>
<h3>Data binding</h3>
<p>We have our action in place, but we can’t do much with spaces played as we’re not updating our data based on the user input - we’re just directly updating the UI. Instead, let’s update our data array, and have that reflect to the UI, which is a much better way to handle things.</p>
<p>In our markup, we’ll alter our Grid component template as follows:</p>
<pre><code class="language-plaintext">&#x3C;script type="text/x-template" id="grid">
  &#x3C;div class="grid">
    &#x3C;div class="row" v-for="(row, row_index) in rows">
      &#x3C;div class="column" v-for="(column, column_index) in row" v-on:click="tap" v-bind:data-row="row_index" v-bind:data-column="column_index">
        {{column}}
      &#x3C;/div>
    &#x3C;/div>
  &#x3C;/div>
&#x3C;/script>
</code></pre>
<p>Specifically, we’re keeping track of the row and column index in our two-dimensional array looping, and then binding it as <code>row</code> and <code>column</code> data variables to reference when a space is played.</p>
<p>Over to our <code>tap</code> method now:</p>
<pre><code class="language-plaintext">tap: function(e) {
  if (e.target.innerText == '') {
    let rows = this.rows;
    rows[e.target.attributes['data-row'].value][e.target.attributes['data-column'].value] = this.next;
    this.rows = rows.slice(0);
    this.next = (this.next == 'x' ? 'o' : 'x');
  }
}
</code></pre>
<p>Here we are grabbing the data rows, then updating the value of our column, using the <code>data-row</code> and <code>data-column</code> bindings present on the element tapped to find the right location in the array. The reason we do a <code>slice(0)</code> is because the way that the data binding works in Vue, the <code>rows</code> property in our data is reactive (meaning it is being watched for changes), but individual changes <em>within</em> the array won’t trigger that watcher, and therefore a re-render. Instead we’re using a local rows variable, and then effectively copying the whole array back into our <code>data</code>, which triggers our reaction and an update of the UI using our template (rather than us modifying the element directly).</p>
<p>So now we have our app data binding correctly, we can implement logic based on the current rows/columns data to check for win criteria!</p>
<h3>Winner winner</h3>
<p>To check for a winner, we need to check each row for three matching values, each column for three matching values, and the two diagonal paths for three matching values. If any of those are true, we have a winner! We can boil this down to the following:</p>
<pre><code class="language-plaintext">checkWinner: function() {
  return (
    this.checkValues(this.rows[0]) ||
    this.checkValues(this.rows[1]) ||
    this.checkValues(this.rows[2]) ||
    this.checkValues([this.rows[0][0], this.rows[1][0], this.rows[2][0]]) ||
    this.checkValues([this.rows[0][1], this.rows[1][1], this.rows[2][1]]) ||
    this.checkValues([this.rows[0][2], this.rows[1][2], this.rows[2][2]]) ||
    this.checkValues([this.rows[0][0], this.rows[1][1], this.rows[2][2]]) ||
    this.checkValues([this.rows[0][2], this.rows[1][1], this.rows[2][0]]));
},
checkValues: function(values) {
  return (values[0] != '' &#x26;&#x26; values[1] != '' &#x26;&#x26; values[2] != '' &#x26;&#x26; (values[0] === values[1]) &#x26;&#x26; (values[1] === values[2]));
}
</code></pre>
<p>Add those methods to our component underneath our <code>tap</code> definition.</p>
<p><code>checkValues</code> is easy enough - we expect an array of three values, we make sure all the values are not blank, and that they are the same. <code>checkWinner</code> then calls <code>checkValues</code> for all of our different possible value arrays - firstly checking each of the three rows (each of those is already an array with three elements), then the three columns, and then lastly, the two diagonals.</p>
<p>With our win logic in place, we now just need to hook it up. We’ll add an additional property, <code>finished</code>, to our data:</p>
<pre><code class="language-plaintext">data: function() {
  return {
    rows: [
      ['', '', ''],
      ['', '', ''],
      ['', '', '']
    ],
    next: 'x',
    finished: false
  };
},
</code></pre>
<p>We’ll then reference that to make sure that you can’t keep playing once we’re finished - at the top of the <code>tap</code> method:</p>
<pre><code class="language-plaintext">tap: function(e) {
  if (!this.finished &#x26;&#x26; e.target.innerText == '') {
</code></pre>
<p>Lastly in terms of logic, we just need to amend the end of our <code>tap</code> method:</p>
<pre><code class="language-plaintext">if (this.checkWinner()) {
  this.finished = true;
} else {
  this.next = (this.next == 'x' ? 'o' : 'x');
}
</code></pre>
<p>So we only go to our next player if we’ve not found a winner - if we have found a winner, we mark the game as finished.</p>
<p>Playing the game now, we’ll see that if one player wins, you can’t continue playing. But some kind of feedback to indicate that the game is over (and to say who has won!) would be good. Easy! We can do that with a single additional line in our template - at the bottom within our <code>.grid</code> div, below the rows &#x26; columns, add:</p>
<pre><code class="language-plaintext">&#x3C;div class="status" v-if="finished">Finished! {{next}} wins!&#x3C;/div>
</code></pre>
<p>Add the following to <code>app.css</code> to make sure our message sits underneath the grid:</p>
<pre><code class="language-plaintext">.status {
  clear: both;
}
</code></pre>
<p>Now when someone wins and the game stops, you can see who has won!</p>
<h3>Whose turn?</h3>
<p>It’d be good if we could show whose turn it is next, in case the players lose track. We already have the data, and as you can probably guess from how we displayed the finish state, it’s fairly easy to do - change our <code>.status</code> text div to the following:</p>
<pre><code class="language-plaintext">&#x3C;div class="status">
  &#x3C;span v-if="finished">Finished! {{next}} wins!&#x3C;/span>
  &#x3C;span v-else>Next go: {{next}}&#x3C;/span>
&#x3C;/div>
</code></pre>
<p>Here we’re making use of <code>v-if</code> and <code>v-else</code> to make sure only one shows - either we’re showing whose turn is next, or we show the finished/winner text as the game is over!</p>
<h3>Replayability</h3>
<p>We’re almost there with our incredible take on Tic-Tac-Toe, but rather than having to refresh the page after every game to go again, wouldn’t it be cool if we could just press a restart button instead?</p>
<p>We’re going to move our code to determine the next player into its own method, so we can re-use it:</p>
<pre><code class="language-plaintext">nextPlayer: function() {
  this.next = (this.next == 'x' ? 'o' : 'x');
},
</code></pre>
<p>Next up, we’ll change the <code>tap</code> method to use that function - so for the winner check or next player logic:</p>
<pre><code class="language-plaintext">if (this.checkWinner()) {
  this.finished = true;
} else {
  this.nextPlayer();
}
</code></pre>
<p>Now, we’ll implement our <code>restart</code> method:</p>
<pre><code class="language-plaintext">restart: function(e) {
  this.rows = [
    ['', '', ''],
    ['', '', ''],
    ['', '', '']
  ];
  this.finished = false;
  this.nextPlayer();
},
</code></pre>
<p>This just resets the rows, makes sure the game is no longer finished, and triggers the next player. Let’s hook that up to something in the template now:</p>
<pre><code class="language-plaintext">&#x3C;div class="status">
  &#x3C;div v-if="finished">
    &#x3C;p>Finished! {{next}} wins!&#x3C;/p>
    &#x3C;a v-on:click="restart">Restart&#x3C;/a>
  &#x3C;/div>
  &#x3C;span v-else>Next go: {{next}}&#x3C;/span>
&#x3C;/div>
</code></pre>
<p>Our restart link shows when the game is finished, and tapping it resets our game accordingly!</p>
<h3>Stalemate</h3>
<p>The last thing we need to handle, is the dreaded stalemate. When two world class Tic-Tac-Toe players are locked together, head-to-head, neither willing to budge an inch, we could end up with a tied game. What then? The game doesn’t get marked as finished, but there are no more moves to make. The games cannot continue!</p>
<p>So let’s add a check for that state, and handle it accordingly. We’ll start by refactoring our <code>checkValues</code> method, so we can re-use the blank check within it for checking if all the spaces have been played:</p>
<pre><code class="language-plaintext">checkValues: function(values) {
  return this.checkValuesPresent(values) &#x26;&#x26; this.checkValuesMatch(values);
},
checkValuesPresent: function(values) {
  return (values[0] != '' &#x26;&#x26; values[1] != '' &#x26;&#x26; values[2] != '');
},
checkValuesMatch: function(values) {
  return (values[0] === values[1]) &#x26;&#x26; (values[1] === values[2]);
}
</code></pre>
<p>As you can see, we’ve separated the two parts of <code>checkValues</code> into a check for whether the specified values are all present (<code>checkValuesPresent</code>) and whether the values all match (<code>checkValuesMatch</code>). Now we can use the <code>checkValuesPresent</code> check in our stalemate logic - add the following method:</p>
<pre><code class="language-plaintext">checkStalemate: function() {
  return !this.finished &#x26;&#x26;
    (this.checkValuesPresent(this.rows[0]) &#x26;&#x26;
    this.checkValuesPresent(this.rows[1]) &#x26;&#x26;
    this.checkValuesPresent(this.rows[2]));
},
</code></pre>
<p>We’re just making sure that the game isn’t yet finished, and all of the rows have values present - then it must be a stalemate!</p>
<p>We’ll add an additional property to track stalemates, so add the default value to our data:</p>
<pre><code class="language-plaintext">next: 'x',
finished: false,
stalemate: false
</code></pre>
<p>And then we’ll update our <code>tap</code> method to account for checking for stalemates:</p>
<pre><code class="language-plaintext">if (this.checkWinner()) {
  this.finished = true;
} else if (this.checkStalemate()) {
  this.stalemate = true;
  this.finished = true;
} else {
  this.nextPlayer();
}
</code></pre>
<p>We have to check for a stalemate after a win, because there might be a winner on the very last space! If it is a stalemate, the game is finished, but also the stalemate property is set.</p>
<p>We can now use this on the frontend within the template to display something more relevant:</p>
<pre><code class="language-plaintext">&#x3C;div class="status">
  &#x3C;div v-if="finished">
    &#x3C;p v-if="stalemate">It's a draw! Stalemate!&#x3C;/p>
    &#x3C;p v-else>Finished! {{next}} wins!&#x3C;/p>
    &#x3C;a v-on:click="restart">Restart&#x3C;/a>
  &#x3C;/div>
  &#x3C;span v-else>Next go: {{next}}&#x3C;/span>
&#x3C;/div>
</code></pre>
<p>We’re either displaying our draw statement for stalemates, or the winner text, and the restart button either way so a new game can start. The only thing left, is to make sure our stalemate flag is reset on restart:</p>
<pre><code class="language-plaintext">restart: function(e) {
  this.rows = [
    ['', '', ''],
    ['', '', ''],
    ['', '', '']
  ];
  this.finished = false;
  this.stalemate = false;
  this.nextPlayer();
},
</code></pre>
<p>Now win, lose or draw, players can continue playing!</p>
<h3>Wrapping up</h3>
<p>So our Tic-Tac-Toe game is pretty much feature complete, at least in terms of a basic game two people can play on a single computer. It saves on paper and drawing, and we’ve done it all with just a little HTML + CSS, and a bit of fun JavaScript, all thanks to Vue.js!</p>
<p>This is one way to build a Vue.js app, and is better suited for small, self-contained ideas like this. In a future post we’ll look at going back to Webpack and using <code>vue-cli</code>, so that we can do things like having each component of our app (template HTML and JS logic) in its own <code>.vue</code> file, that’s pre-processed accordingly to build the JS for our page. As projects increase in complexity, that helps to give them structure and keep them maintainable.</p>
<p>Check out the full code for this post at <a href="https://github.com/ejdraper/tic-tac-vue">https://github.com/ejdraper/tic-tac-vue</a>, and you can play the game itself below!</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Frontend Fun with Rails 5.1 and Webpacker]]></title>
            <link>https://ejdraper.com/2018/01/08/frontend-fun-with-rails-5-1-and-webpacker</link>
            <guid isPermaLink="false">https://ejdraper.com/2018/01/08/frontend-fun-with-rails-5-1-and-webpacker</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>Client side frameworks for more responsive web apps are <em>en vogue</em>, and have been for a number of years now. The frameworks themselves change in popularity - to begin with it was Backbone, then Ember and Angular - more recently, frameworks like Vue and React have become the most popular choices.</p>
<p>Let it never be said that Rails doesn’t move with the times though, as Rails 5.1 introduced the Webpacker gem, providing a smarter interface to allow you to use Webpack config for bundling JavaScript packages on the client side of your Rails web app. This means easier access to stable versions of client side frameworks, and easier maintainability for those dependencies going forward. It’s a separate gem too, allowing you to also use it in Rails 4.2+ apps if needed.</p>
<p>Let’s take a look at just how easy it is in Rails 5.1 now to setup Vue.js and React. Make sure you have the latest version of Rails installed, and then we’ll setup a <a href="https://github.com/ejdraper/frontend-fun/commit/3c7cd6d2c10b17785400f04f8795fefffb97ec05">new empty app</a>:</p>
<pre><code class="language-plaintext">rails new frontend-fun
</code></pre>
<p>You can also specify to use webpack as part of this command and skip the next couple of steps:</p>
<pre><code class="language-plaintext">rails new frontend-fun --webpack
</code></pre>
<p>However, if you’re looking to add this to an existing Rails app, these next two steps will allow you to add Webpacker ready to use.</p>
<p>Within the app, add the <code>webpacker</code> gem to <code>Gemfile</code>:</p>
<pre><code class="language-plaintext">gem "webpacker"
</code></pre>
<p>Then run bundle from a terminal in the root directory of the project to install the gem:</p>
<pre><code class="language-plaintext">bundle install
</code></pre>
<p>At this point, we’ll now have some additional commands available to us courtesy of the webpacker gem, to install frontend packages. We’ll get things rolling with the initial command to prep our webpacker config:</p>
<pre><code class="language-plaintext">bin/rails webpacker:install
</code></pre>
<p>With <a href="https://github.com/ejdraper/frontend-fun/commit/eb408b923ab907d5be64081dc3847fc4a80dc1cc">that done</a>, we should probably setup a basic page for testing, so create a new controller <code>app/controllers/site_controller.rb</code>, with the following Ruby code in it:</p>
<pre><code class="language-plaintext">class SiteController &#x3C; ApplicationController
end
</code></pre>
<p>Then we’ll create a template for our content, at <code>app/views/site/index.html.erb</code>:</p>
<pre><code class="language-plaintext">&#x3C;h1>FrontendFun&#x3C;/h1>
</code></pre>
<p>Finally, in our <code>config/routes.rb</code> file, we’ll add a reference for the root of our app to the new controller and action:</p>
<pre><code class="language-plaintext">Rails.application.routes.draw do
  root "site#index"
end
</code></pre>
<p>If you test <a href="https://github.com/ejdraper/frontend-fun/commit/cad37daa4899cb8d97dc7d3541a8c03f4beadf88">our app now</a>, you’ll see the <em>FrontendFun</em> header. Last thing we now need to do is hook in our webpacker JS, with a reference from our layout template. In <code>app/views/layouts/application.html.erb</code>, below the <code>javascript_include_tag</code> reference in the <code>&#x3C;head></code>, add:</p>
<pre><code class="language-plaintext">&#x3C;%= javascript_pack_tag 'application' %>
</code></pre>
<p><a href="https://github.com/ejdraper/frontend-fun/commit/17ab5377b2f411a51ca01a8f3d3096881901bd9c">Now</a> if you reload the page, and look in the JavaScript console, you should see:</p>
<pre><code class="language-plaintext">Hello World from Webpacker
</code></pre>
<p>Webpacker - it’s alive!</p>
<h3>Vue.js</h3>
<p>To install Vue.js, run the following commands:</p>
<pre><code class="language-plaintext">bin/rails webpacker:install:vue
bin/yarn install
</code></pre>
<p>This will install the Vue.js packages. We’ll then hook up the Hello Vue pack that is setup by default, by modifying our <code>javascript_pack_tag</code> line in <code>app/views/layouts/application.html.erb</code>:</p>
<pre><code class="language-plaintext">&#x3C;%= javascript_pack_tag 'application', 'hello_vue' %>
</code></pre>
<p>Reload our page, and you’ll <a href="https://github.com/ejdraper/frontend-fun/commit/943e520533073d0c506b1a9bd5e2f1569c8fbf9d">now</a> see <em>Hello Vue!</em> in our page body, which is coming directly from Vue.js!</p>
<h3>React</h3>
<p>Now, in a production application, you’re unlikely to want to use more than one frontend framework, unless you were transitioning from one to another. But, this is <em>FrontendFun</em>, so we’re going to add React too!</p>
<p>By now, this should be fairly straightforward, we run:</p>
<pre><code class="language-plaintext">bin/rails webpacker:install:react
bin/yarn install
</code></pre>
<p>This will install the React packages now, and setup a base <code>HelloReact</code> component similar to our <code>HelloVue</code>. So we’ll just need to modify our <code>javascript_pack_tag</code> one more time to reference our React pack:</p>
<pre><code class="language-plaintext">&#x3C;%= javascript_pack_tag 'application', 'hello_vue', 'hello_react %>
</code></pre>
<p>Once more, reload <a href="https://github.com/ejdraper/frontend-fun/commit/771fce6b9419097eee3bec5cc8523bf31dad76bf">our page</a>, and behold - <em>Hello Vue!</em> and <em>Hello React!</em>.</p>
<p>Two frontend frameworks, setup very easily, co-existing in the same HTML page in our Rails app. The possibilities are practically endless!</p>
<h3>Next steps</h3>
<p>From here, you can edit either <code>app/javascripts/packs/hello_vue.js</code> and <code>app/javascripts/app.vue</code> if you want to use Vue.js, or <code>app/javascripts/hello_react.jsx</code> for React, adding new components and interactions to build out your frontend, and integrate it with whatever backend functionality your Rails app might offer. You can check out the simple demo Rails app that we’ve just built up <a href="https://github.com/ejdraper/frontend-fun">here</a>.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Say hello to AppTrack]]></title>
            <link>https://ejdraper.com/2017/12/21/say-hello-to-apptrack</link>
            <guid isPermaLink="false">https://ejdraper.com/2017/12/21/say-hello-to-apptrack</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>Say hello to AppTrack, a brand new utility for macOS that’s available today on the macOS App Store!</p>
<h5>What’s AppTrack?</h5>
<p>AppTrack is a macOS app that tracks the apps you have open on your Mac, and captures the time spent in each one, so you can see where you are spending the most time.</p>
<h5>Knowledge is the first step</h5>
<p>AppTrack will help you to identify bad habits, and adjust over time to being more productive when it counts. It’s easy to overlook how much we can flick between apps, a quick look over at Twitter, or browsing for the perfect playlist in Spotify! Even if you’re regimented with something like the <a href="https://en.wikipedia.org/wiki/Pomodoro_Technique">Pomodoro technique</a>, it can still be easy to overrun on the rest periods and get carried away browsing Reddit! Now you can quantify where your time is being spent, and resolve to make positive steps towards being more productive.</p>
<h5>Where can I learn more?</h5>
<p>You can visit the AppTrack page on the KickCode site that includes more details and screenshots <a href="https://kickcode.com/apptrack">here</a>.</p>
<h5>Where can I get it?</h5>
<p>It’s available right now on the <a href="https://itunes.apple.com/us/app/apptrack/id1303655973">macOS App Store</a> for $2.99/£2.99!</p>
<h5>Over to you</h5>
<p>This is just the first version of AppTrack. I’ll be looking to add features to AppTrack in subsequent versions, like being able to differentiate between websites in browsers so you can see how much of your Google Chrome time is Trello and GitHub, and how much is Facebook and YouTube! I welcome any feedback, suggestions, questions or comments though, so please <a href="http://twitter.com/ejdraper">let me know</a>!</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[It's about time]]></title>
            <link>https://ejdraper.com/2017/11/22/its-about-time</link>
            <guid isPermaLink="false">https://ejdraper.com/2017/11/22/its-about-time</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>Well well well. Over four years since my last post here! Time flies when you’re having fun.</p>
<p><em>UPDATE: I’ve since brought across some of my writing from <a href="https://kickcode.com/">kickcode.com</a> so there are a few more posts in the intervening time period now!</em></p>
<p>Looking back over the blog, I’ve done the whole “wow, it’s been ages since I last posted, but I’m going to blog a lot more now!” post a fair few times. So what’s one more?</p>
<p>As a bit of fun, here are some things that have happened since I last blogged here:</p>
<ul>
<li>We had a third child!</li>
<li>Our eldest two children started school</li>
<li>I became a governor at the kids school, and have since gone on to become Chair of Governors</li>
<li>We <em>all</em> (all five of us!) started learning karate with a fantastic local club, grading a number of times, and competing successfully at a variety of competitions - in the case of my eldest two kids, recently competing at an overseas, international level World Championships event and bringing home bronze medals</li>
<li>I finally found a fitness routine that I enjoy and have been able to stick to, with the advice and guidance of a good friend, managing to lose 3.5 stone, and dropping to under 13% body fat in a little over a year</li>
<li>I ran a 10K race, clocking in at around 56 minutes</li>
<li>I got my first (and for the time being, only) tattoo</li>
<li>We returned to Vegas, where we got married ten years ago this year, for a few days break away</li>
<li>Worked on and delivered over 12 different web and mobile apps, some from scratch, and some where I was brought onboard to extend and improve them. Some were long term engagements, and others were small 6-8 week projects to deliver MVP (minimum viable product) prototypes</li>
<li>I’ve learnt React/React Native, the Go programming language, and played around with Rust too</li>
</ul>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with NSTableView]]></title>
            <link>https://ejdraper.com/2015/08/18/working-with-nstableview</link>
            <guid isPermaLink="false">https://ejdraper.com/2015/08/18/working-with-nstableview</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>This article is a look at how to use <strong>NSTableView</strong> when building a Mac app using RubyMotion, and is taken from the <strong>Data</strong> chapter in my book, Building Mac OS X apps with RubyMotion. If you like what you read here, please take a look at my book - in the book we progress further with the following app code to look at Core Data, and then integrate with iCloud. You can also get a free 20+ page Getting Started guide.</p>
<p>A table view can be a good way to start with presenting data in your app, before you customize further or even replace it later if needed. It’s a no-frills, easy to use way to get something up and running. We’ll start by building a simple note taking app, that will just keep the notes in memory and display them in the table view. Create the app using the OS X template as we’ve done before:</p>
<pre><code class="language-plaintext">motion create --template=osx Noteworthy
cd Noteworthy
</code></pre>
<p>First up, let’s add in our favorite user interface gem, <strong>motion-kit</strong>:</p>
<pre><code class="language-plaintext">gem 'motion-kit'
</code></pre>
<p>Then run the following:</p>
<pre><code class="language-plaintext">bundle install
</code></pre>
<p>Then we’ll create our layout file to setup our user interface - here is the code for <strong>app/main_layout.rb</strong>:</p>
<pre><code class="language-plaintext">class MainLayout &#x3C; MotionKit::Layout
  FORM_HEIGHT = 100
  TITLE_HEIGHT = 30
  CONTENT_HEIGHT = 70
  BUTTON_WIDTH = 70
  BUTTON_HEIGHT = 30

  def layout
    add NSView, :form do
      constraints do
        width.equals(:superview)
        height.is(FORM_HEIGHT)

        min_left.is 0
        min_top.is 0
      end

      add NSTextField, :title_text do
        placeholderString "Enter note title"

        constraints do
          width.equals(:superview)
          height.is(TITLE_HEIGHT)

          min_left.is 0
          min_top.is 0
        end
      end

      add NSTextField, :content_text do
        placeholderString "Enter note content"

        constraints do
          width.equals(:superview)
          height.is(CONTENT_HEIGHT)

          min_left.is 0
          min_top.is TITLE_HEIGHT
        end
      end

      add NSButton, :save_button do
        title "Save"

        constraints do
          width.equals(BUTTON_WIDTH)
          height.is(BUTTON_HEIGHT)

          min_right.is 0
          min_bottom.is 0
        end
      end
    end

    add NSScrollView, :scroll_view do
      has_vertical_scroller true

      constraints do
        width.equals(:superview)
        height.equals(:superview).minus(FORM_HEIGHT)

        min_top.is FORM_HEIGHT
      end

      table_view = add(NSTableView, :table_view) do
        row_height 25

        add_column "title" do
          title "Title"
          min_width 150
        end

        add_column "content" do
          title "Content"
        end
      end
      document_view table_view
    end
  end
end
</code></pre>
<p>Most of this should be fairly straightforward if you’ve previously read through my <a href="https://ejdraper.com/2014/12/19/customising-a-mac-os-x-window-further-with-rubymotion-and-motionkit">previous post on motion-kit</a> - we’re just setting up a window with the top section containing form fields for creating a new note, with a button to save it, and the bottom section is a table view inside a scroll view, so that when there is more content in the table than there is room in the window, you can scroll through it easily. We’re setting up two columns in the table view, <strong>title</strong> and <strong>content</strong>.</p>
<p>After that, we’ll update our <strong>AppDelegate</strong>, adding the following to the end of our <strong>applicationDidFinishLaunching</strong>:</p>
<pre><code class="language-plaintext">@title_text = @layout.get(:title_text)
@content_text = @layout.get(:content_text)

@notes = []
@table_view = @layout.get(:table_view)
@table_view.delegate = self
@table_view.dataSource = self

@save_button = @layout.get(:save_button)
@save_button.target = self
@save_button.action = 'note_save:'
</code></pre>
<p>We’re grabbing references to the controls we need to interact with, and then we’re following that up by ensuring that the <strong>AppDelegate</strong> itself acts as both the delegate, and data source for our table view - we’ll come back to that in a minute. Then we’re setting up the save button to call a method on the <strong>AppDelegate</strong>, called <strong>note_save</strong>. That method looks like this:</p>
<pre><code class="language-plaintext">def note_save(sender)
  title = @title_text.stringValue
  content = @content_text.stringValue
  return if title.nil? || title.empty? ||
</code></pre>
<p>content.nil? || content.empty?</p>
<pre><code class="language-plaintext">@notes &#x3C;&#x3C; {:title => title, :content => content}
  @table_view.reloadData
  @title_text.stringValue = ""
  @content_text.stringValue = ""
end
</code></pre>
<p>Nothing too tricky here - we’re validating the inputs first of all, then adding a note to our <strong>@notes</strong> array as a simple hash with <strong>:title</strong> and <strong>:content</strong> keys. We’ll reload the table view so that it updates to show the new note, and then we’ll clear out the text fields ready for the next note. All that remains now is to implement a couple of methods we need to handle the table view itself - specifically, we’re going to be making sure we conform to the base necessities required for the <strong>NSTableViewDataSource</strong> and <strong>NSTableViewDelegate</strong> protocols. For the former, we need to add the following very simple method:</p>
<pre><code class="language-plaintext">def numberOfRowsInTableView(table_view)
  @notes.length
end
</code></pre>
<p>This just ensures that we’re telling the table view how many rows we have based on our notes in our <strong>@notes</strong> array. The next method we need, and final bit of code we have to add to see all of this working, is a little bit more involved:</p>
<pre><code class="language-plaintext">def tableView(table_view, viewForTableColumn: column,
</code></pre>
<p>row: row) result = table_view.makeViewWithIdentifier(column.identifier, owner: self) if result.nil? result = NSTextField.alloc.initWithFrame([[0, 0], [column.width, 0]]) result.identifier = column.identifier result.editable = false end result.stringValue = @notes[row][column.identifier.to_sym] result end</p>
<p>This is called for each column, in each row - i.e. for every one of our configured columns in our layout (we have two, title and content), and then for however many rows we have based on the previous method we defined that looks at the length of the <strong>@notes</strong> array. We’re calling <strong>makeViewWithIdentifier</strong> to see if we already have a view we can use in the pool, utilizing the built-in table view recycling to avoid creating too many controls. This is important, especially if you’re building an app that might ultimately have hundreds or thousands of rows perhaps, and/or a lot of columns.</p>
<p>If we can’t find a view to use, we’ll set one up. We don’t need to worry about any frame dimensions besides the width which we can ascertain from the configured column width, and likewise we set the identifier to match the column too. In this case we don’t want the text fields editable. Lastly, regardless of how we got our view, the final thing to do is to set the string value contents of the cell - we’re effectively indexing into our <strong>@notes</strong> array by both the row (to find the right note), and then using the column identifier to find the right key in our note hash to get the contents. We just have to return our control, and we’re done!</p>
<p>If you fire up the app now, you’ll see that we have the form, and an empty table. Entering a note without filling in both fields doesn’t save, and filling in both fields and hitting save then clears the fields, and adds the note to our table below. You can keep adding as many notes as you’d like!</p>
<p><img src="https://ejdraper.com/images/nstableview_noteworthy.png" alt="NSTableView displaying notes, with form fields for adding a note above"></p>
<p>This is a fairly simple table view implementation, and of course you can customize an awful lot about the table view to make it more useful, to make it look nicer, and to make it better suit your purposes.</p>
<p>If you quit the app and restart it though, you’ll see all of our precious notes have disappeared. That’s where Core Data would come in handy!</p>
<p>You can see the code for this section <a href="https://github.com/kickcode/Noteworthy/tree/table_view">here</a>.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dragging and dropping into your RubyMotion Mac OS X app]]></title>
            <link>https://ejdraper.com/2015/05/20/dragging-and-dropping-into-a-rubymotion-mac-os-x-app</link>
            <guid isPermaLink="false">https://ejdraper.com/2015/05/20/dragging-and-dropping-into-a-rubymotion-mac-os-x-app</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>In this tutorial we’re going to look at how to setup your app to receive drag and drop events - so that you can receive data simply by the user dragging something into a predefined area of your application user interface.</p>
<p>This can be quite useful if your app needs a file input, requires a URL, or expects some text input, amongst other things. We’ll look at how to setup an area to accept the drag and drop, and how to receive and process data, separating files, from URLs, from plain old text. We’ll also look at how to update your user interface to feedback to the user the status of the drag and drop operation.</p>
<h3>Setting up a space</h3>
<p>Let’s setup a demo app that we’ll use for the rest of this tutorial:</p>
<pre><code class="language-plaintext">motion create --template=osx DragAndDropDemo
cd DragAndDropDemo
</code></pre>
<p>Now before we do anything in <strong>AppDelegate</strong>, let’s setup a new view type, inheriting from <strong>NSImageView</strong>:</p>
<pre><code class="language-plaintext">class DragAndDropView &#x3C; NSImageView
end
</code></pre>
<p>This is what we’ll use as our area to receive drag and drops, and we’ll be building it out like a little control we can re-use and drop wherever it is needed. For our purposes, we’ll just make sure it sits in the center of our default app window created as part of the RubyMotion OS X template. Add our drag and drop view setup to the end of <strong>applicationDidFinishLaunching</strong>:</p>
<pre><code class="language-plaintext">@drag_and_drop = DragAndDropView.alloc.initWithFrame(CGRectZero)
self.set_drag_and_drop_frame
@mainWindow.contentView.addSubview(@drag_and_drop)
</code></pre>
<p>This sets up the view, and adds it to the window. As we’ve done in previous tutorials, we’ll handle resizing by managing the view frame in a separate method (<strong>set_drag_and_drop_frame</strong>) we can call from both the initial setup, and from the window resize handler. Speaking of that, let’s go ahead and make sure the <strong>AppDelegate</strong> is acting as the delegate for our <strong>@mainWindow</strong> by adding this to the bottom of the <strong>buildWindow</strong> method:</p>
<pre><code class="language-plaintext">@mainWindow.delegate = self
</code></pre>
<p>Then we’ll add the <strong>windowDidResize</strong> method to call the frame update too:</p>
<pre><code class="language-plaintext">def windowDidResize(sender)
  self.set_drag_and_drop_frame
end
</code></pre>
<p>Lastly, we need our <strong>set_drag_and_drop_frame</strong> method to initialize the control frame:</p>
<pre><code class="language-plaintext">def set_drag_and_drop_frame
  window_size = @mainWindow.frame.size
  drag_and_drop_size = [200, 200]
  @drag_and_drop.frame = [
    [
      (window_size.width / 2.0) - (drag_and_drop_size[0] / 2.0),
      (window_size.height / 2.0) - (drag_and_drop_size[1] / 2.0)
    ],
    drag_and_drop_size
  ]
end
</code></pre>
<p>So now we’ve got our view setup, we can run the app - our view doesn’t display or do anything, so it won’t look any different yet!</p>
<p>[<a href="https://github.com/kickcode/DragAndDropDemo/commit/13080b10508ad80c7434acddcd10ff0037b28fde">code</a>]</p>
<h3>Setting up for user feedback</h3>
<p>Before we implement our actual dragging functionality, we’ll add some custom code to provide better feedback to the user when something is being dragged in to the app. Our <strong>DragAndDropView</strong> is a subclass of the <strong>NSImageView</strong>, and we’ll want to keep the image rendering capability (as we’ll be using that later), but for now we can override the drawing of the control to provide a highlight stroke effect, and we’ll toggle that on and off as needed to indicate a drag in progress.</p>
<p>First things first, let’s keep a variable as to whether we should be rendering the highlight or not, and provide a helper method for turning the highlight on, and one for turning the highlight off:</p>
<pre><code class="language-plaintext">def highlight!
  @highlight = true
  self.needsDisplay = true
end

def unhighlight!
  @highlight = false
  self.needsDisplay = true
end
</code></pre>
<p>After we set the variable, in each case we trigger a re-render by setting <strong>needsDisplay</strong> to true.</p>
<p>Then we’ll override <strong>drawRect</strong> to actually render the highlight:</p>
<pre><code class="language-plaintext">def drawRect(frame)
  super(frame)

  if @highlight
    NSColor.grayColor.set
    NSBezierPath.setDefaultLineWidth(5)
    NSBezierPath.strokeRect(frame)
  end
end
</code></pre>
<p>As we can see here, we’re calling <strong>super</strong> to keep the existing <strong>NSImageView</strong> render functionality, but in addition to that, if the highlight functionality is enabled, we’re drawing a rectangle stroke effect in gray around the control itself.</p>
<p>Running the app right now won’t show anything different yet - we still need to handle drag operations!</p>
<h3>Handling inputs</h3>
<p>Now we need to customize our view so it indicates that it can act as a receiver for dragging, this is done with the <strong>NSDraggingDestination</strong> protocol. The nice thing about using RubyMotion is that we don’t need to explicitly declare protocols we want to implement in our classes, we just need to make sure we implement the required methods. In this case, it means adding four methods to our <strong>DragAndDropView</strong> control - <strong>draggingEntered</strong>, <strong>draggingExited</strong>, <strong>prepareForDragOperation</strong> and <strong>performDragOperation</strong>. Let’s take a look at each one in turn to figure out what they are doing, and how we can use them to implement the functionality we want, which to begin with will just be supporting the dragging of files into our app:</p>
<pre><code class="language-plaintext">def draggingEntered(info)
  self.highlight!
  NSDragOperationCopy
end
</code></pre>
<p><strong>draggingEntered</strong> is fairly self explanatory - this fires when we drag something over the top of our control. In this case, we do two things - firstly we highlight our control to give the user some feedback that they are dragging into the right area, and secondly we need to return an indicator of what we can do with the data being given to us. In our case, we just want to display and acknowledge that we have it, and not have any effect on the original source of the data, and so we specify <strong>NSDragOperationCopy</strong>. You can inspect the <strong>info</strong> which is an object of type <strong>NSDraggingInfo</strong>, and validate it to decide what kind of operation (if any) you want to allow for it. If you want to be able to modify the source through the dragging action, there are other options such as <strong>NSDragOperationMove</strong> and <strong>NSDragOperationDelete</strong>. If you don’t want to allow the drag, you can return <strong>NSDragOperationNone</strong> instead.</p>
<pre><code class="language-plaintext">def draggingExited(info)
  self.unhighlight!
end
</code></pre>
<p>This too is fairly straightforward - <strong>draggingExited</strong> fires when the drag leaves our control area, so we’ll unhighlight our control. A user might be dragging the object elsewhere, or have decided against the drag before releasing it.</p>
<pre><code class="language-plaintext">def prepareForDragOperation(info)
  self.unhighlight!
end
</code></pre>
<p><strong>prepareForDragOperation</strong> fires when the drag is released and is going to happen, so we can perform any preparatory steps. In this case, we need to unhighlight the control as the dragging itself is over, and it hasn’t left the control area to be able to fire <strong>draggingExited</strong>, so we can do that now.</p>
<pre><code class="language-plaintext">def performDragOperation(info)
  if info.draggingSource != self
    if NSImage.canInitWithPasteboard(info.draggingPasteboard)
      image = NSImage.alloc.initWithPasteboard(info.draggingPasteboard)
    else
      image = NSImage.imageNamed("file_icon")
    end
    self.setImage(image)
  end
end
</code></pre>
<p>This is the meat of the actual drag operation - <strong>performDragOperation</strong> is where we can action and process the data. It’s worth noting that setting the image like this isn’t strictly necessary - if you implement the first three methods, but not <strong>performDragOperation</strong>, and test by dragging an image file over to the control, you’ll see it still works. It’s basically setting the image of the control to the incoming file by default. However, we want to ensure that other files are received, and that in those cases we display a file icon to let the user know we’ve received them, even if we can’t display them. If you try that without this method, you’ll see that it really only works for images. We also want to extend the functionality later on to do a whole lot more!</p>
<p>So we’re ensuring first of all that the source of the dragging operation isn’t ourselves (i.e. dragging the current image from the control), and then we see if it’s an image or not. If it is, we’ll display it, and if not, we’ll display the file icon instead.</p>
<p>Make sure to copy the <strong>file_icon.png</strong> from the code below into your <strong>resources</strong> folder for your app.</p>
<p>Fire it up and try dragging across files - images, and other types, and see how it reacts!</p>
<p><img src="https://ejdraper.com/images/drag_and_drop_demo-initial_drag.png" alt="Initial drag receiver setup"></p>
<p>[<a href="https://github.com/kickcode/DragAndDropDemo/commit/a0944a6927deee56374f245a92122080f7a50959">code</a>]</p>
<h3>Processing files</h3>
<p>Now, you may have noticed that in the above, besides setting the image on the imageview if the dragged in file is an image, we’re not actually doing anything with the incoming data. So we’ll add a mechanism to our <strong>DragDropView</strong> that’ll bubble up some events we can hook into from our <strong>AppDelegate</strong> to handle the incoming data. But before we do, let’s setup some additional UI that we’ll use when handling those events, to feed back to the user.</p>
<p>We’ll add a label below our drag and drop field, which will serve two purposes - initially, to guide the user to dragging a file to the area above the label, and also to update with information about the data dragged in.</p>
<p>At the end of our <strong>applicationDidFinishLaunching</strong>, add the following:</p>
<pre><code class="language-plaintext">@label = NSTextField.alloc.initWithFrame(CGRectZero)
@label.bezeled = false
@label.drawsBackground = false
@label.editable = false
@label.selectable = false
@label.alignment = NSCenterTextAlignment
@label.stringValue = "Drag a file above"
self.set_label_frame
@mainWindow.contentView.addSubview @label
</code></pre>
<p>As we’ve seen before, this uses the <strong>NSTextField</strong> control, and tweaks a few settings to provide a read-only label for us to use.</p>
<p>We then need to add our <strong>set_label_frame</strong> method to setup the frame itself:</p>
<pre><code class="language-plaintext">def set_label_frame
  window_size = @mainWindow.frame.size
  label_size = [200, 50]
  @label.frame = [
    [(window_size.width / 2.0) - (label_size[0] / 2.0), @drag_and_drop.frame.origin.y - label_size[1]],
    label_size
  ]
end
</code></pre>
<p>Then, we’ll add a call to <strong>set_label_frame</strong> to our resize handler <strong>windowDidResize</strong>:</p>
<pre><code class="language-plaintext">def windowDidResize(sender)
  self.set_drag_and_drop_frame
  self.set_label_frame
end
</code></pre>
<p>Now if you fire up the app, you’ll see the label sat underneath our drag and drop control.</p>
<p><img src="https://ejdraper.com/images/drag_and_drop_demo-label.png" alt="Label"></p>
<p>[<a href="https://github.com/kickcode/DragAndDropDemo/commit/f48172149ab389831d2242c53f6c9b70f628f972">code</a>]</p>
<p>Let’s extend our <strong>DragDropView</strong> to allow a delegate to be specified, and to raise an event on the delegate when we receive data. First of all, we need to add an attribute accessor to be able to specify the delegate class on the control:</p>
<pre><code class="language-plaintext">class DragAndDropView &#x3C; NSImageView
  attr_accessor :delegate
</code></pre>
<p>Next up, we’ll add a method that’ll be used to call methods on our delegate, that’ll provide the necessary checks that we need. Add the following to our <strong>DragDropView</strong> as well:</p>
<pre><code class="language-plaintext">def send_delegate_event(name, arg)
  return if self.delegate.nil?
  return unless self.delegate.respond_to?(name.to_sym)

  self.delegate.send(name.to_sym, arg)
end
</code></pre>
<p>This only sends the call to the specified delegate method if the delegate itself is set, and if an appropriate method is defined on the delegate to handle our event. We’re defining things like this because later on we’re going to add additional events for different types of data that we can receive, and ultimately we might want our <strong>AppDelegate</strong> to only respond to certain events, and not to error if we don’t answer the call for other events. This is similar to how delegates work for built-in controls and events - we can set <strong>AppDelegate</strong> as the delegate for a text field for example, and define methods to handle events such as text field editing ending - but if we don’t set the delegate, or don’t define the method to handle the event, we don’t end up with an error or a crash.</p>
<p>Now all that remains on the control side of things is to hook into the <strong>performDragOperation</strong>, extract the useful information and bubble that up as a delegate method call. In that method, and below our call to <strong>setImage</strong>, we’ll add the following:</p>
<pre><code class="language-plaintext">if info.draggingPasteboard.types.include?('NSFilenamesPboardType')
  files = info.draggingPasteboard.propertyListForType('NSFilenamesPboardType')
  self.send_delegate_event(:drag_received_for_file_paths, files)
end
</code></pre>
<p>So here we’re validating what type of data we have and making sure we’ve received a drag that contains one or more filenames specified. As we’ll see later on, we’ll be adding to this to check for differing types of data, and thus extracting the data and raising events differently for each, allowing us to respond to different data sources in separate ways. In this case, if it is a pasteboard containing <strong>NSFilenamesPboardType</strong>, we can then load up the property list supplied for that pasteboard type, which then contains an array of the files dragged in, which is what we expose in our event call, named <strong>drag_received_for_file_paths</strong>.</p>
<p>Back in our <strong>AppDelegate</strong>, we now just need to set ourselves as the delegate for our drag and drop control, so where we define the <strong>@drag_and_drop</strong> instance, add:</p>
<pre><code class="language-plaintext">@drag_and_drop.delegate = self
</code></pre>
<p>Then, we’ll implement a method called <strong>drag_received_for_file_paths</strong>:</p>
<pre><code class="language-plaintext">def drag_received_for_file_paths(paths)
  @label.stringValue = "Received: #{paths.join(',')}"
end
</code></pre>
<p>This just updates the label to list the file(s) that we’ve received in the drag operation. Try it out - drag one file, or a few files, and see it in action!</p>
<p><img src="https://ejdraper.com/images/drag_and_drop_demo-handling_files.png" alt="Handling files"></p>
<p>[<a href="https://github.com/kickcode/DragAndDropDemo/commit/aafbd686cc49a8eeea04642ddae56e5126fa9bc9">code</a>]</p>
<h3>Handling text</h3>
<p>Let’s extend our <strong>DragAndDropView</strong> now to handle text dragged in too. If you fire it up and try dragging across some text from a text editor, or selected text from a browser, you’ll see that it doesn’t respond to the drag. None of our handling fires, and the data sort of “pings back”, indicating it’s not being received. This is because by default, the <strong>NSImageView</strong> we’re inheriting from for our control responds to certain drag types (i.e. files), but we have to tell it we want it to respond to additional types. Add the following method to our <strong>DragAndDropView</strong> class:</p>
<pre><code class="language-plaintext">def initWithFrame(frame)
  super(frame)

  self.registerForDraggedTypes([NSStringPboardType])

  self
end
</code></pre>
<p>Here we’re overriding the initialization method, calling the original one first, and then taking the opportunity to register an additional dragged type - <strong>NSStringPboardType</strong>. This will allow us to receive text. Fire up the app now, and you’ll see dragging across some text <em>works</em>, in as much as the control is highlighted when we drag it across (as it is when we’re dragging files), and also if we drop it, we don’t see any errors in our console log. The data itself though isn’t processed in any way, so let’s do that by raising a new delegate event we can handle. In our <strong>performDragOperation</strong>, add the following to the end (but inside the outermost <strong>if</strong> statement):</p>
<pre><code class="language-plaintext">text = info.draggingPasteboard.stringForType(NSPasteboardTypeString)
self.send_delegate_event(:drag_received_for_text, text) unless text.nil?
</code></pre>
<p>We’re using <strong>stringForType</strong> and passing in <strong>NSPasteboardTypeString</strong> to represent our request to see if there is any text in the dragging pasteboard. If there is, we publish that up to the delegate with a new event, <strong>drag_received_for_text</strong>.</p>
<p>Finally, as before, we just need to add our delegate event handler to <strong>AppDelegate</strong>:</p>
<pre><code class="language-plaintext">def drag_received_for_text(text)
  @label.stringValue = "Received: #{text}"
end
</code></pre>
<p>Now if we fire up the app, and drag across some text, we’ll see it listed in the label. File dragging still works also, and any new drag just replaces the contents of the old one.</p>
<p><img src="https://ejdraper.com/images/drag_and_drop_demo-handling_text.png" alt="Handling text"></p>
<p>[<a href="https://github.com/kickcode/DragAndDropDemo/commit/132750c6e4f23f4a59913756c5bae09c3f0943a6">code</a>]</p>
<h3>Handling URLs</h3>
<p>The last data type we’ll add in for this demo is dragging in URLs, for example dragging in a URL from a browser address bar. Again, as with the text, we need to register a new dragged type for this to work - <strong>NSURLPboardType</strong>. So we’ll update our call to <strong>registerForDraggedTypes</strong> to look like this:</p>
<pre><code class="language-plaintext">self.registerForDraggedTypes([NSStringPboardType, NSURLPboardType])
</code></pre>
<p>Next up, in <strong>performDragOperation</strong>, below the text handling code we just added, add the following:</p>
<pre><code class="language-plaintext">url = NSURL.URLFromPasteboard(info.draggingPasteboard)
self.send_delegate_event(:drag_received_for_url, url.absoluteString) unless url.nil?
</code></pre>
<p>As with the text, this is fairly straightforward - we instantiate a URL from the pasteboard, and assuming we got one, we bubble that up to a new event <strong>drag_received_for_url</strong>.</p>
<p>And then the final step is to implement that event handler in <strong>AppDelegate</strong>:</p>
<pre><code class="language-plaintext">def drag_received_for_url(url)
  @label.stringValue = "Received: #{url}"
end
</code></pre>
<p>Really simple again, we’re just responding to it and displaying the URL in the label. This means that by and large, our three event handlers are roughly the same, but in a real application you’d most likely go on to perform something slightly different for each data type, which is why we’ve structured it so that they are handled, raised and trapped as separate events.</p>
<p><img src="https://ejdraper.com/images/drag_and_drop_demo-handling_urls.png" alt="Handling URLs"></p>
<p>[<a href="https://github.com/kickcode/DragAndDropDemo/commit/5c51eaa38693238e65c18e6d4d29975a939dfad2">code</a>]</p>
<p>If you run the app now, you’ll see URL drags from the browser address bar work into our app now. Interestingly though, if you test file drags, you’ll see the URLs that are being displayed aren’t the original URLs, it’s an odd looking <em>file:///.file/id=?</em> URL. This is because the code we added for the URL handling will also work on the file drag operations too - effectively, both event types, <strong>drag_received_for_file_paths</strong> and <strong>drag_received_for_url</strong> will be raised, with <strong>drag_received_for_url</strong> handled last, and thus overwriting the label display with the funky looking URL.</p>
<p>Let’s switch out our URL handling for the following instead:</p>
<pre><code class="language-plaintext">url = info.draggingPasteboard.propertyListForType('public.url')
self.send_delegate_event(:drag_received_for_url, url) unless url.nil?
</code></pre>
<p>[<a href="https://github.com/kickcode/DragAndDropDemo/commit/8512d2ab357aa2ab32abd47bf78f203928a64880">code</a>]</p>
<p>Now if you run and test it, you’ll see that files display the proper path, while the URL dragging also works. It seems therefore that consulting the ‘public.url’ property on the pasteboard is a more accurate way to go and differentiate between those two types of dragging. When looking at the data for a specific type of drag operation, it’s worth either assigning the <strong>info</strong> var passed to us in <strong>performDragOperation</strong> to a variable that you can access and play with on the console while testing, or to log out the available types at least with a statement like this:</p>
<pre><code class="language-plaintext">NSLog("TYPES: #{info.draggingPasteboard.types.join(', ')}")
</code></pre>
<p>That will show you what types are available, and inspecting those further with <strong>propertyListForType</strong> will let you see what data is provided. It also seems that the text handling can read the URL as the string contents of the pasteboard, so you might be seeing both <strong>drag_received_for_url</strong> and <strong>drag_received_for_text</strong> fire with the URL passed as an argument - we can tidy up our handling still further to ensure we’re only ever raising one event. Below our <strong>setImage</strong> call in <strong>performDragOperation</strong>, replace what we have with the following:</p>
<pre><code class="language-plaintext">if info.draggingPasteboard.types.include?('NSFilenamesPboardType')
  files = info.draggingPasteboard.propertyListForType('NSFilenamesPboardType')
  self.send_delegate_event(:drag_received_for_file_paths, files)
elsif info.draggingPasteboard.types.include?('public.url')
  url = info.draggingPasteboard.propertyListForType('public.url')
  self.send_delegate_event(:drag_received_for_url, url) unless url.nil?
else
  text = info.draggingPasteboard.stringForType(NSPasteboardTypeString)
  self.send_delegate_event(:drag_received_for_text, text) unless text.nil?
end
</code></pre>
<p>This now just means we’re matching in a sort of priority order - first filenames, then the URL, then finally falling back on the string contents of the pasteboard. As a result of daisy chaining the conditional statements though, once we have a match, no other processing happens, which results in a more reliable result for the consumer of these events, in this case, our <strong>AppDelegate</strong>.</p>
<p>[<a href="https://github.com/kickcode/DragAndDropDemo/commit/aacf671d7626b7766932ca207ab90968d9168db3">code</a>]</p>
<h3>More detailed URL handling</h3>
<p>One thing that I spotted only when investigating the available types for a URL was that there was an additional type that included not just the URL, but the title of the webpage from the browser too! Let’s add that in as an additional event, as that could be quite useful. First of all, as this would be an event with two arguments (URL and title), let’s update our <strong>send_delegate_event</strong> helper method to support that:</p>
<pre><code class="language-plaintext">def send_delegate_event(name, *args)
  return if self.delegate.nil?
  return unless self.delegate.respond_to?(name.to_sym)

  self.delegate.send(name, *args)
end
</code></pre>
<p>We’ve changed the <strong>arg</strong> to instead be <strong>*args</strong>, which acts as an argument list, that we’re then passing straight through when we call the delegate method. We can now have methods that have 1 argument, 2 arguments, or 10 arguments!</p>
<p>Now let’s add our extended URL handling - we’re going to add this to our daisy chained conditionals, above the existing URL support which we’ll leave in place in case there are any URL dragging operations that don’t provide this additional data (it will most likely depend on which browser or app you’re dragging the URL from):</p>
<pre><code class="language-plaintext">elsif info.draggingPasteboard.types.include?('WebURLsWithTitlesPboardType')
  url, title = info.draggingPasteboard.propertyListForType('WebURLsWithTitlesPboardType').flatten
  self.send_delegate_event(:drag_received_for_url_and_title, url, title)
</code></pre>
<p>As you can see here, we’re checking for a specific new type, <strong>WebURLsWithTitlesPboardType</strong>, and if that’s available, it’ll come back as an array in this format:</p>
<pre><code class="language-plaintext">[["url", "title"]]
</code></pre>
<p>Therefore we flatten it to get just a single array, and extract our URL and title, which we bubble up with a new delegate event, <strong>drag_received_for_url_and_title</strong>, and pass both arguments. To handle this now, we just need to implement the handler on our <strong>AppDelegate</strong>:</p>
<pre><code class="language-plaintext">def drag_received_for_url_and_title(url, title)
  @label.stringValue = "Received: #{url}"
  @mainWindow.title = title
end
</code></pre>
<p>Here we’re once again putting the URL in the label to feed back to the user, but to make things a bit more interesting, we’re setting our actual app window title to the title we receive from the URL web page drag. If you test that now, you’ll see that in fact the window title changes to reflect the page that was dragged in!</p>
<p>[<a href="https://github.com/kickcode/DragAndDropDemo/commit/01adfd330116c2b658ed9fbfcff873891894c439">code</a>]</p>
<h3>Improving the visual feedback</h3>
<p>The last thing we’ll look at in our demo app here is to improve the user visual feedback, so that the icon shown on the image view changes for different types of drag operation - right now, an image is displayed if it’s an image file, and anything else results in the file icon. Let’s add a text icon and a URL icon to differentiate between those drag operations also. It’ll take a bit of tweaking of our <strong>performDragOperation</strong> method, so here is how it should look in full to make this happen:</p>
<pre><code class="language-plaintext">def performDragOperation(info)
  if info.draggingSource != self
    image = NSImage.alloc.initWithPasteboard(info.draggingPasteboard)
      if NSImage.canInitWithPasteboard(info.draggingPasteboard)

    if info.draggingPasteboard.types.include?('NSFilenamesPboardType')
      files = info.draggingPasteboard.propertyListForType('NSFilenamesPboardType')
      self.send_delegate_event(:drag_received_for_file_paths, files)
    elsif info.draggingPasteboard.types.include?('WebURLsWithTitlesPboardType')
      url, title = info.draggingPasteboard.propertyListForType('WebURLsWithTitlesPboardType').flatten
      self.send_delegate_event(:drag_received_for_url_and_title, url, title)
      image = NSImage.imageNamed("url_icon")
    elsif info.draggingPasteboard.types.include?('public.url')
      url = info.draggingPasteboard.propertyListForType('public.url')
      self.send_delegate_event(:drag_received_for_url, url) unless url.nil?
      image = NSImage.imageNamed("url_icon")
    else
      text = info.draggingPasteboard.stringForType(NSPasteboardTypeString)
      self.send_delegate_event(:drag_received_for_text, text) unless text.nil?
      image = NSImage.imageNamed("text_icon")
    end

    image ||= NSImage.imageNamed("file_icon")
    self.setImage(image)
  end
end
</code></pre>
<p>Breaking it down, we’re setting our image to be the image itself if the pasteboard is an image file. Otherwise, inside of our daisy chained conditionals for matching different drag types, we’re setting the appropriate image. For the files, we’re not setting an image - it’ll either already be set if it’s an image file, or we’ll be using the file icon as a default anyway, which we’ll come back to in a second.</p>
<p>For the two URL handling conditionals, and the string/text handling, we’re setting either the <strong>url_icon</strong> or <strong>text_icon</strong> image. Lastly, as we just mentioned, if no other image is set already, we’ll use the <strong>file_icon</strong> as a default so we show something, before setting the image as our final action now in <strong>performDragOperation</strong>.</p>
<p>As before, copy the additional icons (<strong>url_icon.png</strong> and <strong>text_icon.png</strong>) from the code below into the <strong>resources</strong> directory in your app before running it.</p>
<p>If you run the app now and try dragging in various different data sources, you’ll see that as well as the label (and for URLs with titles, the window title) changing, the icon will update to reflect the source too, which provides additional user feedback.</p>
<p><img src="https://ejdraper.com/images/drag_and_drop_demo-better_icons-text.png" alt="Better icon for handling text"></p>
<p><img src="https://ejdraper.com/images/drag_and_drop_demo-better_icons-urls.png" alt="Better icon for handling URLs"></p>
<p>[<a href="https://github.com/kickcode/DragAndDropDemo/commit/755e29889927e0259cc1cd900d5b55d954fc0beb">code</a>]</p>
<h3>Wrapping up</h3>
<p>So now we have a demo app that can receive multiple data types dragged over to it, providing feedback to the user that it can receive that drag, and then updating further when it’s received and processed the data. Additionally, we’ve done this with a re-usable drag and drop image view control, that handles the processing of the drag operations, provides visual feedback by changing the icon shown (or showing an image file), and bubbles up various events so that a consumer app can receive more data about drag events and act accordingly. From here you could build an app that took files and uploaded them, scanned text to provide useful analysis, or altered images in a common way for repeatable tasks!</p>
<p>If you’ve enjoyed the content here, remember that early access orders for my forthcoming book, Building Mac OS X apps with RubyMotion, open up on June 8th - make sure you’re subscribed to the mailing list so you can get a launch discount! Any comments or questions, please drop them below, or tweet me <a href="http://twitter.com/ejdraper">@ejdraper</a>.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[User specified custom key combination for a global hotkey]]></title>
            <link>https://ejdraper.com/2015/05/13/custom-user-hotkey-combo</link>
            <guid isPermaLink="false">https://ejdraper.com/2015/05/13/custom-user-hotkey-combo</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>Over a year ago, I covered global hotkeys in <a href="https://ejdraper.com/2014/03/23/global-hotkeys-for-mac-os-x-apps-in-rubymotion">a tutorial</a> on this very blog. However, handling a global hotkey combo is only half of the story - I’m sure in most apps you’ve seen that provide that kind of functionality, the app also allows the user to override the default, and specify their own key combination to use instead. How do they do it? We’re going to build on the app we already created in that tutorial (the code is <a href="https://github.com/kickcode/HotkeyDemo">here</a>) to find out.</p>
<h3>DDHotKey, revisited</h3>
<p>The library we used in the last tutorial on global hotkeys, that provided a nice and neat wrapper around the old Carbon APIs for hotkeys, also provides a ready-to-use UI component for user input of hotkeys! The only thing we need to figure out is how we integrate with it, and how we store the users chosen key combination for use between app sessions. Let’s start with the UI.</p>
<p>We’re going to add the <strong>DDHotKeyTextField</strong> to the window, so at the end of our <strong>buildWindow</strong> method, we’ll set it up like this:</p>
<pre><code class="language-plaintext">size = @mainWindow.frame.size
field_size = [150, 30]
@hot_key_field = DDHotKeyTextField.alloc.initWithFrame(
  [
    [(size.width / 2.0) - (field_size[0] / 2.0), (size.height / 2.0) - (field_size[1] / 2.0)],
    field_size
  ])
@hot_key_field.delegate = self

@mainWindow.contentView.addSubview(@hot_key_field)
</code></pre>
<p>Nothing too complex there - we’re centering the field in our window, setting the <strong>AppDelegate</strong> to be the delegate for the field, and adding it to our window.</p>
<p>Next up, we need a method to register our hotkeys. This will serve two purposes - it’s what we’ll call when we detect a new hotkey set using our <strong>DDHotKeyTextField</strong>, and we’ll also switch the initial hotkey registration for the app to use it too, for consistency:</p>
<p>def registerHotKey(keyCode, modifierFlags) center = DDHotKeyCenter.sharedHotKeyCenter center.unregisterAllHotKeys center.registerHotKeyWithKeyCode( keyCode, modifierFlags: modifierFlags, target: self, action: ‘handleHotkey:’, object: nil) end</p>
<p>This should be fairly simple to follow based on how we were registering hotkeys before - basically we’re passing in the key code and modifier flags that describes the hotkey combo; we’re grabbing the hotkey center, this time firstly unregistering all existing hotkeys (remember this will be called when changing the hotkey so we need to remove any existing combo), and then registering the hotkey pointing to our handle hotkey method, <strong>handleHotKey</strong>, for when it is triggered.</p>
<p>Let’s change the initial app setup to use this method to make sure it’s working. In <strong>applicationDidFinishLaunching</strong>, we’ll replace our <strong>registerHotKeyWithKeyCode</strong> call to the <strong>DDHotKeyCenter</strong> with a call to our new <strong>registerHotKey</strong> method:</p>
<pre><code class="language-plaintext">@hot_key_field.hotKey = self.registerHotKey(KVK_ANSI_H, (NSCommandKeyMask | NSAlternateKeyMask))
</code></pre>
<p>Then we need to hook into when the <strong>DDHotKeyTextField</strong> is done being edited, so we can re-register the hotkey. We’ve already set the delegate for the field to the <strong>AppDelegate</strong>, so now all we need to do is define the following method:</p>
<pre><code class="language-plaintext">def controlTextDidEndEditing(notification)
  self.registerHotKey(@hot_key_field.hotKey.keyCode, @hot_key_field.hotKey.modifierFlags) if @hot_key_field.hotKey
end
</code></pre>
<p>This will get called when editing is finished on that field (i.e. when enter is pressed), and it simply calls <strong>registerHotKey</strong> with the current key code and modifier flags for the field hotkey, so long as it exists.</p>
<p>If you fire up the app now, you should see that a default hotkey combo is set, the field allows that to be changed, and when it is changed, the app responds as expected on that new hotkey, instead of the old one.</p>
<p><img src="https://ejdraper.com/images/hotkeydemo_hotkey_field.png" alt="Hotkey field"></p>
<p>[<a href="https://github.com/kickcode/HotkeyDemo/tree/custom_hotkey_field">code</a>]</p>
<h3>Persistence</h3>
<p>You’ll also notice though that shutting down the app and firing it back up restores the default combo, and any user customization is lost. We need to save the key code and modifier flags for any hotkey selected, so that we can use that when the app is restarted, and so if the user has changed it, it stays changed. We’re going to use <strong>NSUserDefaults</strong> to store the key code and modifier flags. First things first then, when a hotkey is registered, let’s store the values. Amend the top of <strong>registerHotKey</strong> to the following:</p>
<pre><code class="language-plaintext">def registerHotKey(keyCode, modifierFlags)
  NSUserDefaults.standardUserDefaults['keyCode'] = keyCode
  NSUserDefaults.standardUserDefaults['modifierFlags'] = modifierFlags
</code></pre>
<p>The key code and modifier flags is all we need to describe the hotkey combo, so we’ll stash those. Next up, let’s add some helper methods for retrieving those values - and we’ll move our defaults into those methods too, for the first run of the app where no values will be set:</p>
<pre><code class="language-plaintext">def userKeyCode
  NSUserDefaults.standardUserDefaults['keyCode'] || KVK_ANSI_H
end

def userModifierFlags
  NSUserDefaults.standardUserDefaults['modifierFlags'] || (NSCommandKeyMask | NSAlternateKeyMask)
end
</code></pre>
<p>So we’re looking up our persisted values, falling back to the same defaults for the key code and modifier flags that we were using before. Now, in <strong>applicationDidFinishLaunching</strong>, we can put into place the final piece of the puzzle. Instead of using our default combo there on every app startup, we’ll refer to these helper methods:</p>
<pre><code class="language-plaintext">@hot_key_field.hotKey = self.registerHotKey(self.userKeyCode, self.userModifierFlags)
</code></pre>
<p>This means that when the app is run for the first time, it’ll fall back on the defaults provided within those helper methods still, but once values are persisted and saved, it’ll use those instead.</p>
<p>Try it out now, fire up the app, change the key combo from <strong>cmd+alt+h</strong> to something else, press enter, restart the app, and then test out your new custom key combo for hiding and showing the app, persisted between app sessions. Power to the users!</p>
<p>[<a href="https://github.com/kickcode/HotkeyDemo/tree/saving_custom_combo">code</a>]</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Previewing video and audio when capturing on Mac OS X with RubyMotion]]></title>
            <link>https://ejdraper.com/2015/05/07/previewing-video-and-audio-when-capturing-on-mac-os-x-with-rubymotion</link>
            <guid isPermaLink="false">https://ejdraper.com/2015/05/07/previewing-video-and-audio-when-capturing-on-mac-os-x-with-rubymotion</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>In the <a href="https://ejdraper.com/2015/05/06/capturing-video-and-audio-on-mac-os-x-with-rubymotion">last article</a> we covered how to capture video and audio from attached devices on Mac OS X using RubyMotion. In this article we’re going to extend our basic <a href="https://github.com/kickcode/AVCapture">AVCapture</a> app to display a preview of the video being captured, and audio levels, so that capturing is more responsive and you can be sure you’re recording what you want to record.</p>
<h3>Previewing video</h3>
<p>First thing first, we’ll need to make room for our preview. Let’s move our button to start and stop recording to the bottom left of the window - we’ll put the video preview above it, and it’ll leave room for our audio levels meter to the right of the button. We’ll add a constant for the button size now so we can refer to it elsewhere, so add this just inside the <strong>AppDelegate</strong> class declaration:</p>
<pre><code class="language-plaintext">class AppDelegate
  BUTTON_SIZE = [150, 30]
</code></pre>
<p>Then change <strong>set_button_frame</strong> to the following:</p>
<pre><code class="language-plaintext">def set_button_frame
  @button.frame = [[0, 0], BUTTON_SIZE]
end
</code></pre>
<p>With the button out of the way, we can then setup the video preview. First of all, we need a view to display it in, so in our <strong>buildWindow</strong> setup method, at the bottom we’ll add the following:</p>
<pre><code class="language-plaintext">bounds = @mainWindow.contentView.bounds
bounds.size.height -= BUTTON_SIZE.last
bounds.origin.y += BUTTON_SIZE.last
@view = NSView.alloc.initWithFrame(bounds)
layer = CALayer.layer
@view.setLayer(layer)
@view.setWantsLayer(true)
@mainWindow.contentView.addSubview(@view)
</code></pre>
<p>end</p>
<p>We’re using the <strong>BUTTON_SIZE</strong> constant to work out the rest of the window area available after the button, and then we’re creating a blank view with that space. We need to setup a default blank layer using <strong>CALayer.layer</strong>, and we need to set <strong>setWantsLayer</strong> to true to be able to be able to add a sublayer which we’ll be doing next from within <strong>didStartRunning</strong>:</p>
<pre><code class="language-plaintext">def didStartRunning
  @video_preview = AVCaptureVideoPreviewLayer.alloc.initWithSession(@session)
  @video_preview.frame = @view.bounds
  @view.layer.addSublayer(@video_preview)

  url = NSURL.alloc.initWithString("file:///Users/#{NSUserName()}/Desktop/temp#{Time.now.to_i}.mp4")
  @output.startRecordingToOutputFileURL(url, recordingDelegate: self)
end
</code></pre>
<p>Before we start our recording, we’re using the <strong>AVCaptureVideoPreviewLayer</strong> class, configured against our <strong>@session</strong>, to be able to create a layer; then we’re setting the bounds to match the view, and then we’re adding it as a sublayer. That’s it!</p>
<p>Run the app now, and when you start recording the captured output appears in the window above our button, and it disappears when we stop our capture session. Pretty cool huh?</p>
<p><img src="https://ejdraper.com/images/avcapture_video_preview.png" alt="Captured video preview"></p>
<p>[<a href="https://github.com/kickcode/AVCapture/tree/video_capture_preview">code</a>]</p>
<h3>Coping with window resizes</h3>
<p>We already handled window resizes for our centered button in the code, based upon our centered button code example <a href="https://ejdraper.com/2014/12/17/how-to-setup-and-position-basic-controls-in-a-mac-os-x-app-window-with-rubymotion">here</a> - however now our button is in the bottom left (and stays there), that is no longer the problem. Instead, our video preview doesn’t properly size up or down on resize when already active. So let’s handle the resize event in the same way, and re-initialize the view holding our video preview layer any time a resize happens to properly update the preview. First things first, let’s add a method to handle the setup and updating of our video preview frame, which we can now call both on initial capture start, as well as on resize, to keep the preview size in sync with the window:</p>
<pre><code class="language-plaintext">def update_video_preview
  if @view
    @video_preview.removeFromSuperlayer if @video_preview
    @view.removeFromSuperview
  end

  bounds = @mainWindow.contentView.bounds
  bounds.size.height -= BUTTON_SIZE.last
  bounds.origin.y += BUTTON_SIZE.last
  @view = NSView.alloc.initWithFrame(bounds)
  layer = CALayer.layer
  @view.setLayer(layer)
  @view.setWantsLayer(true)
  @mainWindow.contentView.addSubview(@view)

  @video_preview.frame = @view.bounds
  @view.layer.addSublayer(@video_preview)
end
</code></pre>
<p>As you can see, we’re coping with an existing <strong>@view</strong> and <strong>@video_preview</strong> layer, removing them from their parent view/layer as appropriate, before using the window bounds (minus the button size) to calculate the room left for the preview - the same as we were doing before. We then add the view, set the video preview layer bounds based on the view we’ve setup, and add the video preview layer as a sublayer. The only thing we’re not doing here is creating the actual video preview layer - this we will do only when the capture session starts, because if we did it in <strong>update_video_preview</strong>, getting called on each resize, we’d find that recreating new video preview layers against the session would actually trigger it to stop recording output for some reason. Seeing as we don’t need to reinitialize that anyway, we just need to remove it from the old view and add it to the new one, then it doesn’t matter too much.</p>
<p>So now we need to reference this when the capture session starts, so that our code works as it did before - the first part of <strong>didStartRunning</strong> should now look like this:</p>
<pre><code class="language-plaintext">def didStartRunning
  @video_preview = AVCaptureVideoPreviewLayer.alloc.initWithSession(@session)
  self.update_video_preview
</code></pre>
<p>We’ll create the video preview layer as before, and then we’ll call our new method for updating the video preview, in this case initialising the view and adding the sublayer to get the output showing. Lastly, we just need to hook things in on resize, as so within <strong>windowDidResize</strong>:</p>
<pre><code class="language-plaintext">def windowDidResize(notification)
  self.set_button_frame
  self.update_video_preview if @is_running
end
</code></pre>
<p>We check to make sure <strong>@is_running</strong> is equal to true, to be sure that it’s worth bothering with a video preview.</p>
<p>Now if you run the app, you’ll see that resizing the window resizes the video output preview in real-time - pretty neat!</p>
<p>One thing we now need to fix though is that with the way this is setup, you’ll notice trying to record more than one video during one run of the app doesn’t work. The first one records fine, and from then on, it doesn’t begin recording. This is because re-initializing the video preview layer in this way each session (while all of the rest of the session and recording setup is unchanged) causes an error (<strong>AVErrorSessionConfigurationChanged</strong> specifically), somewhat similar to how we didn’t want it re-initialised on each window resize or else it’d stop recording. So we’ll change <strong>didStartRunning</strong> so it only sets up <strong>@video_preview</strong> when it doesn’t already exist:</p>
<pre><code class="language-plaintext">def didStartRunning
  @video_preview ||= AVCaptureVideoPreviewLayer.alloc.initWithSession(@session)
</code></pre>
<p>Now when we start multiple recordings in one run of the app, none of the AV related configuration or setup changes, and so we’re free to just start and stop the session and create as many recordings as we want.</p>
<p>When you do get an error that seems to prevent recording (in our app it’ll just keep going back to <strong>Start</strong> and shutting the webcam back off a few seconds after pressing <strong>Start</strong>), you can usually get to the bottom of it from within <strong>didFinishRecordingToOutputFileAtURL</strong>. That will still get called, but you can now use the <strong>error</strong> parameter to see what’s going on. The message isn’t always very useful, but the <strong>code</strong> property will provide a value you can check against the error codes <a href="https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVFoundation_ErrorConstants/index.html#//apple_ref/doc/uid/TP40009935">here</a>, which along with the description of each error further down that document, should give you enough to go on. Those are also very useful of course because in a production ready app, you’d want to cope with a lot of those errors and feed them back to the user, for things such as being out of disk space etc.</p>
<p>[<a href="https://github.com/kickcode/AVCapture/tree/more_robust_video_capture_preview">code</a>]</p>
<h3>Tapping into audio levels</h3>
<p>Next up, let’s use the space to the right of the start/stop button to show an audio level meter. Before we get in to the user interface though, first we’ll look at how to tap into the necessary audio output to poll for audio peak and average levels.</p>
<p>We need to add an audio output, so in <strong>applicationDidFinishLaunching</strong>, below where we setup our movie file output, let’s add this:</p>
<pre><code class="language-plaintext">@audio_output = AVCaptureAudioDataOutput.alloc.init
@session.addOutput(@audio_output) if @session.canAddOutput(@audio_output)
</code></pre>
<p>This creates an audio data output and adds it to the session, ready for us to use. The rate of change for the average power and peak hold levels on audio channels though is so quick that there aren’t any delegate methods or notifications we can hook into to watch for changes, so instead we just need to poll for it - the resolution is up to you and the app you’re building, but in our example we’ll be polling 10 times a second. We’ll do that with a scheduled interval, so add this to the bottom of <strong>applicationDidFinishLaunching</strong>:</p>
<pre><code class="language-plaintext">NSTimer.scheduledTimerWithTimeInterval(0.1,
  target: self,
  selector: 'checkAudioLevels',
  userInfo: nil,
  repeats: true)
</code></pre>
<p>This repeats endlessly while the app is running, and runs every 0.1s. Now we just need to implement <strong>checkAudioLevels</strong> and inspect the audio output:</p>
<pre><code class="language-plaintext">def checkAudioLevels
  return unless @is_running
  sum = 0
  @audio_output.connections.first.audioChannels.each_with_index do |channel, index|
    NSLog "CHANNEL[#{index}]: avg: #{channel.averagePowerLevel}, peak: #{channel.peakHoldLevel}"
    sum += (channel.averagePowerLevel + channel.peakHoldLevel) / 2.0
  end
  avg = sum / @audio_output.connections.first.audioChannels.count
  NSLog "AVERAGE AVERAGE: #{avg}"
end
</code></pre>
<p>Let’s run through what this is doing - firstly we make sure we’re running a capture before we do anything, and if it is, we loop through the channels on the audio outputs connection (it can have only one connection), and we’re logging out the average power and peak hold level. We’re also adding the average of those two values for each channel to a running total, and then creating an average single value based on both average power and peak hold, for all available audio channels, and logging that out too. If you run the app now, then start the session, you’ll notice that any noises make a significant change to the numbers being shown on the console.</p>
<p><img src="https://ejdraper.com/images/avcapture_audio_levels.png" alt="Logging audio levels to the console"></p>
<p>[<a href="https://github.com/kickcode/AVCapture/tree/tapping_into_audio_levels">code</a>]</p>
<h3>Displaying audio levels visually</h3>
<p>So we have the data, but we need a way of displaying that to the user so that they can see that audio levels are as expected. We’re going to use a simple custom meter control that I created to display the levels - the idea being that it’s a bar, with color thresholds such that normal volume shows green, louder shows yellow, and extremely noisy shows as red. The code for the control itself is available <a href="https://github.com/kickcode/motion-meter">here</a>, and you’ll be able to see a bit more about how it works in a chapter in my forthcoming book.</p>
<p>First things first then, let’s add the gem we need to our <strong>Gemfile</strong>:</p>
<pre><code class="language-plaintext">source 'https://rubygems.org'

gem 'rake'
# Add your dependencies here:

gem 'motion-meter'
</code></pre>
<p>Then in our <strong>applicationDidFinishLaunching</strong>, above the <strong>NSNotificationCenter</strong> and <strong>NSTimer</strong> code, we’ll add our new control as follows:</p>
<pre><code class="language-plaintext">@audio_level = Motion::Meter::ThresholdMeter.alloc.initWithFrame(CGRectZero)
@audio_level.add_threshold(-20, -5, NSColor.greenColor)
@audio_level.add_threshold(-5, 3, NSColor.yellowColor)
@audio_level.add_threshold(3, 10, NSColor.redColor)
@audio_level.min_value = -20
@audio_level.max_value = 10
self.set_audio_level_frame
@mainWindow.contentView.addSubview(@audio_level)
</code></pre>
<p>The meter control allows thresholds to be set, and for that we just need to define a lower and upper limit for the threshold, along with a color to use for rendering the meter if the current value is within that threshold. We also set a min and max value to prepare the control for the range of values to expect - typically our calculated average works out at around somewhere between -20 and 10 it seems from the logging, so we’ll set it up accordingly.</p>
<p>We’ll also need to add this method that is called to setup the frame too:</p>
<pre><code class="language-plaintext">def set_audio_level_frame
  @audio_level.frame = [
    [BUTTON_SIZE.first, 0],
    [@mainWindow.contentView.bounds.size.width - BUTTON_SIZE.first, BUTTON_SIZE.last]
  ]
end
</code></pre>
<p>And the reason that’s in its own method, as with the <strong>set_button_frame</strong>, is so that we can also call it from the resize handler when the window is resized. Therefore, <strong>windowDidResize</strong> becomes:</p>
<pre><code class="language-plaintext">def windowDidResize(notification)
  self.set_button_frame
  self.set_audio_level_frame
  self.update_video_preview if @is_running
end
</code></pre>
<p>Lastly, we need to be setting the value from within our <strong>checkAudioLevels</strong> method, so the control can use the latest value each time we check the levels - here we’re using our calculated average value:</p>
<pre><code class="language-plaintext">def checkAudioLevels
  return unless @is_running
  sum = 0
  @audio_output.connections.first.audioChannels.each_with_index do |channel, index|
    sum += (channel.averagePowerLevel + channel.peakHoldLevel) / 2.0
  end
  avg = sum / @audio_output.connections.first.audioChannels.count
  @audio_level.value = avg
end
</code></pre>
<p>You’ll notice we’ve also lost our logging statements - now that we’re representing those values visually through our meter control, they are no longer needed.</p>
<p>If we fire up our app, and click <strong>Start</strong>, we’ll see our video preview appear, and below it, alongside our button, a meter that reacts to the input audio volume of our recording - try clapping and see it react accordingly, jumping into the yellow or red thresholds.</p>
<p><img src="https://ejdraper.com/images/avcapture_audio_level_display.png" alt="Displaying calculated audio level"></p>
<p>[<a href="https://github.com/kickcode/AVCapture/tree/display_audio_levels">code</a>]</p>
<h3>Next steps</h3>
<p>There is obviously a whole lot more that you could do with the AVFoundation framework, we’ve really just scratched the surface of what’s possible here. Capturing still images, altering the configuration and presets to change the quality of the output, processing data to modify it on the fly, as well as doing more interesting things with the output such as streaming or uploading - there is a lot of potential. In my book, you’ll be able to read this content and more to cover capturing audio and video in more detail, as well as a whole bunch of other OS X app building topics using RubyMotion. If you’re interested in being able to build apps and utilities for OS X quickly and easily, you’ll want this book! So sign up now below to be notified when early access starts very soon (subscribers will get an exclusive discount!).</p>
<p>Other than that, feel free to tweet me <a href="http://twitter.com/ejdraper">@ejdraper</a>, or comment below with any questions or comments.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Capturing video and audio on Mac OS X with RubyMotion]]></title>
            <link>https://ejdraper.com/2015/05/06/capturing-video-and-audio-on-mac-os-x-with-rubymotion</link>
            <guid isPermaLink="false">https://ejdraper.com/2015/05/06/capturing-video-and-audio-on-mac-os-x-with-rubymotion</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>In this article we’re going to look at how you can use RubyMotion and the AVFoundation framework to build a Mac OS X app that lets you capture video and audio from attached input sources (like the built-in iSight), and how you can then output that combined footage to a movie file. You can see the code for the app <a href="https://github.com/kickcode/AVCapture">here</a>.</p>
<h3>App setup and capture overview</h3>
<p>The first thing we need to do is setup a new Mac app:</p>
<pre><code class="language-plaintext">motion create --template=osx AVCapture
</code></pre>
<p>Then we need to edit the Rakefile to add the AVFoundation for us to use:</p>
<pre><code class="language-plaintext">Motion::Project::App.setup do |app|
  # Use `rake config' to see complete project settings.
  app.name = 'AVCapture'

  app.frameworks += ['AVFoundation']
end
</code></pre>
<p>[<a href="https://github.com/kickcode/AVCapture/tree/app_setup">code</a>]</p>
<p>Now we’re ready to start capturing from input sources. Whether audio or video, the setup and API calls are roughly the same, with the process being the following steps:</p>
<ul>
<li>create and configure a capture session</li>
<li>find the device(s) you want to capture from</li>
<li>create a capture input from the device(s)</li>
<li>check to make sure the capture inputs can be added, and if so, add it to the capture session</li>
<li>create a capture output representing how you want to save or process the captured data</li>
<li>check to make sure it can be added to the session, and if so, add it</li>
<li>when you want to begin capturing, start the session, and once the session is started, begin any output specific actions (such as recording to file)</li>
<li>stop the session when you’re done capturing</li>
</ul>
<p>Now, that seems like a lot of steps, but each step is quite straightforward, which is the great thing about the API - it breaks down a complicated task into a series of very simple steps, and along the way allows a ton of configuration, customisation, and different input and output options.</p>
<p>So what are we going to be building? To keep things simple to begin with, we’ll build an app that shows a window with a button on it, and when the button is pressed, we begin recording using the first video and audio device found, and when it’s pressed again, we’ll stop recording. It’ll output the captured audio and video inputs to file. This means we don’t have to focus too much on the UI of our test app, but can focus instead on the code that makes all of the above steps happen.</p>
<h3>Setting up our capture session and device inputs</h3>
<p>So first things first, we want to setup our capture session and device inputs, and we’ll do that in <strong>applicationDidFinishLaunching</strong>.</p>
<pre><code class="language-plaintext">def applicationDidFinishLaunching(notification)
  buildMenu
  buildWindow

  @session = AVCaptureSession.alloc.init
  @session.sessionPreset = AVCaptureSessionPresetHigh
</code></pre>
<p>Creating a session is fairly familiar of course, with a standard <strong>.alloc.init</strong>, and then we set a preset that determines the quality of the capture. There are a fair few presets to choose from, and a good description of them is available better than I could summise in the docs <a href="https://developer.apple.com/library/ios/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/04_MediaCapture.html#//apple_ref/doc/uid/TP40010188-CH5-SW16">here</a>. In this case we’ll use a preset which represents the highest quality that the recording devices allows for. You can additionally go into much more detailed configuration for session quality, but we won’t get into that right now.</p>
<p>Next up, we need to locate our devices. You can easily find the available devices on the system with <strong>AVCaptureDevice.devices</strong>, and the key is to inspect them and find the ones that support the type of capture you want to do - in this case, we want a video input device, and an audio input device. If you want to see the devices available with a friendly name, you can log the following or run it in the console:</p>
<pre><code class="language-plaintext">AVCaptureDevice.devices.map(&#x26;:localizedName)
</code></pre>
<p>We’ll be taking the first of each one we find, which commonly on a Mac will be the video from the built-in iSight, and the audio from the built-in mic:</p>
<pre><code class="language-plaintext">devices = AVCaptureDevice.devices
video_device = devices.select { |device| device.hasMediaType(AVMediaTypeVideo) }.first
audio_device = devices.select { |device| device.hasMediaType(AVMediaTypeAudio) }.first
</code></pre>
<p><strong>hasMediaType</strong> is a useful way of determining the media capabilities of each device, so we can find the devices we need for both audio and video - in this case, they are separate, but if you had a USB connected webcam that did both audio and video, you’d see that it would support both media types and thus could be used for either/both.</p>
<p>Next up, we need to create a capture input from these devices, before we can add them to our capture session:</p>
<pre><code class="language-plaintext">video_input = AVCaptureDeviceInput.deviceInputWithDevice(video_device, error: nil)
audio_input = AVCaptureDeviceInput.deviceInputWithDevice(audio_device, error: nil)
</code></pre>
<p>And then lastly, we check to ensure we can add the inputs, before adding them to our session:</p>
<pre><code class="language-plaintext">if @session.canAddInput(video_input) &#x26;&#x26; @session.canAddInput(audio_input)
  @session.addInput(video_input)
  @session.addInput(audio_input)
end
</code></pre>
<p>Now our session and inputs are setup, let’s configure the output!</p>
<h3>Configuring our capture outputs</h3>
<p>We just have to decide on the type of output we want, and then instantiate an instance of that output type. In this case, we’ll be using the movie file output, which processes the data directly to a file. Again, we’re checking if we can add the output before adding it to the session:</p>
<pre><code class="language-plaintext">@output = AVCaptureMovieFileOutput.alloc.init
@session.addOutput(@output) if @session.canAddOutput(@output)
</code></pre>
<p>There are of course other types of output for performing different tasks - they are listed in full in the docs <a href="https://developer.apple.com/library/ios/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/04_MediaCapture.html#//apple_ref/doc/uid/TP40010188-CH5-SW17">here</a>, but in short alongside the movie file output, there are outputs for directly processing frame data for captured video and audio (for modifying it on the fly), as well as an output for capturing still images from a video device.</p>
<p>If you run the app now, you’ll see a blank window, and not much else happening (yet).</p>
<p><img src="https://ejdraper.com/images/avcapture_blank.png" alt="Blank window after session setup"></p>
<p>[<a href="https://github.com/kickcode/AVCapture/tree/session_and_device_inputs_outputs">code</a>]</p>
<h3>Push to start, push to stop</h3>
<p>So now everything is setup, but we need a way to start and stop the actual capture. Let’s add a button to our basic window to allow us to do just that - at the end of <strong>applicationDidFinishLaunching</strong>, add:</p>
<pre><code class="language-plaintext">@button = NSButton.alloc.initWithFrame(CGRectZero)
self.set_button_frame
@button.title = "Start"
@mainWindow.contentView.addSubview(@button)
</code></pre>
<p>Then below that, add these methods that we require, so we handle window resizing (similar to the article on positioning controls <a href="http://kickcode.com/blog/2014/12/17/how-to-setup-and-position-basic-controls-in-a-mac-os-x-app-window-with-rubymotion.html">here</a>), and to setup the button frame used initially and with the resizing:</p>
<pre><code class="language-plaintext">def windowDidResize(notification)
  self.set_button_frame
end

def set_button_frame
  size = @mainWindow.frame.size
  button_size = [150, 30]
  @button.frame = [
    [(size.width / 2.0) - (button_size[0] / 2.0), (size.height / 2.0) - (button_size[1] / 2.0)]
    , button_size
  ]
end
</code></pre>
<p>We also need to make sure the app delegate is the delegate for the window, in order for our <strong>windowDidResize</strong> event handler to be called, so add this at the bottom of <strong>buildWindow</strong>:</p>
<pre><code class="language-plaintext">@mainWindow.orderFrontRegardless
  @mainWindow.delegate = self
end
</code></pre>
<p>Then, we need to set the target/action for the button, and point it to a method to start the session capture and recording to file, so back in <strong>applicationDidFinishLaunching</strong>, add:</p>
<pre><code class="language-plaintext">@button.target = self
@button.action = 'toggle_capture:'
</code></pre>
<p>And the implementation for the button handler goes as follows:</p>
<pre><code class="language-plaintext">def toggle_capture(sender)
  @is_running ||= false
  if @is_running
    @session.stopRunning
    @button.title = "Start"
  else
    @session.startRunning
    @button.title = "Stop"
  end
  @is_running = !@is_running
end
</code></pre>
<p>Here we can see that we’re tracking whether we’re running or not, initially defaulting to false, and then based on that we’re either starting or stopping the session, and updating the button text accordingly. Finally, we’re flipping the <strong>@is_running</strong> tracking var for next time.</p>
<p>And if we fire up the app now, we’ll see we can click the button, have it toggle between <strong>Start</strong> and <strong>Stop</strong>, and you should notice that the light on your built-in iSight goes on and off as you start and stop the capture. But there is no output file, no actual saved recording. That’s because we need to start the output itself, and specify a filename, and the best way to do that is to respond to when the session has started by subscribing to a notification, and firing up our output in there.</p>
<p><img src="https://ejdraper.com/images/avcapture_start.png" alt="Start button with no session running"></p>
<p><img src="https://ejdraper.com/images/avcapture_stop.png" alt="Stop button with session running"></p>
<p>[<a href="https://github.com/kickcode/AVCapture/tree/start_stop_capture_button">code</a>]</p>
<h3>audio + video = mp4</h3>
<p>So first of all, at the end of <strong>applicationDidFinishLaunching</strong>, let’s add our notification handler code:</p>
<pre><code class="language-plaintext">NSNotificationCenter.defaultCenter.addObserver(self,
  selector: 'didStartRunning',
  name: AVCaptureSessionDidStartRunningNotification,
  object: nil)
</code></pre>
<p>We’re adding an observer for the <strong>AVCaptureSessionDidStartRunningNotification</strong> notification, and we’re asking that <strong>didStartRunning</strong> is called when that event is fired. The code for our <strong>didStartRunning</strong> method looks like this:</p>
<pre><code class="language-plaintext">def didStartRunning
  url = NSURL.alloc.initWithString("file:///Users/#{NSUserName()}/Desktop/temp#{Time.now.to_i}.mp4")
  @output.startRecordingToOutputFileURL(url, recordingDelegate: self)
end
</code></pre>
<p>Here we’re constructing a URL to represent a file to save, using <strong>NSUserName()</strong> to grab the current user to use within the path. Then we call <strong>startRecordingToOutputFileURL</strong> with the URL and the app delegate as the recording delegate, which will begin to save the output from our capture session to file.</p>
<p>Now when we fire up the app, each time we start and stop we’ll create a new file, with the output from the video of the iSight and the audio of the mic. However you might notice that if you start and stop quite quickly, no file is created. If you start and wait a few seconds, and then stop, you’ll get a file, but it’ll only be very short. This is because it takes a second or two to start writing the output to file, and as such some additional feedback might be useful in our app so we know when we’re actually recording.</p>
<p>[<a href="https://github.com/kickcode/AVCapture/tree/output_to_file">code</a>]</p>
<h3>Making it more responsive</h3>
<p>Firstly, let’s change our <strong>toggle_capture</strong> method so that it is essentially moving the app into a working state on a button click, and awaiting the actions to complete before updating the UI further. This means that clicking <strong>Start</strong> will change the button text to <strong>Starting…</strong> and clicking <strong>Stop</strong> will change it to <strong>Stopping…</strong>, as well as rendering the button unusable until it’s been updated further.</p>
<pre><code class="language-plaintext">def toggle_capture(sender)
  return if @is_working
  @is_running ||= false
  if @is_running
    @is_working = true
    @output.stopRecording
    @session.stopRunning
    @button.title = "Stopping..."
  else
    @is_working = true
    @session.startRunning
    @button.title = "Starting..."
  end
  @button.enabled = false
end
</code></pre>
<p>You’ll see we have an additional variable, <strong>@is_working</strong>, used to ensure that while we’re in the working state, we don’t action any other button presses, and we also disable the button to be sure. This is only half the story though - now we need some callbacks from the output itself to know when it starts and stops recording so that we can update the UI, the <strong>@is_working</strong> var, and re-enable the button. You may have noticed when we start recording in <strong>didStartRunning</strong>, we make this call:</p>
<pre><code class="language-plaintext">@output.startRecordingToOutputFileURL(url, recordingDelegate: self)
</code></pre>
<p>This sets the app delegate as the delegate for receiving events related to the recording, and we’re now explicitly calling <strong>stopRecording</strong> in <strong>toggle_capture</strong> too, so as such we can now implement a couple of delegate methods to handle our response to starting and stopping recording. Add the following:</p>
<pre><code class="language-plaintext">def captureOutput(output, didStartRecordingToOutputFileAtURL: url, fromConnections: connections)
  @button.title = "Stop"
  @button.enabled = true
  @is_working = false
  @is_running = true
end

def captureOutput(output, didFinishRecordingToOutputFileAtURL: url, fromConnections: connections, error: err)
  @button.title = "Start"
  @button.enabled = true
  @is_working = false
  @is_running = false
end
</code></pre>
<p>We’re re-enabling the button and marking <strong>@is_working</strong> as false in both cases, for starting and stopping, but when we’ve started we’ll update the button text to <strong>Stop</strong>, and mark <strong>@is_running</strong> as true, and when we’ve finished we’ll update the button to show <strong>Start</strong> and set <strong>@is_running</strong> to false. Fairly simple, and we now have a more complete feedback loop with more robust handling of the way that the recording starts and stops, which provides better feedback to the user.</p>
<p><img src="https://ejdraper.com/images/avcapture_starting.png" alt="Working button state while session and recording is started"></p>
<p>[<a href="https://github.com/kickcode/AVCapture/tree/responsive_capture_ui">code</a>]</p>
<h3>Tidy up</h3>
<p>The last thing we’ll do is a quick bit of tidyup to ensure that our recording and session stay in sync, even if there is an error. Right now if the user presses <strong>Stop</strong>, both the session and recording are stopped, but if the recording is stopped independently by the system for some reason (out of disk space, for example), then our session will continue going even when the session stops. Our button will update, but the webcam will stay on. We’ll just move this line from <strong>toggle_capture</strong>:</p>
<pre><code class="language-plaintext">@session.stopRunning
</code></pre>
<p>to the top of our <strong>didFinishRecordingToOutputFileAtURL</strong> method:</p>
<pre><code class="language-plaintext">def captureOutput(output, didFinishRecordingToOutputFileAtURL: url, fromConnections: connections, error: err)
  @session.stopRunning
  @button.title = "Start"
</code></pre>
<p>That’s it! Now when the start button is hit, we start the session, and when the session is started, we start the recording. When the stop button is pressed, we stop the recording, and if that happens, or if the recording is stopped for any other reason, then the session is stopped also.</p>
<p>[<a href="https://github.com/kickcode/AVCapture/tree/session_tidyup">code</a>]</p>
<h3>Next steps</h3>
<p>So we’ve seen that it’s not too tricky to use the robust <strong>AVCaptureSession</strong> API to capture video and audio, and get an output file of the total captured footage. But it’d make the app more useful if it was possible to preview what the video looked like, and the audio levels so we can be sure everything is working while recording. Tomorrow I’ll have a post looking at how we can improve this app to do just that! Make sure to check back then, or follow us on Twitter so you know when that post is up. I’ll also have an overdue update on my RubyMotion Mac OS X book later in the week too, so stay posted for that!</p>
<p><strong>UPDATE:</strong> <a href="https://ejdraper.com/2015/05/07/previewing-video-and-audio-when-capturing-on-mac-os-x-with-rubymotion">Here</a> is the next post, covering the video preview and audio level display!</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customise a Mac OS X window further with RubyMotion and MotionKit]]></title>
            <link>https://ejdraper.com/2014/12/19/customising-a-mac-os-x-window-further-with-rubymotion-and-motionkit</link>
            <guid isPermaLink="false">https://ejdraper.com/2014/12/19/customising-a-mac-os-x-window-further-with-rubymotion-and-motionkit</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>In our <a href="https://ejdraper.com/2014/12/17/how-to-setup-and-position-basic-controls-in-a-mac-os-x-app-window-with-rubymotion">last article</a> we looked at ways to build up a basic Mac OS X app window, adding controls and some interactivity. It was an introduction to how to layout and position controls to achieve the effect you want in an application window, but there are tools to make our lives easier, especially when it comes to building things that are more complex. Enter <a href="http://github.com/motion-kit/motion-kit">MotionKit</a>.</p>
<p>MotionKit provides a whole layer of abstraction for building up your user interface, and provides a neat DSL to do it. It makes building complex user interfaces much easier, and even better than that, it actually works on iOS as well as OS X, so it’s great to get to know it, as it’ll save you time!</p>
<p>First of all, let’s build up the user interface we had in the last tutorial in MotionKit. It’ll give us a good idea of how much easier things are! We’ll do this by using a separate layout class to construct our UI elements, and this will not only more cleanly separate our elements, but will also make it so that we can do more with less code.</p>
<p>We need to add our new dependency for the motion-kit gem first, so add this to Gemfile:</p>
<pre><code class="language-plaintext">gem 'motion-kit'
</code></pre>
<p>Then run the following:</p>
<pre><code class="language-plaintext">bundle install
</code></pre>
<p>Then we’ll create our new file at app/main_layout.rb that’ll describe our UI components:</p>
<pre><code class="language-plaintext">class MainLayout &#x3C; MotionKit::Layout
  SIZE = [150, 30]

  view :button, :label

  def layout
    add NSButton, :button do
      title "a test button"
      size SIZE
      autoresizing_mask :pin_to_center
      frame from_center
    end
    add NSTextField, :label do
      bezeled false
      drawsBackground false
      editable false
      selectable false
      size SIZE
      autoresizing_mask :pin_to_center
      frame from_center(up: 3)
    end
  end
end
</code></pre>
<p>This creates the same button and label (using a text field as before), and uses provided helper methods for pinning the items to the center, and autoresizing. This means our <strong>app/app_delegate.rb</strong> gets dramatically simpler, as we can remove our <strong>didResize</strong> handler, and we can replace our control initialization now with:</p>
<pre><code class="language-plaintext">@layout = MainLayout.new
@mainWindow.contentView = @layout.view

@label = @layout.get(:label)
@button = @layout.get(:button)
@button.target = self
@button.action = 'button_pressed:'
</code></pre>
<p>This creates the layout, sets the view of the window to be that of the layout which handles the UI now, and then grabs a reference to the two controls - we want a reference to the button to be able to attach once more our event handler for the click, and we have the reference to the label for updating the text when the button is pressed. That event handler stays the same as before and works without any other modification.</p>
<p>Here is how it looks now - the same as how we had it in the last tutorial:</p>
<p><img src="https://ejdraper.com/images/motionkit_basic_centered_button.png" alt="Basic window with centered button in MotionKit"></p>
<p>[<a href="https://github.com/kickcode/WindowAndControlsDemo/releases/tag/motionkit_basic_centered_button">code</a>]</p>
<p>So now we’ve replaced what we had before with something that is a bit tidier and easier to understand - let’s build on that to add slightly more interesting functionality. Let’s build a basic calculator for adding two numbers together. This will require a few more controls to be setup, and gives us chance to look at another way to organise our controls - using AutoLayout constraints.</p>
<p>So let’s start by modifying our <strong>app/main_layout.rb</strong> file, replacing our existing UI with our desired new UI:</p>
<pre><code class="language-plaintext">class MainLayout &#x3C; MotionKit::Layout
  SIZE = [150, 30]

  def layout
    add NSTextField, :num1 do
      constraints do
        right.equals(:separator, :left).minus(10)
        top.equals(:separator, :top).minus(5)
        size [50, 30]
      end
    end
    add NSTextField, :separator do
      stringValue "+"
      bezeled false
      drawsBackground false
      editable false
      selectable false
      size_to_fit
      autoresizing_mask :pin_to_center
      frame from_center
    end
    add NSTextField, :num2 do
      constraints do
        left.equals(:separator, :right).plus(10)
        top.equals(:separator, :top).minus(5)
        size [50, 30]
      end
    end

    add NSButton, :calculate do
      title "Calculate"
      size_to_fit
      constraints do
        top.equals(:separator, :bottom).plus(10)
        left.equals(:separator, :left).minus(25)
      end
    end

    add NSTextField, :result do
      bezeled false
      drawsBackground false
      editable false
      selectable false
      size_to_fit
      constraints do
        top.equals(:calculate, :bottom).plus(10)
        left.equals(:separator, :left)
      end
    end
  end
end
</code></pre>
<p>That’s a bit more code than before, but when we consider we have five controls now, it’s not too much to get our heads around. Most of it is self-explanatory and similar to the previous code - we’re either creating NSTextField controls or NSButton controls, for the <strong>:result</strong> and <strong>:separator</strong> controls we want them to act like labels so much as before, we’re setting a few different things to make them look and behave as such. For <strong>:num1</strong> and <strong>:num2</strong> we want actual text field inputs, and then we have our button, <strong>:calculate</strong>. What is new are the <strong>constraints</strong> blocks, so let’s dig in deeper there.</p>
<p><strong>constraints</strong> blocks are the hooks into AutoLayout and its constraints API, allowing us to specify UI placement based on a set of constraints. It manages all the constraints for the UI pieces alongside each other in the parent view, and sets out the UI to match them accordingly. You can reference other elements, and thus can build the elements off of one another, and in relation to each other, which makes things a whole lot easier. In this particular case, we’re setting our <strong>:separator</strong> label (the “+” sign) in the center, without any constraints, but using the frame and autoresize declarations we were using before. We’re then using AutoLayout constraints to ensure the <strong>:num1</strong> and <strong>:num2</strong> fields sit either side correctly. We then place the <strong>:calculate</strong> button relative to the <strong>:separator</strong> in the center, but below it, and again we place the <strong>:result</strong> label below that, in the center also. This gives us a whole lot of UI elements with not a lot of code, and it’s all pinned around the autoresizing central elements, which makes the whole thing scale nicely and automatically too. What’s not to like?</p>
<p>One other thing to note is that amongst the helpers provided for creating UI with MotionKit, there is a block you can wrap commands in, called <strong>deferred</strong>, which ensures that the helpers are run when all controls are initialised, and not just in the order they are called. This is especially useful when you are referencing other controls from your helper calls, however all <strong>constraints</strong> blocks are deferred by default, and so there isn’t a need to wrap our constraint code in a <strong>deferred</strong> block as well - but it could come in useful elsewhere, if you are using a lot of interdependent frame helpers.</p>
<p>The DSL itself for constraints is quite expressive, and allows you to match and specify on a great many things - for a full reference it’s best to check out the <a href="https://github.com/motion-kit/motion-kit/blob/master/READMORE.md#autolayout">MotionKit docs</a>, but as you can see in our code we’re making use of matching on the <strong>top</strong>, <strong>left</strong> and <strong>right</strong> sides of other controls, and using <strong>plus</strong> / <strong>minus</strong> calls to make relative adjustments.</p>
<p>We’re left with an expressive, neat way of describing our user interface, but now it’s back to <strong>app/app_delegate.rb</strong> so we can grab references to the controls we need, and hook up our calculator functionality! We can remove the existing UI setup code and instead use this:</p>
<pre><code class="language-plaintext">@layout = MainLayout.new
@mainWindow.contentView = @layout.view

@num1 = @layout.get(:num1)
@num2 = @layout.get(:num2)
@calculate = @layout.get(:calculate)
@calculate.target = self
@calculate.action = 'calculate_result:'
@result = @layout.get(:result)
</code></pre>
<p>This sets up the view using our separate layout, as before, as well as grabbing the control references we need. It also sets up the click event handler for the button as before, only this time pointing at the <strong>calculate_result</strong> method. So all that remains is to implement that to fulfill the calculator functionality for our UI:</p>
<pre><code class="language-plaintext">def calculate_result(sender)
  @result.stringValue = (@num1.stringValue.to_i + @num2.stringValue.to_i).to_s
end
</code></pre>
<p>And that’s it! It should look like this:</p>
<p><img src="https://ejdraper.com/images/motionkit_calculator.png" alt="MotionKit calculator UI"></p>
<p>[<a href="https://github.com/kickcode/WindowAndControlsDemo/releases/tag/motionkit_calculator">code</a>]</p>
<p>A super simple addition calculator UI implemented in a very small amount of code, all thanks to the beauty of MotionKit. In a future tutorial we’ll build up a more life-like example UI to demonstrate some other control and view classes, and some more MotionKit goodness.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to setup and position basic controls in a Mac OS X app window using RubyMotion]]></title>
            <link>https://ejdraper.com/2014/12/17/how-to-setup-and-position-basic-controls-in-a-mac-os-x-app-window-with-rubymotion</link>
            <guid isPermaLink="false">https://ejdraper.com/2014/12/17/how-to-setup-and-position-basic-controls-in-a-mac-os-x-app-window-with-rubymotion</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>We’ve focused a lot in past articles on menu bar apps, but of course it’s quite likely that if you’re building an OS X app, you’ll want to have an actual application window to expose further functionality, unless you can fit what your app does neatly into a customised status bar menu.</p>
<p>The code for this tutorial is in <a href="https://github.com/kickcode/WindowAndControlsDemo">this</a> repo, which will also contain code for future windowed Mac OS X UI tutorials. The full code for this particular app is in <a href="https://github.com/kickcode/WindowAndControlsDemo/tree/basic">this branch</a>, and throughout the article there will be code links to specific tags which allow you to jump in at a specific point, or reference it as you run through building the app yourself.</p>
<p>So let’s start with the default OS X template RubyMotion provides - it gives us the setup for a default application window, complete with a menu, which we’ll leave as-is.</p>
<pre><code class="language-plaintext">motion create --template=osx WindowAndControlsTest
cd WindowAndControlsTest
rake
</code></pre>
<p>That’ll give you the basic window seen below.</p>
<p><img src="https://ejdraper.com/images/basic_window_skeleton.png" alt="Basic window skeleton app"></p>
<p>[<a href="https://github.com/kickcode/WindowAndControlsDemo/releases/tag/skeleton">code</a>]</p>
<p>Now let’s look at adding a control - a button, in fact. In <strong>app/app_delegate.rb</strong>, at the bottom of the <strong>buildWindow</strong> method, add:</p>
<pre><code class="language-plaintext">@button = NSButton.alloc.initWithFrame([[0, 0], [150, 30]])
@button.title = "a test button"
@mainWindow.contentView.addSubview @button
</code></pre>
<p>This is quite straightforward - we’re setting up a button at position [0,0], 150px wide and 30px high, we’re setting the title on it, and we’re adding it to our window view. Running that you can see the button in the bottom-left - on OS X, the root anchor for X and Y positioning (0,0) is bottom left, not top left as it is on iOS.</p>
<p><img src="https://ejdraper.com/images/basic_window_button.png" alt="Basic button"></p>
<p>[<a href="https://github.com/kickcode/WindowAndControlsDemo/releases/tag/basic_button">code</a>]</p>
<p>Let’s reposition our button so it’s in the middle of the screen. If you’re coming from iOS development, you may be used to fixed screen dimensions, but as you may also be finding out with each new iPhone announced, it’s much better to avoid hard-coding heights and widths of windows into your app, and instead query the information needed to position things accordingly. Amend our button initialisation to look like the following:</p>
<pre><code class="language-plaintext">size = @mainWindow.frame.size
@button = NSButton.alloc.initWithFrame([[size.width / 2.0, size.height / 2.0], [150, 30]])
</code></pre>
<p>We’re taking our window size, and positioning our button based on half-width and half-height. When we run that, it’s definitely getting warmer, but it’s not quite right. In fact, it’s fairly obvious that the bottom left edge of the button is in the center of the window, but what we really want is the center of the button to be in the center of the window. For that, we need to take half of the button height and half of the button width away from our button position, so that the bottom left of the button accounts for wanting the center in the center of the window. Tweaking our code further gives us this:</p>
<pre><code class="language-plaintext">size = @mainWindow.frame.size
button_size = [150, 30]
@button = NSButton.alloc.initWithFrame([
  [(size.width / 2.0) - (button_size[0] / 2.0), (size.height / 2.0) - (button_size[1] / 2.0)],
  button_size])
</code></pre>
<p>Now when we run things, we can see our button is right in the center of the window.</p>
<p><img src="https://ejdraper.com/images/basic_window_centered_button.png" alt="Basic centered button"></p>
<p>[<a href="https://github.com/kickcode/WindowAndControlsDemo/releases/tag/basic_centered_button">code</a>]</p>
<p>However, try resizing the window by grabbing the grab handle in the bottom right, and you’ll see that the button itself is basically still anchored relative to the bottom left, and as the window expands or contracts, it is no longer in the center of the smaller or larger window. This is because we’re just setting this all up once on app launch - let’s try making it so it’s responsive to window changes, to keep our button in the center on resize.</p>
<p>We need to start by handling changes to the window size, so our first change is to set the app delegate as the delegate also for the main window, so we can implement a listener for the resize method we need. First of all, find our initialisation for <strong>@mainWindow</strong>, and add the delegate line below what’s already there:</p>
<pre><code class="language-plaintext">@mainWindow.delegate = self
</code></pre>
<p>Now, we can add a method that’ll update the button position based on the window size, basically the same as we were doing on initialization but abstracted out to its own method, and we’ll also add a method to handle the resize event and call our new button positioning method:</p>
<pre><code class="language-plaintext">def windowDidResize(notification)
  self.set_button_frame
end

def set_button_frame
  size = @mainWindow.frame.size
  button_size = [150, 30]
  @button.frame = [
    [(size.width / 2.0) - (button_size[0] / 2.0), (size.height / 2.0) - (button_size[1] / 2.0)],
    button_size]
end
</code></pre>
<p>Of course, we can remove the duplicate button frame code, as we no longer need to set it specifically in the setup, we can just call <strong>set_button_frame</strong> there too!</p>
<pre><code class="language-plaintext">@button = NSButton.alloc.initWithFrame(CGRectZero)
self.set_button_frame
@button.title = "a test button"
</code></pre>
<p>Now if you run the app, then using the grab handle resize the window, you’ll see the button is stuck right in the center there. Neat!</p>
<p><img src="https://ejdraper.com/images/basic_window_centered_button_on_resize.png" alt="Basic centered button on resize"></p>
<p>[<a href="https://github.com/kickcode/WindowAndControlsDemo/releases/tag/basic_centered_button_on_resize">code</a>]</p>
<p>So let’s do one more thing now on our basic window tutorial, and handle some interactivity - it’d be good if our button actually did something! Let’s track how many times it is clicked, and show that beneath the button.</p>
<p>First of all, let’s add a new control, a label, above our button creation in <strong>buildWindow</strong>. This gives us chance to explore the fact that there actually is no label control in Cocoa - so instead we’re going to use a text field:</p>
<pre><code class="language-plaintext">@label = NSTextField.alloc.initWithFrame(CGRectZero)
@label.bezeled = false
@label.drawsBackground = false
@label.editable = false
@label.selectable = false
@mainWindow.contentView.addSubview @label
</code></pre>
<p>We’re removing the bezeling, not drawing the background, and making sure it’s not editable or selectable - and voila, we have a label. Next up, we want to make sure the label frame is set to just below the button frame anytime the button frame changes - so we’ll add this to the bottom of <strong>set_button_frame</strong>:</p>
<pre><code class="language-plaintext">@label.frame = [
  [(size.width / 2.0) - (button_size[0] / 2.0), (size.height / 2.0) - (button_size[1] / 2.0) - (button_size[1])],
  button_size]
</code></pre>
<p>This is the same as the main button, but set one button height lower, so it’s beneath.</p>
<p>Next, we need to setup the button click handler:</p>
<pre><code class="language-plaintext">@button.target = self
@button.action = 'button_pressed:'
</code></pre>
<p>By setting the button target to self, and setting the action, we’re pointing to the method that will be triggered by a click - we now need to implement that method:</p>
<pre><code class="language-plaintext">def button_pressed(sender)
  @taps ||= 0
  @taps += 1

  @label.stringValue = "#{@taps} presses"
end
</code></pre>
<p>Here we’re initializing the taps variable if it doesn’t already exist (i.e. on first click), then incrementing it, and setting the label text based on the count. Now our functionality will work like this:</p>
<p><img src="https://ejdraper.com/images/basic_window_centered_button_on_click.png" alt="Basic centered button on click"></p>
<p>[<a href="https://github.com/kickcode/WindowAndControlsDemo/releases/tag/basic_centered_button_on_click">code</a>]</p>
<p>So, we’ve covered initializing and laying out basic controls, and establishing some very basic interactivity in our window - it’s good to know how to layout simple user interface by hand, but in the next article we’ll look at using motion-kit, which is an awesome lib for constructing user interfaces more quickly, and works really nicely as you start to build your app up.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WordTarget 1.2, coming soon]]></title>
            <link>https://ejdraper.com/2014/11/30/wordtarget-1-2-coming-soon</link>
            <guid isPermaLink="false">https://ejdraper.com/2014/11/30/wordtarget-1-2-coming-soon</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>The next update for WordTarget has now been submitted, and it’s so big, we’ve skipped 1.1 entirely and gone straight to 1.2! So what’s on the way?</p>
<h3>Improved user interface</h3>
<p>That’s right, the boring old menu is now gone, replaced with a customised drop down panel, with everything you need at your fingertips! There are easy-to-use controls for starting and stopping the tracker, resetting, changing whether it counts up or down, and further options for exiting the app and seeing the about panel. Underneath is the history of your words, showing you a readable list of your word tracking history.</p>
<p><img src="https://ejdraper.com/images/wordtarget/1.2/list.png" alt="New menu user interface"></p>
<h3>Easy at-a-glance view of whether you hit your target for a day</h3>
<p>Each entry in the list has a tick or a cross, denoting whether you hit your target for that day, so you can quickly get a gauge on your overall progress, and whether in general you’re hitting your targets or not.</p>
<h3>Targets for each day are stored so changing your target doesn’t change whether you hit your target for a day in the past</h3>
<p>The target in use for each day is now persisted, so changing your target in the future doesn’t re-evaluate past days and change successful days into failures (for example, when you’ve decided to raise your daily word target).</p>
<h3>Click to view the breakdown of your words per-application</h3>
<p>One of the most requested features was being able to see a per-application breakdown in the word count for each day, to see where all of those words were going. Now you can see just that in 1.2!</p>
<p><img src="https://ejdraper.com/images/wordtarget/1.2/app_breakdown.png" alt="Per-application breakdown of words for a day"></p>
<h3>Local notification popup when you hit your target</h3>
<p>Getting a little popup letting you know you hit your target is a good motivation that you’re on track and doing well - unless of course you’re only just getting started, in which case it might be a reminder to up that target a little bit for tomorrow!</p>
<h3>When?</h3>
<p>With any luck, this new version will be in the Mac App Store within 7-10 days! In the meantime, the app is on sale at the minute for Black Friday - through the end of Monday, you can pick it up for <a href="https://itunes.apple.com/app/wordtarget/id751480906">$3.99/£2.49</a>! With each new version of the app that adds great new features, the price will increase - but once purchased, regardless of the price paid, you’ll get all the future updates, so it’s worthwhile picking up soon if you want to lock in this great functionality now, with new stuff coming down the pipe later!</p>
<h3>On the slate for 1.3</h3>
<ul>
<li>Hot keys for easily starting/stopping tracking</li>
<li>Blacklist for excluding tracking for certain applications, even if the app is running and tracking</li>
</ul>
<h3>Other ideas for future versions (1.3 and beyond)</h3>
<ul>
<li>Editing a past days target, for when you need to change a historical target (that will affect whether the day is marked as successful or not)</li>
<li>Being able to export your data</li>
<li>iCloud or other support to allow synced usage across machines</li>
<li>Tracking streaks for consecutive days hitting your target</li>
<li>Achievements for certain streak levels, to help keep you motivated</li>
<li>More notifications to provide ongoing progress updates as you work towards your target each day, not just when it’s hit</li>
</ul>
<p>Follow <a href="http://twitter.com/WordTargetApp">@WordTargetApp</a> or <a href="http://twitter.com/kickcode">@kickcode</a> on Twitter to keep up to date with the latest updates on the app! Any questions, let me know.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Announcing WordTarget - a writing productivity tool]]></title>
            <link>https://ejdraper.com/2014/11/07/announcing-wordtarget-a-writing-productivity-tool</link>
            <guid isPermaLink="false">https://ejdraper.com/2014/11/07/announcing-wordtarget-a-writing-productivity-tool</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>Wow, where has the year gone? It’s been a very busy Summer and now Autumn too here at <a href="https://kickcode.com/">KickCode</a> HQ, with Winter just peeking around the corner. I have a bit of catching up to do here on this blog, and I’ve got some fresh new content and some other interesting news and announcements coming over the next few weeks (including a long overdue update about the book!), but for today I want to talk about a new Mac OS X app I’ve built.</p>
<p><a href="https://kickcode.com/wordtarget">WordTarget</a> is a productivity tool (written in RubyMotion) that sits in your menubar, and helps you to hit a writing goal. If that sounds straightforward, it’s because it is! But the real key to WordTarget helping you is that it will track your progress across any applications, and you can start and stop it counting right from the menu bar. So perhaps you want to write 500 words a day, but depending upon the day (or time of day!) you might be writing a blog post, working on a book, writing some documentation, getting through your emails, or writing a letter. No matter which apps you use, WordTarget will be counting so you can keep tally, and know when you’ve hit your target. Or if you prefer, you can switch it to count down to zero from your target instead.</p>
<p>It allows you to view the data for previous days so you can track your progress over time too, so it’s not just for the here and now, but can really help you with a longer term goal, if you’re aiming for a certain word count for a larger project like a book, a thesis or essay etc.</p>
<p>It’s been available on the <a href="https://itunes.apple.com/app/wordtarget/id751480906">Mac App Store</a> for a little while now, in a sort of stealth/soft launch mode, and in that time I’ve had a few people checking out and using the app, who have let me know it’s useful for them, and provided some great feedback. I’ve been working on an updated version that is not too far away, and with those additional features will come a small price increase, so it seems like the perfect time now to let people in on the fun, and if you pick it up now you’ll then be entitled to future updates of the app for free through the App Store, even if the price changes later!</p>
<p>I’ll be going into details on the new features in the next version in a future post, but for now I’m announcing a competition where someone can win a copy of WordTarget every single day from now until the end of November, to celebrate <a href="http://nanowrimo.org/">National Novel Writing Month</a> (#NaNoWriMo). All you have to do to enter is to follow <a href="http://twitter.com/WordTargetApp">@WordTargetApp</a>, and then tweet about the app, making sure to include @WordTargetApp, and a link to the competition in the tweet - that’s it! You can even use the buttons below to make it easier.</p>
<p><a href="https://twitter.com/WordTargetApp">Follow @WordTargetApp</a></p>
<p>If you can’t wait to see if you’re a winner, you can of course buy the app on the <a href="https://itunes.apple.com/app/wordtarget/id751480906">Mac App Store right now</a> - it’s just £4.99/$6.99, which is a small price to help you keep your writing squarely on track each day! More information about the app is available <a href="https://kickcode.com/wordtarget">here</a>, with setup screencasts for Mac OS X 10.8, 10.9 and 10.10 available <a href="https://kickcode.com/wordtarget/setup">here</a>.</p>
<p>If you have any questions about the app, the competition, or anything else, tweet <a href="http://twitter.com/ejdraper">@ejdraper</a>, or comment below!</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get started building Mac OS X apps with RubyMotion fast]]></title>
            <link>https://ejdraper.com/2014/05/07/how-to-get-started-building-mac-os-x-apps-with-rubymotion-fast</link>
            <guid isPermaLink="false">https://ejdraper.com/2014/05/07/how-to-get-started-building-mac-os-x-apps-with-rubymotion-fast</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>I was fortunate enough to be asked to speak at <a href="http://surreyrubyists.tumblr.com/">SRUG</a>, and after having to unfortunately postpone last month due to illness, I gave my talk at last nights meeting.</p>
<h3>Speaking</h3>
<p>It was the first time I’d spoken and given a talk at such an event, but I really enjoyed it. SRUG has a core group of very knowledgeable Rubyists, so it was fun to talk all about RubyMotion, as so many were very keen on learning all about it. I had some great questions at the end too, and some really good discussions about RubyMotion, and some other great dev topics too. It was a really fun night, and I’m looking forward to the next meeting already (especially as I can relax a bit more as I won’t be presenting!).</p>
<h3>Slides</h3>
<p>I’ve put the slides up online, and you can see them below:</p>
  
For the last section, the [NoteMeNot](https://github.com/kickcode/NoteMeNot) demo app, I was stepping through various pre-built code commits to demonstrate adding the additional features for the app (wasn't quite foolish/brave enough to attempt live coding in my first talk!), so you can follow along too by clicking the link on each slide which will take you to the GitHub commit pertaining to that change. Over the course of a number of slides we go from a simple app skeleton, to a functioning note taking app with local file persistence.
<p>You can check out the source code for that application on GitHub <a href="https://github.com/kickcode/NoteMeNot">here</a>.</p>
<p>I also mention a couple of apps that aren’t yet available in the presentation - WordTarget will be a paid app coming very soon, and Wonderment will be an open-source app once I tidy up a bit of the code and fix one or two remaining bugs.</p>
<h3>Book</h3>
<p>Lastly, the book is absolutely still coming, as I mention in the talk - it just turns out writing a book is a lot harder than it looks! I don’t want to rush things and put something out I’m not totally happy with, but I’m now planning on having the first 1/3rd of so of the book available for people who want to purchase early access this month, and I’m planning on finishing it entirely by July/August time (if not before). I know a few of you are really looking forward to it, so apologies for the delay, but I’m hopeful that it’ll be worth the wait!</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement global hotkeys in your Mac OS X app using RubyMotion]]></title>
            <link>https://ejdraper.com/2014/03/23/global-hotkeys-for-mac-os-x-apps-in-rubymotion</link>
            <guid isPermaLink="false">https://ejdraper.com/2014/03/23/global-hotkeys-for-mac-os-x-apps-in-rubymotion</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>Many apps can make use of global hotkeys, often to perform a background action (such as taking a screenshot or starting and stopping something), or to hide and show the window of an app. To implement them in your own app, the easiest way is to use the fairly old Carbon APIs for registering and responding to hotkeys being pressed - the good news is that this is quite straightforward, especially if you use a wrapper library.</p>
<h3>DDHotKey</h3>
<p>There is a very useful, easy to use project called DDHotKey that provides Cocoa classes that wraps the Carbon API calls to register system-wide hotkey event handlers. It’s not (at the time of writing) on <a href="http://cocoapods.org/">Cocoapods</a>, however we can still use it in our project fairly easily, with a simple modification. Grab the code from <a href="https://github.com/davedelong/DDHotKey">here</a>, and put it in vendor/DDHotKey. You’ll need to remove the main.m file in the root of the folder, as RubyMotion will get confused with a vendored lib that contains an executable artifact. Alternatively, I’ve forked the lib and made the change, so you can grab the already working code from <a href="https://github.com/ejdraper/DDHotKey">here</a>. Once you have added the lib to the vendor folder, you can easily configure it to build with your app in the Rakefile:</p>
<pre><code class="language-plaintext">app.frameworks += ["Carbon"]
app.vendor_project 'vendor/DDHotKey', :static, :cflags => "-fobjc-arc"
</code></pre>
<p>We’re ensuring we include the Carbon.framework in the build, we’re building DDHotKey as a static lib, and we’re also explicitly enabling ARC when compiling the lib.</p>
<h3>Listening in</h3>
<p>Then, setting up a hotkey is quite straightforward - first of all we grab a reference to the hotkey center object exposed by DDHotKey:</p>
<pre><code class="language-plaintext">center = DDHotKeyCenter.sharedHotKeyCenter
</code></pre>
<p>Then we just need to pick a key, pick our modifiers, and setup the event handler to point to a method of our choosing:</p>
<pre><code class="language-plaintext">center.registerHotKeyWithKeyCode(KVK_ANSI_M, modifierFlags: NSCommandKeyMask | NSAlternateKeyMask,
  target: self, action: 'handleHotkey:', object: nil)
</code></pre>
<h3>A note on keys and modifiers</h3>
<p>In the case above, <strong>KVK_ANSI_M</strong> is a constant provided by the Carbon APIs that refers to the keycode representing the M key. You can replace this with the constant for whichever key you’d like to trigger on. Likewise, in addition to <strong>NSCommandKeyMask</strong> and <strong>NSAlternateKeyMask</strong>, there is also <strong>NSCommandKeyMask</strong>, <strong>NSShiftKeyMask</strong>, and <strong>NSFunctionKeyMask</strong> which you can factor into your key combinations for hotkeys.</p>
<h3>Respond accordingly</h3>
<p>And finally we just have to define our event handler to do something:</p>
<pre><code class="language-plaintext">def handleHotkey(event)
  puts "hotkey pressed!"
end
</code></pre>
<p>And that’s all there is to it! You can define multiple hotkey handlers to do different things in your app, so you’re not just restricted to one.</p>
<h3>Example app</h3>
<p><a href="https://github.com/kickcode/HotkeyDemo">Here</a> is a sample app that is the default RubyMotion OS X app template, with the default window hidden by default and the app running in the background, and with Cmd+Alt+H setup to hide and show the window. Overall, global hotkeys are great for putting your app at your users fingertips at any time, and it doesn’t take a very long time to implement it!</p>
<h3>Further reading</h3>
<p>Ideally you want to allow your users to choose the key combo for certain actions, so they can change the defaults if they have conflicts between apps, or if they just prefer different combinations - and DDHotKey provides a customised NSTextField control that allows you to capture and store a combination for use as a hotkey. I’ll cover how to roll that into a settings screen for your app, persisting the results in app configuration, in my forthcoming book, Building Mac OS X apps with RubyMotion. Be sure to sign up below to be notified when it’s ready for an exclusive discount!</p>
<p>If there are any questions on this article, please let me know in the comments below, or on <a href="http://twitter.com/ejdraper">Twitter</a>!</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RubyMotion on OS X - the sky is the limit (especially for Rails developers!)]]></title>
            <link>https://ejdraper.com/2014/03/06/rubymotion-on-os-x-the-sky-is-the-limit</link>
            <guid isPermaLink="false">https://ejdraper.com/2014/03/06/rubymotion-on-os-x-the-sky-is-the-limit</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<h3>Announcements</h3>
<p>I know things have been a little quiet around here for the last month or two - a combination of client work, writing the book, and most recently welcoming our third child into the world have kept me busy! Going to make an effort to return to more regular articles here on the blog again though now, and I have some great content lined up for the next few weeks. The book is also progressing nicely, although to make sure it’s as good as I want it to be, I’ve pushed back the pre-order and early access until April, and I’m aiming for June for the final version. I want to make sure that even with the early access, you’ll be getting something immediately polished, useful and valuable right away. One other announcement - if you’re local to Guildford, Surrey in the UK, and want to come along and see me talk about using RubyMotion to build Mac OS X apps, then I’ll be speaking at SRUG on April 8th - you can register for free <a href="https://www.eventbrite.co.uk/e/surrey-rubyists-april-2014-registration-10851153091">here</a>. Now on to todays post…</p>
<h3>Future of building OS X apps with RubyMotion</h3>
<p>I received a great question via email recently from <a href="http://ryanjafari.me/">Ryan Jafari</a>, who asked me where the growing trend and popularity in OS X development with RubyMotion might lead, as well as whether OS X might catch up with iOS in terms of resources for RubyMotion development. In writing an email back, I thought it was an interesting topic in general and so thought I’d put my response up here on the blog.</p>
<p>I definitely think that over time there will be more resources for OS X development with RubyMotion, and less of it will be concentrated solely on iOS development. I think it’s mainly a case of RubyMotion having been around since mid 2012 for iOS, but only supporting OS X since the middle of last year. I think over time there may even be some cross-over with libraries that support both - <a href="http://joybox.io/">Joybox</a> for example already does this. Likewise there are others who are starting to shift to providing resources for OS X development with RubyMotion as well as iOS.</p>
<p>Of course perhaps the overall interest in developing apps for iOS is greater than for OS X right now - iPhones and iPads are more ubiquitous than Macs still - however with the Mac App Store now there is a better market for reaching that audience on the Mac desktop. While it perhaps still doesn’t have the appeal of the iOS App Store gold-rush of the last few years, it’s a good, interesting (and not exactly small!) niche to be in I think. In many respects it may even be a more easily surmountable task to stand out with a decent OS X app on the Mac App Store than it is on the iOS App Store, as things are much more densely populated on iOS.</p>
<p>Also, OS X desktop development with Objective-C is more entrenched and has been around for a lot longer than iOS development was by the time RubyMotion initially rolled around, and so perhaps iOS developers were more open to switching to RubyMotion than their desktop counterparts. However I think one of the biggest draws of RubyMotion is actually in bringing over Ruby developers who have mainly worked on the web (as I myself did) who want to start working on mobile apps, and now, desktop apps. I still work on the web a lot, but enjoy application development too - and the unique angle for Ruby web developers is that we can look to build client apps for web apps on desktop and mobile now in Ruby (Ruby on Rails on the web for example, RubyMotion for the clients). I think that’s quite an attractive proposition for a lot of Ruby developers! So if you’re a Rails developer, or have done a lot of Ruby previously with other frameworks, then there hasn’t been a better time to be able to look into building mobile and desktop apps using RubyMotion!</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[motion-popup: a RubyMotion gem for popup panels in your status bar app]]></title>
            <link>https://ejdraper.com/2014/01/04/motion-popup-a-rubymotion-gem-for-popup-status-bar-app-windows</link>
            <guid isPermaLink="false">https://ejdraper.com/2014/01/04/motion-popup-a-rubymotion-gem-for-popup-status-bar-app-windows</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>Happy New Year to you all! Hope you all had a happy holidays and wonderful New Years.</p>
<p>In the <a href="https://ejdraper.com/2013/12/14/custom-ui-popup-panel-for-mac-os-x-status-bar-app-with-rubymotion">last tutorial</a> we setup a custom user interface using a popup window panel underneath our status bar menu item. I’ve now moved the core re-usable code to make that happen into its own little <a href="http://rubygems.org/gems/motion-popup">gem</a> to make it easier for you to use in your own apps. The panel and the background custom drawing code is part of the gem, allowing you to easily instantiate and show a window underneath your own status bar item, and also allowing you to configure some of the parameters used for drawing the panel to customise it.</p>
<p>You can check out the code for it <a href="https://github.com/kickcode/motion-popup">here</a>, and read up on usage and customisation <a href="https://github.com/kickcode/motion-popup#usage">here</a>.</p>
<p>I’d also like to thank everyone that has subscribed to be notified about my upcoming RubyMotion Mac OS X apps book, Building Mac OS X apps with RubyMotion. The support and interest has been overwhelming and has really reinforced my motivation to make the book a really useful resource for developers who want to build Mac OS X apps with RubyMotion.</p>
<p>If you’ve not yet signed up to know when the pre-order is available, you can do so here or at the bottom of this post - and if you’re on the fence about whether it’d be useful, the recent tutorials I’ve written on using RubyMotion to create Mac OS X apps will give you a flavour of what the content will be like. Don’t forget that if you subscribe now, you’ll get an exclusive discount on pre-ordering the book too when the time comes!</p>
<p>Here are the Mac OS X RubyMotion tutorials from late last year in order - there is more to come over the next few months!</p>
<ul>
<li><a href="https://ejdraper.com/2013/10/18/rubymotion-status-bar-apps-for-osx">How to quickly get started creating status bar apps for Mac OS X using RubyMotion</a></li>
<li><a href="https://ejdraper.com/2013/11/07/rubymotion-background-process-in-status-bar-app">How to build a RubyMotion status bar app that updates in the background</a></li>
<li><a href="https://ejdraper.com/2013/11/22/talking-to-an-api-from-your-rubymotion-app">How to integrate your RubyMotion OS X app with a JSON based web API</a></li>
<li><a href="https://ejdraper.com/2013/11/27/user-notifications-in-your-os-x-app">Displaying user notifications in your RubyMotion OS X app</a></li>
<li><a href="https://ejdraper.com/2013/12/14/custom-ui-popup-panel-for-mac-os-x-status-bar-app-with-rubymotion">Building a custom user interface for your Mac OS X status bar app in RubyMotion</a></li>
</ul>
<p>If you have any questions about the new gem, the recent tutorials, or the forthcoming book, please get in touch in the comments below or <a href="http://twitter.com/ejdraper">@ejdraper</a> on Twitter. Look out for the next tutorial article soon, and I hope 2014 is off to a great start for everyone!</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a custom user interface for your Mac OS X status bar app in RubyMotion]]></title>
            <link>https://ejdraper.com/2013/12/14/custom-ui-popup-panel-for-mac-os-x-status-bar-app-with-rubymotion</link>
            <guid isPermaLink="false">https://ejdraper.com/2013/12/14/custom-ui-popup-panel-for-mac-os-x-status-bar-app-with-rubymotion</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>Status bar apps are very useful, but what we’ve <a href="https://ejdraper.com/2013/10/18/rubymotion-status-bar-apps-for-osx">gone</a> <a href="https://ejdraper.com/2013/11/07/rubymotion-background-process-in-status-bar-app">through</a> <a href="https://ejdraper.com/2013/11/22/talking-to-an-api-from-your-rubymotion-app">so</a> <a href="https://ejdraper.com/2013/11/27/user-notifications-in-your-os-x-app">far</a> in our series on building Mac OS X status bar apps with <a href="http://www.rubymotion.com/">RubyMotion</a> really only covers the basics, and our apps can often be much improved by implementing a more custom user interface than just a dropdown menu when you click on the item in the status bar.</p>
<p>The reasons you’d want to implement your own user interface are fairly varied, but generally speaking it gives you the ability to more easily show specific data, and handle interactions within the app in a way that better relates to what your app does.</p>
<p>In this article we’re going to take the <a href="https://github.com/kickcode/CommitTrackerMenu">app</a> we’ve built up in the <a href="https://ejdraper.com/2013/11/22/talking-to-an-api-from-your-rubymotion-app">previous</a> <a href="https://ejdraper.com/2013/11/27/user-notifications-in-your-os-x-app">couple</a> of articles, and go from a fairly staid, boring menu to list the commits, to a far more vibrant and interesting custom panel that lists the commits in a much more visually pleasing manner, and includes the user avatar image. As we’re building upon the existing codebase, and there is a fair bit of new code involved as well as changes to the existing code, we won’t be running through every single line - instead I’ll be focusing on the key implementation details, and all of the code is available as always on <a href="https://github.com/kickcode/CommitTrackerMenu">GitHub</a>.</p>
<h3>Custom panel</h3>
<p>First things first, we need to setup a window that we can show when the status item is clicked. Instead of inheriting from <strong>NSWindow</strong>, we’ll inherit from <strong>NSPanel</strong>, which is a special subclass of <strong>NSWindow</strong> that auto hides when it loses focus, and is generally perfect for a window that belongs to a background status bar app such as in this case.</p>
<p>The full definition of our <strong>PopupPanel</strong> custom window class is <a href="https://github.com/kickcode/CommitTrackerMenu/blob/94bd1e46554910b1130ea2237c6b0fe7419bb76a/app/popup_panel.rb">here</a>. Essentially though, we’re just setting up the window in our custom init method:</p>
<pre><code class="language-plaintext">self.initWithContentRect([[0, 0], [POPUP_WIDTH, POPUP_HEIGHT]],
  styleMask: NSBorderlessWindowMask,
  backing: NSBackingStoreBuffered,
  defer: false)
self.title = NSBundle.mainBundle.infoDictionary['CFBundleName']
self.delegate = self
self.setBackgroundColor(NSColor.clearColor)
self.setOpaque(false)
</code></pre>
<p>The origin for the window isn’t relevant (hence 0,0) as we’ll be moving it to show under the status item anyway. We’re using a borderless window, and then we’re setting it to be transparent so it’s invisible, allowing us to set a content view that’ll do our custom pane shape drawing.</p>
<pre><code class="language-plaintext">@background = PopupBackground.alloc.initWithFrame(self.frame)
self.setContentView(@background)
</code></pre>
<p>This is where we initialise that very custom popup background class - we’ll look at how that works shortly.</p>
<p>The only other really interesting code here is the <strong>showHide</strong> method:</p>
<pre><code class="language-plaintext">if self.isVisible
  self.orderOut(false)
else
  event_frame = NSApp.currentEvent.window.frame
  window_frame = self.frame
  window_top_left_position = CGPointMake(
    event_frame.origin.x + (event_frame.size.width / 2) - (window_frame.size.width / 2),
    event_frame.origin.y)

  self.setFrameTopLeftPoint(window_top_left_position)
  @background.setArrowX(window_frame.size.width / 2)

  NSApp.activateIgnoringOtherApps(true)
  self.makeKeyAndOrderFront(self)
end
</code></pre>
<p>This is what gets called when the status menu button is pressed. We want it to act as a toggle, so we are using <strong>isVisible</strong> to determine the current state. If we are showing the window (i.e. it’s not already visible), there is a bit more work to do. The important bit is that on the X axis we use the origin from the frame of the cause of the event, in this case the status menu item, and add half its own width to it to find the center of that menu item; we then remove half the width of our custom window panel to find the origin point on the X axis for our panel to ensure it’ll appear centered underneath the status item. Then we set the arrow for the custom pane that points from our panel up to the status item - we’ll see how that functions in a minute too.</p>
<p>The rest of the class just ensures the panel functions as a key window, so we can receive notification when it loses focus, and correctly hide it so that pressing the button again shows it as expected rather than leaving it in a weird state.</p>
<p>The other piece of the puzzle is our custom background view that we’re using as the content view for our custom window, to render the panel background by doing some custom drawing. You can see that in full <a href="https://github.com/kickcode/CommitTrackerMenu/blob/d87d6c64f9ff6d813f2fb66c74f0c46483c43a0d/app/popup_background.rb">here</a>. It’s based on the excellent Objective-C code written for <a href="http://blog.shpakovski.com/2011/07/cocoa-popup-window-in-status-bar.html">this</a> blog post, and basically uses a Bezier path to draw a panel with rounded edges, and an arrow on the top side in the middle that’ll appear to be pointing up at the status item. I won’t run through all of the code here, as it’s really just stepping through the various points (top of arrow, right of arrow, top right corner, bottom right corner, bottom left corner, top left corner, left of arrow) to draw the shape, and then to both fill the shape, as well as to draw an outline stroke.</p>
<p>The other bit of noteworthy code in this class is how we update it so that the arrow is set in the right spot and to redraw:</p>
<pre><code class="language-plaintext">def setArrowX(value)
  @arrow_x = value
  self.setNeedsDisplay(true)
end
</code></pre>
<p>This updates the X value used in the drawing method, and <strong>setNeedsDisplay</strong> ensures that our draw method is hit again to re-draw. <strong>setArrowX</strong> is what we called from our <strong>PopupPanel</strong>, and so the rendering cycle for the custom window then is complete.</p>
<h3>Right place, right time</h3>
<p>We’ve actually already done the work in our <strong>PopupPanel</strong> class <strong>showHide</strong> method to calculate the right place to show the window, and to set the arrow on the custom pane - all that remains is to alter our <strong>AppDelegate</strong> and status menu setup to trigger the panel instead of a menu. We need to create the window within the <strong>AppDelegate</strong>:</p>
<pre><code class="language-plaintext">@window = PopupPanel.alloc.initPopup
</code></pre>
<p>And then we’ll remove this line that set the status menu as the menu to use for the status item:</p>
<pre><code class="language-plaintext">@status_item.setMenu(@status_menu)
</code></pre>
<p>We’ll then add these two lines to trigger a call to a custom event handler instead:</p>
<pre><code class="language-plaintext">@status_item.setTarget(self)
@status_item.setAction('showHide:')
</code></pre>
<p>That event handler looks like this:</p>
<pre><code class="language-plaintext">def showHide(sender)
  @unseen = 0
  self.showUnseenCommits
  @window.showHide(sender)
end
</code></pre>
<p>Now, we could have set the target to the <strong>@window</strong> itself, and called our <strong>showHide</strong> method directly there rather than through a delegate event handler on our <strong>AppDelegate</strong>. However, as we see above, in addition to simply toggling the window, we also have some work to do that pertains to things handled within the <strong>AppDelegate</strong> - we want to clear the unseen commits, so that they are “marked as read”, in the same way that we did before when the menu was shown. Hence the abstraction within the <strong>AppDelegate</strong> to perform the additional functionality.</p>
<h3>Collecting commits</h3>
<p>Right now if you fire the app up, you should see a custom panel that gets shown right beneath our status bar item when we click on the status menu entry. However, there isn’t any content in here just yet. Our background call to hit the GitHub API and pull out the right data is still working - we just need to take the data we have there, and use the very versatile <strong>NSCollectionView</strong> to render it nicely into our custom pane. The file that contains the majority of our code for this is <a href="https://github.com/kickcode/CommitTrackerMenu/blob/65b85b40cf53d90988bb5d6c5413a510fb2d44c6/app/commits.rb">here</a>.</p>
<p>There are a few moving pieces to contend with. First of all, we’ll define a Struct that’ll contain the data we want to take from our call to GitHub, so we can store it in a neat way to use within the collection view:</p>
<pre><code class="language-plaintext">Commit = Struct.new(:name, :repo, :message, :avatar, :url)
</code></pre>
<p>An <strong>NSCollectionView</strong> basically works off an array, and provided with a prototype object, will know how to generate the custom view for each object it finds in the array. So we define our custom view, <strong>CommitView</strong>, with some fairly easy to follow code that simply builds the three controls we’re using - an <strong>NSBox</strong> to encapsulate the item with a neat visual boundary (and show the actor and repo for a commit as a heading), an <strong>NSImageView</strong> to show the relevant user avatar, and an <strong>NSTextField</strong> configured to function as a label to show the commit message. We then provide a method that takes in our object (an instance of our <strong>Commit</strong> struct), and will use the fields to populate these controls. The last code of interest in our custom commit view is that we’re handling the click on it to open the commit page on GitHub directly from the view:</p>
<pre><code class="language-plaintext">def mouseDown(event)
  NSWorkspace.sharedWorkspace.openURL(NSURL.URLWithString(@object.url))
end
</code></pre>
<p>The nice thing about this is that we no longer have to do a lookup to correlate the item clicked with a list of URLs - we’re handling this event on the view that is tied to a specific object, an object we can easily re-access from the event handler to provide the URL to open.</p>
<p>After that, we need to then define our prototype, as a subclass of <strong>NSCollectionViewItem</strong> - this must implement <strong>loadView</strong>, which will create a new <strong>CommitView</strong> instance, and <strong>setRepresentedObject</strong> which is passed an object from our content array, and so calls through to our <strong>setViewObject</strong> on our custom view to setup the various controls with the right data. This means that the collection view will loop through the array of content objects, instantiating a collection view item using our prototype, which in turn creates an instance of our custom view, and passes the relevant commit object all the way through to the view to render correctly.</p>
<p>All that remains now is to setup the <strong>NSCollectionView</strong> itself within our custom panel, which we’ll do in our <strong>AppDelegate</strong>. Where we previously created the window, below that we’ll go ahead and setup a scroll view first of all:</p>
<pre><code class="language-plaintext">scroll_view = NSScrollView.alloc.initWithFrame(NSInsetRect(@window.contentView.frame,
  PopupBackground::LINE_THICKNESS + SCROLL_VIEW_INSET, PopupBackground::ARROW_HEIGHT + SCROLL_VIEW_INSET))
scroll_view.hasVerticalScroller = true
@window.contentView.addSubview(scroll_view)
</code></pre>
<p>We’re using a scroll view so that we can have content a lot longer than our custom pane (given that the idea is to keep it quite small to sit beneath the status menu item, and there might be a lot of commits to show). It’s fairly easy to get going - we’re setting the frame to be inset slightly from the content view frame, to avoid getting too close to the rounded corners and overlapping them, and we’re making sure it’s a vertical scroller so we can scroll up and down our commit list.</p>
<p>We’re then going to setup our collection view using the scroll view frame, and we’re giving it an instance of the commit prototype so that it’ll know how to create our custom views. We then assign that to the scroll view:</p>
<pre><code class="language-plaintext">@collection_view = NSCollectionView.alloc.initWithFrame(scroll_view.frame)
@collection_view.setItemPrototype(CommitPrototype.new)

scroll_view.documentView = @collection_view
</code></pre>
<p>The last piece of the puzzle is getting the data into the collection view each time it changes - here we need to delve into our <strong>checkForNewEvents</strong> method that processes our GitHub events. We can remove a fair bit of code now as things are nice and simple (you can see the exact changes in <a href="https://github.com/kickcode/CommitTrackerMenu/commit/d87d6c64f9ff6d813f2fb66c74f0c46483c43a0d#diff-0">this</a> diff). However, the most important thing is creating instances of our <strong>Commit</strong> struct for each commit with the right data from the GitHub API, and appending it to an array that we setup towards the beginning of <strong>checkForNewEvents</strong>:</p>
<pre><code class="language-plaintext">@data &#x3C;&#x3C; Commit.new(actor, repo, message, avatar, url)
</code></pre>
<p>And after we’ve finished processing all of the commits, we update the collection view quite easily:</p>
<pre><code class="language-plaintext">@collection_view.setContent(@data)
</code></pre>
<p>Running the app now and clicking the menu item will show the custom panel, complete with the custom commit views for each commit found. Clicking an item will open it as it did before (and auto hide the panel).</p>
<h3>Additional options</h3>
<p>This all functions really well, but we’ve lost a little bit of potentially vital functionality - the menu options to show the about window, and to quit the app! The nice thing is we still have our menu with those options, and we can add a button to our custom panel that when clicked will show that exact same menu but as a context sensitive popup menu instead!</p>
<p>We just need to setup an <strong>NSButton</strong> within our <strong>AppDelegate</strong> and add it to the content view of our custom window, which we’ll do beneath the scroll view:</p>
<pre><code class="language-plaintext">@options_button = NSButton.alloc.initWithFrame(NSMakeRect(PopupPanel::POPUP_WIDTH - BUTTON_WIDTH, 0,
  BUTTON_WIDTH, BUTTON_HEIGHT))
@options_button.setTitle("Options")
@options_button.setButtonType(NSMomentaryLightButton)
@options_button.setBezelStyle(NSRoundedBezelStyle)
@options_button.setTarget(self)
@options_button.setAction('showMenu:')
@window.contentView.addSubview(@options_button)
</code></pre>
<p>And then we’ll implement the <strong>showMenu</strong> event handler:</p>
<pre><code class="language-plaintext">def showMenu(sender)
  NSMenu.popUpContextMenu(@status_menu, withEvent: NSApp.currentEvent, forView: sender)
end
</code></pre>
<p>Now when you run the app, you’ll see we have an options button at the bottom, and clicking it reveals our menu with the about and quit functionality working just the same as before! This is a great way to still tuck away the standard stuff your app might need in a normal menu, but retain all of the power and customisation that building your own custom user interface will bring you.</p>
<p>Here is what our end result looks like:</p>
<p><img src="https://ejdraper.com/images/commit_tracker_menu.png" alt="Commit Tracker Menu with fancy UI"></p>
<p>Phew, that was a quite a long tutorial this time! But we’ve seen that relatively speaking, it isn’t a whole lot of code to implement a custom user interface that you can tweak to better suit your own app. You could tweak the <strong>PopupBackground</strong> drawing to do something different, and of course you don’t have to use a scroll view and collection view to display the data - it depends on what you are showing. If you do use a collection view, you can customise your own item view that best suits the data you’re showing. There are a number of different ways to use this approach, but end up with a result perfectly tailored to your app.</p>
<p>As we didn’t cover every last line of code that was changed, and there were a few more general tweaks made to the app since our last article, you can view all of the changes in this <a href="https://github.com/kickcode/CommitTrackerMenu/compare/2e996de73a83eeba1ca2126bb1f1296af502fe84...8a11efeb87be8829eca72b33595bae60d9c3647e">diff</a> over on GitHub.</p>
<p>Let me know if you enjoyed the article, or if you have any questions, comments or suggestions, either below, or <a href="http://twitter.com/ejdraper">@ejdraper</a> on Twitter!</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Displaying user notifications in your RubyMotion OS X app]]></title>
            <link>https://ejdraper.com/2013/11/27/user-notifications-in-your-os-x-app</link>
            <guid isPermaLink="false">https://ejdraper.com/2013/11/27/user-notifications-in-your-os-x-app</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>Notification Center was first announced for Mac OS X 10.8 Mountain Lion, and then it saw some improvements for Mac OS X 10.9 Mavericks. Similar to the notifications on iOS, it provides a convenient way for applications to show information to the user, and is especially useful for applications that run in the background, or that have a background processing component that needs to display and highlight information to the user.</p>
<h3>Notify</h3>
<p>Using them is fairly straightfward - we’ll run through how to add them to an application, and we’re going to build upon the small status bar app we created in the <a href="https://ejdraper.com/2013/11/22/talking-to-an-api-from-your-rubymotion-app">last tutorial</a> to demo this. If you weren’t following along with that article, it ran through creating a status bar application which talked to a JSON API (the GitHub API) to retrieve commit data and show the latest commits from repositories you have access too. We can now extend that to popup a notification whenever new commits are found. We can also respond to a click on the notification by showing the menu containing the list of commits. All of the <a href="https://github.com/kickcode/CommitTrackerMenu/commit/c44e89209780ee1ec6ca1ea8a976276061faee0d">changes</a> we’ll be making are to the <a href="https://github.com/kickcode/CommitTrackerMenu/blob/master/app/app_delegate.rb">app_delegate.rb</a> file.</p>
<p>First things first, we need to add something to the end of our <strong>applicationDidFinishLaunching</strong> method:</p>
<pre><code class="language-plaintext">NSUserNotificationCenter.defaultUserNotificationCenter.setDelegate(self)
</code></pre>
<p>This will allow us to intercept events regarding our notifications, and handle the clicks on them, which we’ll cover shortly.</p>
<p>Next up, we’ll add a method to show new commits as a notification:</p>
<pre><code class="language-plaintext">def showNotification(new_commits)
  return unless new_commits > 0
  notification = NSUserNotification.alloc.init
  notification.title = "New commits"
  notification.informativeText = "There are #{new_commits} new commits."
  notification.soundName = NSUserNotificationDefaultSoundName
  NSUserNotificationCenter.defaultUserNotificationCenter.scheduleNotification(notification)
end
</code></pre>
<p>Here we’re making sure we only trigger a new notification when there are new commits, we’re setting the title and text, and we’re using a default sound (the very familiar tri-tone noise). You can also specify a path to a.caf audio file in the resources bundle of the app, if you so wish. Lastly, we schedule the notification with the user notification center, and as we set no particular scheduled date for the notification, it shows immediately. You could schedule a notification for a specific time by setting the <strong>deliveryDate</strong> on the notification before adding to the user notification center - this one is scheduled for 10 minutes from now:</p>
<pre><code class="language-plaintext">notification.deliveryDate = Time.now + (10 * 60)
NSUserNotificationCenter.defaultUserNotificationCenter.scheduleNotification(notification)
</code></pre>
<p>Now we need to trigger our notifications method, so we’re going to dip into our <strong>checkForNewEvents</strong> method, which is where our commit processing happened, and towards the end where we used to have the following:</p>
<pre><code class="language-plaintext">@unseen += (@commits - @last_commits).length
self.showUnseenCommits
</code></pre>
<p>We’ll modify that to this:</p>
<pre><code class="language-plaintext">new_commits = (@commits - @last_commits).length
@unseen += new_commits
self.showUnseenCommits
self.showNotification(new_commits)
</code></pre>
<p>What we’re doing here is taking the amount of new commits we found (the difference between our <strong>@commits</strong> and <strong>@last_commits</strong> arrays), and we’re adding it to the unseen counter to display the total number of unseen commits on the menu, as before. We’re then however using just the amount of new commits for this particular call, to display the notification in the user notification center. Essentially the menu bar item itself tracks a running tally of unseen commits, but the notifications should only ever let you know of new ones it has found since the last time it showed a notification.</p>
<p>If you run the app now, you’ll see that as soon as it starts up and pulls back the initial list of commits, it triggers a notification! However if we click on it in the user notification center, nothing happens. Ideally, we want it to trigger something to show in our app, and also to remove the notification as it has now been seen and processed by the user.</p>
<p>As we’ve already setup our AppDelegate as a delegate for the user notification center in <strong>applicationDidFinishLaunching</strong>, all that remains is to handle the approriate event by creating a method as follows:</p>
<pre><code class="language-plaintext">def userNotificationCenter(center, didActivateNotification: notification)
  @status_item.popUpStatusItemMenu(@status_menu)
  center.removeDeliveredNotification(notification)
end
</code></pre>
<p>The <strong>didActivateNotification</strong> method is what handles the click on a notification created by our app, and so we perform two functions here - the first is to trigger the status bar menu to popup, showing the latest commits, and the second is to remove the delivered notification from the notification center, thereby clearing it out of the users way.</p>
<h3>Notified</h3>
<p>That’s it, a fairly short tutorial this time around, mainly because the <strong>NSUserNotification</strong> and <strong>NSUserNotificationCenter</strong> APIs are very clean, tidy and easy to work with. They provide some great additional interaction with your users, making apps more interesting, informative and accessible - and all in just a few lines of code! You can see the above changes in a commit to our existing codebase <a href="https://github.com/kickcode/CommitTrackerMenu/commit/c44e89209780ee1ec6ca1ea8a976276061faee0d">here</a>, and you can of course grab the entire code for the app <a href="https://github.com/kickcode/CommitTrackerMenu">here</a>.</p>
<p>If you have any comments, questions or suggestions, please let me know below. Remember to follow <a href="http://twitter.com/ejdraper">@ejdraper</a> on Twitter to hear about the latest articles as we put them up!</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to integrate your RubyMotion OS X app with a JSON based web API]]></title>
            <link>https://ejdraper.com/2013/11/22/talking-to-an-api-from-your-rubymotion-app</link>
            <guid isPermaLink="false">https://ejdraper.com/2013/11/22/talking-to-an-api-from-your-rubymotion-app</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>In our <a href="https://ejdraper.com/2013/11/07/rubymotion-background-process-in-status-bar-app">last article</a> on <a href="http://www.rubymotion.com/">RubyMotion</a> OS X apps, we built a status bar app that fetched data in the background to keep the menu item continually updated and showing the latest information. Our data source was from the local system, fetching the CPU usage statistics. In this article we’ll look at how to integrate with a JSON web API, making HTTP calls from your RubyMotion app, processing the response, and showing that in the menu.</p>
<h3>You have to commit</h3>
<p>The little utility app we’ll build will be a very basic and straightforward one to show the latest commits from projects you have access to on <a href="https://github.com/">GitHub</a>. GitHub has a wonderful JSON API, complete with <a href="http://developer.github.com/">very good documentation</a>, and for developers, utility apps integrating with GitHub can be very useful indeed. You can follow along with the code in the article, and the app is open source and available in full <a href="http://github.com/kickcode/CommitTrackerMenu">here</a> too.</p>
<h3>Familiar start</h3>
<p>By now if you’ve been following along with the RubyMotion on OS X series of articles, you’ll know our starting point. We’ll use the template gem from our <a href="https://ejdraper.com/2013/10/18/rubymotion-status-bar-apps-for-osx">first article</a> to spin up a new app. Let’s fire up a blank status bar app now:</p>
<pre><code class="language-plaintext">motion create --template=osx-status-bar-app CommitTrackerMenu
</code></pre>
<h3>Dependencies</h3>
<p>First thing we’ll do is add the gems we’ll need, <a href="https://rubygems.org/gems/bubble-wrap">BubbleWrap</a>, and <a href="https://rubygems.org/gems/motion-yaml">motion-yaml</a>. Your Gemfile should look something like this:</p>
<pre><code class="language-plaintext">source 'https://rubygems.org'

gem 'rake'
gem 'bubble-wrap'
gem 'motion-yaml'
</code></pre>
<p>Remember to run this when you’re done too:</p>
<pre><code class="language-plaintext">bundle install
</code></pre>
<h3>Configuration</h3>
<p>We’ll come to BubbleWrap in a minute, but we’re using motion-yaml for the configuration for the app - to load our config file and ready it for use in our code, add the following to your <strong>AppDelegate</strong>:</p>
<pre><code class="language-plaintext">class AppDelegate
  CONFIG = YAML::load(NSMutableData.dataWithContentsOfURL(
    NSBundle.mainBundle.URLForResource("config", withExtension: "yml")).to_s)
</code></pre>
<p>This finds the config in the root of the resource bundle, and loads the YAML contents into the constant. You’ll see an <a href="https://github.com/kickcode/CommitTrackerMenu/blob/master/resources/config.yml.example">example config file</a> in the GitHub <a href="http://github.com/kickcode/CommitTrackerMenu">repo</a> for the code, you just need to rename <strong>config.yml.example</strong> to <strong>config.yml</strong> and fill in your GitHub personal access token - you can get one by visiting <a href="https://github.com/settings/applications">here</a>. You can also amend the timer config to specify how often to check for new updates. It should end up looking something like this:</p>
<pre><code class="language-plaintext">timer: 30
github_token: TOKEN
</code></pre>
<h3>GitHub integration</h3>
<p>Now, let’s work on integration with the API itself - this is where BubbleWrap comes in handy. This gem is a fantastic collection of all sorts of great functionality, nice Ruby wrappers around more complicated Cocoa APIs, shortcuts for often used features, and helpers that take advantage of Ruby language features to provide nicer ways of doing things. It’s a veritable Swiss Army Knife for iOS and OS X development.</p>
<p>We’ll be using <strong>BW::HTTP</strong> and <strong>BW::JSON</strong> to grab the data we need and to parse it. We’ve separated out our GitHub integration into a separate class to make it easier to read, so here it is in full:</p>
<pre><code class="language-plaintext">class GitHub
  attr_accessor :token, :user

  def initialize(token, &#x26;block)
    @token = token
    self.user do |json|
      @user = json
      block.call
    end
  end

  def user(&#x26;block)
    self.get("https://api.github.com/user", &#x26;block)
  end

  def events(&#x26;block)
    self.get(@user['received_events_url'], &#x26;block)
  end

  def get(url, &#x26;block)
    BW::HTTP.get(url, {:credentials => {:username => @token, :password => ""}}) do |response|
      block.call(BW::JSON.parse(response.body))
    end
  end
end
</code></pre>
<p>There isn’t a lot to this, essentially we initialize the client with our personal access token. It immediately uses the token to do a quick check, and load the authenticated user JSON - this way we don’t need further user details such as username to make additional calls. It’ll call any block passed into that initialization method when that process is complete, allowing you to wait until the client is ready before doing anything else.</p>
<p>We have a method to retrieve events for the user which we’ll be using as our data source in the status bar itself in a minute, but you’ll see both that and the authenticated user call are wrappers themselves around the get method, which uses the BubbleWrap HTTP methods to easily call to the URL, passing the provided credentials (using the token over basic auth for GitHub means providing the token as the username, and leaving the password blank), and then processing the response body. In this case, we use the BubbleWrap JSON support to parse the body and return an array or hash parsed from the API.</p>
<p>Lastly, you’ll notice too that in the events method, we’re using something provided by the response from the authenticated user check as the URL (<strong>received_events_url</strong> returned within <strong>@user</strong>). The GitHub API helpfully returns other API call URLs within the authenticated user response, which we can then parse and use for further calls. This way, if their API changes and they move or update URLs, our code won’t break as it’s using the pointer to the right method provided by GitHub themselves, rather than a hard-coded URL!</p>
<h3>Menu setup</h3>
<p>With that out of the way, we can now focus back on our status bar app. First, we need to setup our menu items, so our <strong>applicationDidFinishLaunching</strong> method should look like this:</p>
<pre><code class="language-plaintext">def applicationDidFinishLaunching(notification)
  @app_name = NSBundle.mainBundle.infoDictionary['CFBundleDisplayName']

  @status_menu = NSMenu.new
  @status_menu.delegate = self

  @status_item = NSStatusBar.systemStatusBar.statusItemWithLength(NSVariableStatusItemLength).init
  @status_item.setMenu(@status_menu)
  @status_item.setHighlightMode(true)
  @status_item.setTitle(@app_name)

  @http_state = createMenuItem("Loading...", '')
  @http_state.enabled = false
  @status_menu.addItem @http_state

  @status_menu.addItem createMenuItem("About #{@app_name}", 'orderFrontStandardAboutPanel:')
  @status_menu.addItem createMenuItem("Quit", 'terminate:')

  @unseen = 0
  @github = GitHub.new(CONFIG[:github_token]) do
    self.checkForNewEvents
  end
end
</code></pre>
<p>This should be fairly familiar if you’ve been following along with the previous articles. A few key differences, we’re setting the delegate on the status menu to the app delegate itself - we’re doing that so we can look out for a specific event, but we’ll come back to that a little later.</p>
<p>We’re creating a disabled menu item, <strong>@http_state</strong>, used just to display information on the state of the app, so we can update it to show when we’re doing different things. We instantiate it and set it to show “Loading…” to start with.</p>
<p>We then instantiate the GitHub client, and pass in a block that will get called when the initial authenticated user JSON is returned - we need to wait for this, as any subsequent calls won’t work until that has completed. We can then kick off our check for new events. This is where we check with our data source, in this case the GitHub API, and it’s where the meat of the app lies.</p>
<h3>Events</h3>
<p>The method that checks for and processes events from the GitHub API does quite a lot, so we’ll step through it and explain how it works - if you want to see the entire thing, you can do so <a href="https://github.com/kickcode/CommitTrackerMenu/blob/master/app/app_delegate.rb#L33">here</a>.</p>
<pre><code class="language-plaintext">def checkForNewEvents
  begin
    @http_state.title = "Working..."
    @github.events do |events|
      @http_state.title = "Processing..."
</code></pre>
<p>We start by setting our <strong>@http_state</strong> menu item to show us as working, and then as soon as we get the response from GitHub, we switch that to processing.</p>
<pre><code class="language-plaintext">unless events.empty?
  @events.each { |item| @status_menu.removeItem(item) } unless @events.nil?
  @events = []
  @urls = {}
  @last_commits = @commits || []
  @commits = []
</code></pre>
<p>Here we make sure that we have something to process, and then we are removing any menu items that we had previously pertaining to events. Each time this runs it’ll clear out the event menu items, and recreate them based on the data found. In addition to the variable to track those menu items (<strong>@events</strong>), we also have a hash to track URLs (<strong>@urls</strong>), which comes into play when we’re handling menu item clicks for these events, as well as a couple of variables to help us track what’s new between calls (<strong>@commits</strong> and <strong>@last_commits</strong>).</p>
<pre><code class="language-plaintext">counter = 0
events.reverse.each do |event|
  next unless event["type"] == "PushEvent"
  next if event["payload"].nil? || event["payload"]["commits"].nil?

  commits = event["payload"]["commits"].select { |c| c["distinct"] }

  next if commits.length == 0
</code></pre>
<p>We’re now going to loop through all the events returned - we do so in reverse order, as we’ll be adding each menu item in at a specific index, which will in turn push all of those before it further down. So that we end up with date descending (newest first) order in the end, we reverse things to begin with.</p>
<p>We’re skipping over any event that isn’t a push event (code being pushed up to a repository), and that doesn’t have a payload or commits.</p>
<p>Lastly, we also ignore any commits that aren’t <strong>distinct</strong> - this is a very handy flag provided by GitHub from their API, and by distinct they mean if a commit has been seen in the repo before, i.e. if something was pushed as part of a branch, it’d be distinct, but then merging it into master, it’s the same commit, and it is no longer distinct. We only want to be notified of entirely new commits, so we filter out anything that isn’t distinct.</p>
<pre><code class="language-plaintext">actor = event['actor']['login']
repo = event['repo']['name']

commits.each do |commit|
  message = commit['message'].split("\n").first
  message = "#{message[0...30]}..." if message.length > 35
  @urls[counter] = commit['url'].gsub("api.", "").gsub("/repos", "").gsub("/commits", "/commit")
  item = self.createMenuItem("[#{actor}]: #{repo} - #{message}", 'pressEvent:')
</code></pre>
<p>Now we loop through the commits we have left to look at, and we’ll do a bit of processing on the message and URL. We want to truncate the message to a reasonable uniform length, and we need to mess with the URL a bit as the URL returned from GitHub points to the commit within the API, and we want a URL we can open in a browser to show the commit - the always useful String <strong>gsub</strong> method comes in handy there as we stash the URL in our <strong>@urls</strong> hash for looking up later.</p>
<p>We then setup the menu item, similarly to how we’ve done before. Each item will use the same event handler, which we’ll look at shortly. One thing to note is that by specifying <strong>pressEvent:</strong>, instead of just <strong>pressEvent</strong> (note the trailing colon), then our event handler will be sent an argument, the sender of the event, in this case the item itself. As we’re handling all of the item events with the same event handler method, and using the tag on the item to lookup the URL to show, it’ll be quite handy to be sent the clicked item!</p>
<pre><code class="language-plaintext">item.tag = counter
    @events &#x3C;&#x3C; item
    @status_menu.insertItem(item, atIndex: 1)
    counter += 1
    @commits &#x3C;&#x3C; commit['sha']
  end
end
</code></pre>
<p>Here we set a tag on the item, and this is where our counter comes in - we can only use an integer for the tag, but we need a reference to our URL for use in the event handler. So we’ve used the counter as a numeric pointer to the URL in our URLs hash (<strong>@urls</strong>), and we set it on the item so we can match the two together. We are then keeping track of our event menu item (so we can remove it from the menu next time we re-process), and then insert the item into the menu at the same index for each item. We’re doing it at index 1 instead of index 0 so as to always leave the <strong>@http_state</strong> menu item at the top of the menu as the others get pushed down with each new item added.</p>
<p>We then increment our counter for the next commit, and stash the unique SHA reference for the commit in <strong>@commits</strong> so we can compare which commits we’ve seen this time with last time for working out which commits are new.</p>
<pre><code class="language-plaintext">@unseen += (@commits - @last_commits).length
  self.showUnseenCommits
end
</code></pre>
<p>Here we use our arrays of the commit references (<strong>@commits</strong> for this time, <strong>@last_commits</strong> for the last time around) to deduce how many new commits there are in this run, and add that to our unseen total tracking variable, <strong>@unseen</strong>. The method to show those we’ll get into below.</p>
<pre><code class="language-plaintext">@http_state.title = "Ready"
  end
rescue
  @http_state.title = "Error, retrying again shortly"
</code></pre>
<p>If everything finishes as expected, we set the <strong>@http_state</strong> menu item to show things as ready for the next call - and if we experienced an error, we make that clear too.</p>
<pre><code class="language-plaintext">ensure
    NSTimer.scheduledTimerWithTimeInterval(CONFIG[:timer],
      target: self,
      selector: 'checkForNewEvents',
      userInfo: nil,
      repeats: false)
  end
end
</code></pre>
<p>Whatever happens though, the <strong>ensure</strong> part of the <strong>begin/rescue/ensure</strong> block will always end by triggering the next call. We’re using our timer configuration to schedule the same method to be called again. We do this rather than simply call it once at the beginning but with <strong>repeats</strong> set to true, because the call itself and subsequent processing will take a variable amount of time. For the most part it’s very quick, but network slowdowns, poor connections, or timeouts could cause it to take a bit longer. We want our delay between calls to be just that - between calls, not between the time each call is kicked off, regardless of result. From the time our processing ends, to the time it runs again, will be the value we’ve configured.</p>
<h3>Mark all as read</h3>
<p>We have a couple of steps left to flesh out. Above we called <strong>showUnseenCommits</strong> after incrementing how many unseen commits there were - it’s a fairly simple update to the title of the main system menu item for our app:</p>
<pre><code class="language-plaintext">def showUnseenCommits
  @status_item.setTitle("#{@unseen.zero? ? 'No' : @unseen} new #{@unseen == 1 ? 'commit' : 'commits'}")
end
</code></pre>
<p>When we click on the menu, it’d be good to clear the message, sort of a mark all as read. This is the reason we set the delegate for the status menu to be the app delegate itself - luckily we can easily handle the event of the menu opening (in response to the click) by implementing <strong>menuWillOpen</strong>, and in there we can clear the message by setting <strong>@unseen</strong> to zero and updating the status menu text:</p>
<pre><code class="language-plaintext">def menuWillOpen(menu)
  @unseen = 0
  self.showUnseenCommits
end
</code></pre>
<h3>Click to view</h3>
<p>Lastly, when we click on an item, it’d be great to go to that commit on GitHub for viewing. We’ve already stashed the URLs when processing the events above, and so we now just need to lookup the particular URL, which we can do with the numeric tag property on the item. That’s our pointer into the URLs hash, <strong>@urls</strong>, and so our event handler looks like this:</p>
<pre><code class="language-plaintext">def pressEvent(item)
  NSWorkspace.sharedWorkspace.openURL(NSURL.URLWithString(@urls[item.tag]))
end
</code></pre>
<p><strong>NSWorkspace.sharedWorkspace.openURL</strong> is a nice way to use your system default way of opening a URL, i.e. your default browser. Easy!</p>
<p>You can now fire up the app to see it all working together.</p>
<h3>Wrapping up - questions?</h3>
<p>And that’s about it - much like last time, we’ve built a status bar app that runs in the background, updating from a data source. This time though we used HTTP calls and JSON processing to interact with a 3rd party API to make the data a bit more interesting, we used YAML for file configuration, we used a timer instead of a background thread to periodically check for new data, and we dynamically updated our menu list based on the data we brought back, bringing even greater interactivity into our fairly basic app. Remember you can check out all the code <a href="http://github.com/kickcode/CommitTrackerMenu">here</a>.</p>
<p>In our next few articles we’ll look at integrating notifications within our apps to make notifying the user of a change more prominent and useful, and we’ll also start to explore custom user interfaces, to improve the experience for users of your Mac OS X apps, both for status bar apps as we’ve been focusing on thus far, but also for window based apps.</p>
<p>Hopefully you’re enjoying my articles on RubyMotion development - as always, let me know your thoughts, comments and questions below, or contact me on Twitter <a href="http://twitter.com/ejdraper">@ejdraper</a>!</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a RubyMotion status bar app that updates in the background]]></title>
            <link>https://ejdraper.com/2013/11/07/rubymotion-background-process-in-status-bar-app</link>
            <guid isPermaLink="false">https://ejdraper.com/2013/11/07/rubymotion-background-process-in-status-bar-app</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>In our <a href="https://ejdraper.com/2013/10/18/rubymotion-status-bar-apps-for-osx">last post</a> we looked at how easy it is to create an OS X menu bar app using <a href="http://www.rubymotion.com/">RubyMotion</a>. This time around, we’ll look at one of the ways we can make status bar apps more useful - having it fetch and display data from an external source in the background. In our specific example, we’ll be wrapping the <a href="https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/top.1.html">top</a> commandline tool, to pull out CPU usage and display it. It should demonstrate how you could replace that and roll in calls to other system commands for different data, or even API calls to web services to pull in live data from there too.</p>
<p>The code is open source and available <a href="https://github.com/kickcode/CPUTrackerMenu">here</a>. It’s based on using <a href="https://ejdraper.com/2013/10/18/rubymotion-status-bar-apps-for-osx">osx-status-bar-app-template</a> that we detailed in the last post, so if you want to build this yourself as we go along in the article, start by installing the <a href="https://rubygems.org/gems/osx-status-bar-app-template">osx-status-bar-app-template</a> gem and creating a new app using that template.</p>
<h3>Extensions</h3>
<p>First of all, we have one other code file besides the app delegate in the codebase. In <a href="https://github.com/kickcode/CPUTrackerMenu/blob/master/app/extensions/ns_menu_item.rb">app/extensions/ns_menu_item.rb</a>, we have the following:</p>
<pre><code class="language-plaintext">class NSMenuItem
  def checked
    self.state == NSOnState
  end

  def checked=(value)
    self.state = (value ? NSOnState : NSOffState)
  end
end
</code></pre>
<p>If you’ve worked with Ruby before, you’ll know that you can re-open classes to add methods to them, and if you’ve worked with Objective-C much you’ll know that you can do something similar with categories. All we’re essentially doing here is adding some convenience short-hand methods to menu items to allow us to check and uncheck them, and to see if they’re checked. You’ll see how this is used shortly.</p>
<h3>Setting up our menu</h3>
<p>Let’s setup the menu items we need in <a href="https://github.com/kickcode/CPUTrackerMenu/blob/master/app/app_delegate.rb">app/app_delegate.rb</a>. The idea is we’ll have three options, <em>Total</em> to show total CPU usage, <em>User</em> to show the user CPU usage, and <em>System</em> to show the sys CPU usage value. In our <strong>applicationDidFinishLaunching</strong> method, alongside the default menu items created for <em>about</em> and <em>quit</em>, add our three new menu items in:</p>
<pre><code class="language-plaintext">@total_item = createMenuItem("Total", 'clickTotal')
@total_item.checked = true
@status_menu.addItem(@total_item)

@user_item = createMenuItem("User", 'clickUser')
@user_item.checked = false
@status_menu.addItem(@user_item)

@system_item = createMenuItem("System", 'clickSystem')
@system_item.checked = false
@status_menu.addItem(@system_item)
</code></pre>
<p>We’ll also add the following to <strong>applicationDidFinishLaunching</strong>:</p>
<pre><code class="language-plaintext">@user = 0
@sys = 0
self.updateStatus
</code></pre>
<p>We’ll be implementing <strong>updateStatus</strong> shortly, but it’s what sets the title text in the menu bar based on the current values, which we’ve defaulted to 0 above.</p>
<p>Next up, we need to implement the event handlers for each menu item click. We’re going to get a bit funky with the selection, so that if you check <em>Total</em>, it only shows that, and unchecks the other two. You can select either or both of the other two to show, and if you deselect both, it goes back to having <em>Total</em> selected. Our three event handlers look like this:</p>
<pre><code class="language-plaintext">def clickTotal
  @user_item.checked = false
  @system_item.checked = false
  @total_item.checked = true
  self.updateStatus
end

def clickUser
  @total_item.checked = false
  @user_item.checked = !@user_item.checked
  self.mustSelectSomething
  self.updateStatus
end

def clickSystem
  @total_item.checked = false
  @system_item.checked = !@system_item.checked
  self.mustSelectSomething
  self.updateStatus
end

def mustSelectSomething
  @total_item.checked = true if !@user_item.checked &#x26;&#x26; !@system_item.checked
end
</code></pre>
<p>If you select the total one, it automatically unchecks the other two, and you can’t click to unselect it. If you select either user or system, it will uncheck the total one, and either uncheck or check itself, depending upon its current state. They both also use the <strong>mustSelectSomething</strong> method to double check and ensure that if after the click the result is that neither is selected, then the total becomes selected again. All three event handlers finish up by triggering a call to update the status text. Let’s look at how that is implemented next:</p>
<pre><code class="language-plaintext">def updateStatus
  if @total_item.checked
    @status_item.setTitle("CPU: #{sprintf("%.2f", @user + @sys)}%")
  else
    text = []
    text &#x3C;&#x3C; "User: #{sprintf("%.2f", @user)}%" if @user_item.checked
    text &#x3C;&#x3C; "Sys: #{sprintf("%.2f", @sys)}%" if @system_item.checked
    @status_item.setTitle(text.join(", "))
  end
end
</code></pre>
<p>Here is where we’re using the status of each menu item, checked or unchecked, to decide what to show. If total is checked, we’re showing the sum of both the user and sys values as a total CPU usage figure. If not, then we’re showing user, sys, or both, based on which ones are checked. Hopefully by now it’s obvious why we added those convenience methods to the menu items, to make seeing if an item is checked a bit less verbose!</p>
<p>If you run the app, you’ll see it works, showing 0.0% for all figures, but allowing you to toggle between the various different displays. So what we’re now missing is the external source to give us data, and a way to have it run in the background to update the status bar all on its own.</p>
<h3>Driven by data</h3>
<p>We’re going to use the <strong>top</strong> command as the source for our values, and we’re going to use <a href="http://www.ruby-doc.org/core-2.0.0/IO.html#method-c-popen">IO.popen</a> to open up a pipe to the command sampling values continuously. <strong>top</strong> produces a lot of data, so we’ll be filtering it out and looking for the specific line that contains CPU values, then parsing those out. It’s not too tricky, and the whole thing looks like this:</p>
<pre><code class="language-plaintext">def startTop
  IO.popen("top -l 0") do |f|
    while true
      unless((line = f.gets).nil?)
        if line[0...10] == 'CPU usage:'
          line.gsub!("CPU usage: ", "")
          line.split(", ")
          @user, @sys = line.split(", ").map { |p| p.split("%").first.to_f }
          self.updateStatus
        end
      end
    end
  end
end
</code></pre>
<p>Running <strong>top -l 0</strong> is what gives us the output in a format we can work with from a script - by default top is pretty clever, and replaces the output every sample so that when you run it in a terminal, it seems like it updates on screen (rather than scrolling in new data for each sample). By passing -l we’re asking it to run for a specific amount of samples, giving us the output in a raw form, and by specifying 0 rather than a set amount, we’re telling it we want it to run infinitely. With a pipe open to that command running endlessly, we can then read each line, check to see if it’s the line we’re looking for, and then parse out the data. The lines we want look like this:</p>
<pre><code class="language-plaintext">CPU usage: 3.79% user, 3.12% sys, 93.8% idle
</code></pre>
<p>Once we strip out the <em>CPU usage:</em> heading, we can then split on the comma to separate our values, and split on the % to separate the value from the name. We can then parse it as a float, and we just pull out the first two as our user and sys values (we don’t use the idle value). This is an example of how Ruby’s superior string handle really comes in handy, you can see what our breakdown and parsing of that line looks in a Ruby console:</p>
<pre><code class="language-plaintext">> line = "CPU usage: 3.79% user, 3.12% sys, 93.8% idle"
=> "CPU usage: 3.79% user, 3.12% sys, 93.8% idle"
> line.gsub!("CPU usage: ", "")
=> "3.79% user, 3.12% sys, 93.8% idle"
> line.split(", ")
=> ["3.79% user", "3.12% sys", "93.8% idle"]
> line.split(", ").map { |p| p.split("%") }
=> [["3.79", " user"], ["3.12", " sys"], ["93.8", " idle"]]
> line.split(", ").map { |p| p.split("%").first }
=> ["3.79", "3.12", "93.8"]
> line.split(", ").map { |p| p.split("%").first.to_f }
=> [3.79, 3.12, 93.8]
</code></pre>
<p>We fairly effortless and reliably go from a string output from <strong>top</strong>, to pulling out the two values we need. From there, it calls <strong>updateStatus</strong> to reflect the updated values, and we’re golden. Except, how does this method get called? If you try to call <strong>startTop</strong> directly from within <strong>applicationDidFinishLaunching</strong>, then it will fire up and continuously run to pull out values - but you can’t interact with the menu bar app at all, and it won’t update beyond the initial value being shown. This is because our <strong>startTop</strong> method runs endlessly, and thus blocks the main thread when called in that manner. Any UI interactions or any further interaction with the app doesn’t work. We need a way to explicitly call that method in the background of our app, so it happens on a separate thread. Luckily, this is fairly straightforward - add this to the end of <strong>applicationDidFinishLaunching</strong>:</p>
<pre><code class="language-plaintext">self.performSelectorInBackground('startTop', withObject: nil)
</code></pre>
<p>This call returns immediately, firing up that method in a background thread, and meaning that interaction with the app continues as normal, and our <strong>startTop</strong> method keeps running in the background, parsing out the latest values and updating the status bar title text. Voila, we have an app that is talking to a data source in the background, and updating the status bar all on its own. Replacing the <strong>startTop</strong> method with whatever data source you want to regularly query to return data to show in the status bar would be fairly trivial.</p>
<p>If you fire up the app now, you can see it update in real-time:</p>
<p><img src="https://ejdraper.com/images/cputrackermenu.gif" alt="CPUTrackerMenu"></p>
<h3>What next?</h3>
<p>What data sources can you think of that’d be useful to ping and show data from in your status bar? Chances are there are a bunch of things you’d like to keep an eye on, and now with just a small amount of code, and RubyMotion, you can! With <a href="https://github.com/kickcode/CPUTrackerMenu">CPUTrackerMenu</a> too, you can even make sure that your own app isn’t taking up too much CPU by running in the background!</p>
<p>In a future post we’ll look at integrating with web service APIs from within your RubyMotion app - in the meantime, any questions related to this article, a previous article, or RubyMotion dev in general, let me know in the comments below, or catch me on Twitter <a href="http://twitter.com/ejdraper">@ejdraper</a>!</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to quickly get started creating status bar apps for Mac OS X using RubyMotion]]></title>
            <link>https://ejdraper.com/2013/10/18/rubymotion-status-bar-apps-for-osx</link>
            <guid isPermaLink="false">https://ejdraper.com/2013/10/18/rubymotion-status-bar-apps-for-osx</guid>
            <pubDate>Thu, 01 Jan 1970 00:00:00 GMT</pubDate>
            <content:encoded><![CDATA[<p>Recently here at KickCode we’ve been working on our first Mac OS X application, due for submission to the App Store shortly, and using <a href="http://www.rubymotion.com/">RubyMotion</a>. We’ll be unveiling it shortly, but it’s a fairly simple utility app that lives in the status bar. Status bar apps are quite useful, whethere it’s a utility for day to day productivity tasks, or whether it’s a connection or window into an online service, that provides background syncing, notifications, or other information.</p>
<h3>New gem</h3>
<p>The good news is, they’re fairly simple to get up and running using RubyMotion! Indeed, as with a lot of work in RubyMotion, it’s a lot less effort than building the equivalent in Xcode and Objective-C! And we’ve just made it a bit easier still, with a small gem called <a href="https://github.com/kickcode/osx-status-bar-app-template">osx-status-bar-app-template</a> that provides you with a new RubyMotion app template.</p>
<p>Simply run:</p>
<pre><code class="language-plaintext">gem install osx-status-bar-app-template
</code></pre>
<p>And then once installed, you can go ahead and create your new RubyMotion app using the template:</p>
<pre><code class="language-plaintext">motion create --template=osx-status-bar-app TestStatusBarApp
</code></pre>
<p>Then simply fire it up to see the basic skeleton app in action, ready for building upon:</p>
<pre><code class="language-plaintext">cd ./TestStatusBarApp
rake
</code></pre>
<p>At this point you’ll see an entry called “TestStatusBarApp” appear in your status bar, and clicking it will show you three options - a working about window, a custom action to show off how you handle menu item events, and a quit command. Note that the app doesn’t appear in the dock or the cmd+tab window, as it resides solely in the status bar!</p>
<p><img src="https://ejdraper.com/images/osx-status-bar-app.png" alt="RubyMotion app in OS X status bar"></p>
<h3>How it works</h3>
<p>As this is a RubyMotion template, it basically just creates the app skeleton for you, so we can delve into the code to understand better how it’s working, and how we can build on it.</p>
<p>To make the app status bar only, and have the dock and cmd+tab window ignore it as a targetable window, we have added the following to our Rakefile:</p>
<pre><code class="language-plaintext">app.info_plist['LSUIElement'] = true
</code></pre>
<p>We’ve also updated the spec/main_spec.rb to reference and test the status bar menu items instead of windows by default - you’ll want to update this as you make changes to your menus.</p>
<p>The rest of the good stuff happens inside app/app_delegate.rb as you might expect - and it’s surprisingly little code. In our applicationDidFinishLaunching method, we’re setting up a new NSMenu, and then creating a status item to sit in the system status bar:</p>
<pre><code class="language-plaintext">@status_menu = NSMenu.new

@status_item = NSStatusBar.systemStatusBar.statusItemWithLength(NSVariableStatusItemLength).init
@status_item.setMenu(@status_menu)
</code></pre>
<p>We’re using NSVariableStatusItemLength so that the status item can match the content. It’s easier to setup this way, but bear in mind that you probably don’t want the content that’ll appear in the status bar to be changing width too dramatically or too often, as that could be quite annoying!</p>
<p>Next up, we just set the highlight mode to true so that when you click the status bar item you get the blue highlight to show that you’ve clicked it, and we’re also setting the title to the app name:</p>
<pre><code class="language-plaintext">@status_item.setHighlightMode(true)
@status_item.setTitle(@app_name)
</code></pre>
<p>After that we can setup some of our menu items, but we’re using a helper method to make things a little less verbose:</p>
<pre><code class="language-plaintext">def createMenuItem(name, action)
  NSMenuItem.alloc.initWithTitle(name, action: action, keyEquivalent: '')
end
</code></pre>
<p>This just sets up a new menu item with the specified title and action (more on actions in a minute), and returns it. We can then use it like this:</p>
<pre><code class="language-plaintext">@status_menu.addItem createMenuItem("About #{@app_name}", 'orderFrontStandardAboutPanel:')
@status_menu.addItem createMenuItem("Custom Action", 'pressAction')
@status_menu.addItem createMenuItem("Quit", 'terminate:')
</code></pre>
<p>Actions are just references to methods that will act as event handlers for the menu item being clicked. The first and third items have actions that are “built-in” to OS X apps - namely with the default app structure, the about panel is already there and ready to use, and “orderFrontStandardAboutPanel:” shows that window. It contains a list of credits derived from a text file in the “resources” folder of your project (“Credits.rtf”). Within our new template, this is still the same as the one that comes with the default OS X template for RubyMotion, and should be edited to reflect your own details. The third item, with action “terminate:”, as you might expect refers to a method that is already accessible and that shuts the app down. It’s important to provide a way for the user to shutdown your status bar app, as it doesn’t appear in the dock or the “Force Quit” list!</p>
<p>The second menu item there is more interesting - “pressAction” is our own defined method, and acts as our event handler for a click on that item:</p>
<pre><code class="language-plaintext">def pressAction
  alert = NSAlert.alloc.init
  alert.setMessageText "Action triggered from status bar menu"
  alert.addButtonWithTitle "OK"
  alert.runModal
end
</code></pre>
<p>This too is fairly basic - we’re just popping up an NSAlert dialog to show that the menu item has been clicked, and the event handler has correctly received the event. That’s all there is to creating a basic status bar app in RubyMotion!</p>
<h3>Extending our app</h3>
<p>Now let’s extend our default app skeleton provided by the gem to do something a little more interesting. We’ll have a menu item action that updates the content of the status bar item itself. First of all, let’s update our spec to expect a fourth menu item:</p>
<pre><code class="language-plaintext">it "has four menu items" do
  @app.delegate.status_menu.itemArray.length.should == 4
end
</code></pre>
<p>Then, in our app delegate, lets setup a new menu item above the “quit” item, called increment:</p>
<pre><code class="language-plaintext">@status_menu.addItem createMenuItem("Increment", 'pressIncrement')
</code></pre>
<p>Lastly, let’s implement our event handler:</p>
<pre><code class="language-plaintext">def pressIncrement
  @count ||= 0
  @count += 1

  @status_item.setTitle("#{@count} times")
end
</code></pre>
<p>Here we’re establishing a variable to keep track of our count, if one isn’t already set, then we’re incrementing it. Finally we’re referencing our main status item (which remember refers to the item that sits in the status bar itself, not any of the child menu items that show when you click on the status bar item), and we’re updating the title with the count. Now if you fire up the app, and click “Increment” from the status bar app menu, you’ll see the value in the status bar update!</p>
<p><img src="https://ejdraper.com/images/osx-status-bar-app-increment.png" alt="RubyMotion app in OS X status bar extended with increment action"></p>
<p>From here you can see how it’ll now be fairly straightforward to start building slightly more useful functionality into the app, either hooking into system stats or calls to provide data, or perhaps calling out to a third party API to do interesting things, making it all available from the status bar. In a future article we’ll look at how to run things in the background to do something interesting that updates the status bar without direct user interaction.</p>
<h3>Feedback welcome</h3>
<p>In the meantime, check out the <a href="https://rubygems.org/gems/osx-status-bar-app-template">gem</a>, and let me know what you think! Any questions or comments on the above are welcome, either below or <a href="https://twitter.com/ejdraper">@ejdraper</a> on Twitter!</p>]]></content:encoded>
        </item>
    </channel>
</rss>