<?xml version="1.0" encoding="UTF-8"?><rss 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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Wes Alvaro on Medium]]></title>
        <description><![CDATA[Stories by Wes Alvaro on Medium]]></description>
        <link>https://medium.com/@wesalvaro?source=rss-49acf35f81ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*J7Kn9JVIxcnWMwSM.jpg</url>
            <title>Stories by Wes Alvaro on Medium</title>
            <link>https://medium.com/@wesalvaro?source=rss-49acf35f81ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 08:42:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wesalvaro/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[State vs StateFlow in Compose]]></title>
            <link>https://wesalvaro.medium.com/state-vs-stateflow-in-compose-cd13554a57f9?source=rss-49acf35f81ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd13554a57f9</guid>
            <category><![CDATA[state]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[compose]]></category>
            <dc:creator><![CDATA[Wes Alvaro]]></dc:creator>
            <pubDate>Thu, 13 Jun 2024 13:08:43 GMT</pubDate>
            <atom:updated>2025-10-10T04:52:54.480Z</atom:updated>
            <content:encoded><![CDATA[<p>When writing a ViewModel for a Compose UI, should I use Compose States or the more general-use Kotlin StateFlows? I recently asked myself this question and looked to the Internet for answers. Surprisingly, most were much more in favor of StateFlows.</p><p><em>Maybe they’re just not thinking with States</em>.</p><p>The same charm points for Flows came up in several write-ups I read and videos I watched:</p><ul><li>Flows have convenient operators</li><li>Flows better handle process death</li><li>Flows allow for ViewModel reusability</li><li>Flows handle changing values over time</li></ul><p>And similarly, the negative points for States:</p><ul><li>States are annoyingly always Mutable</li><li>States must annoyingly be set on the main thread</li></ul><p>We should certainly use the right tool for the job, so I wouldn’t argue for using States everywhere (even though I love them so much). But for most Compose UIs, States are the right choice. Below are some simple examples where I quickly refute all* the claims above.</p><h3>Flows have great operators</h3><p>No question. Flow operators are super convenient. They’re also super annoying to get right, require setting coroutine contexts, and remembering all those methods. To each their own, but I much prefer State operators…</p><h4>StateFlow</h4><pre>// StateFlow with a Flow operator<br>private val _color = MutableStateFlow(0xFFFFFF)<br>val color = _color.asStateFlow()<br>val nextColor = color.map {<br>  it + 1<br>}.stateIn(viewModelScope)</pre><h4>State</h4><pre>// State with a State &quot;operator&quot;<br>var color by mutableStateOf(0xFFFFFF)<br>  private set<br>val nextColor<br>  get() = color + 1</pre><p>Am I being cheeky? I’m actually not sure…<br>It wasn’t clear to me if they actually thought there were no operators for States or if they just <em>really</em> wanted the derived value to be computed automatically when the base value was changed. I guess the latter is a reasonable idea but it seems very wasteful to me to stateIn a flow that may never even be used. Sure, we could add a WhileSubscribed to it but that just seems like too much now.</p><p>To me, this is the beauty of Compose States:<br><em>They work just like normal values.</em></p><p>The derived color isn’t memoized, but that’s alright. It’s cheap. For more expensive things, Compose has other methods to handle State memoization and derivation for me.</p><h3>Flows handle process death</h3><p>True, there’s a <a href="https://developer.android.com/topic/libraries/architecture/viewmodel/viewmodel-savedstate#savedstate-stateflow"><em>handy</em> method</a> to get a StateFlow from a SavedStateHandle. But saved states are usually changes a user has made to the UI. In that case, why not save the state there? Then it can be forgotten just as easily when it leaves the composition.</p><h4>StateFlow</h4><pre>class MyViewModel(private val ssh: SavedStateHandle) : ViewModel() {<br>    val greeting = ssh.getStateFlow&lt;String&gt;(&quot;greeting&quot;, &quot;hello&quot;)<br>    fun setGreeting(value: String) {<br>        ssh[&quot;greeting&quot;] = value<br>    }<br>}</pre><h4>State</h4><pre>@Composable<br>fun MyComposable() {<br>  var greeting by rememberSaveable { mutableStateOf(&quot;hello&quot;) }<br>  Button(onClick = { greeting = &quot;goodbye&quot; }) {}<br>}</pre><p>A method like that for StateFlows could be made for Compose States and added to (or extended from) the SavedStateHandle just the same.<br>In fact, this functionality is <a href="https://developer.android.com/topic/libraries/architecture/viewmodel/viewmodel-savedstate#savedstate-compose-state">currently available as experimental</a>.</p><h3>Flows win at ViewModel reusability</h3><p>Yeah, I guess so. If you need a generic observable value exposed from your ViewModel for reuse in a <em>different</em> UI framework (i.e. not Compose), then Flows are pretty nice. However, if that’s actually a requirement, it’s not that hard to package up a State as a Flow for that using <a href="https://developer.android.com/develop/ui/compose/side-effects#snapshotFlow">snapshotFlow</a>.</p><h3>Flows handle changing values</h3><p>Yes, but we’re talking about UI <em>state</em> and <em>State</em>Flows, specifically.<br>Why would we care about the interim values? If we do need to buffer values and handle of a stream of values, then States don’t fit the bill.<br><em>StateFlows don’t either.<br></em>You need a trusty ol’ regular Flow with back-pressure to reliably do that!</p><h3>States are always mutable!</h3><p><em>No?</em> Sure, if you leave a State a State (i.e. don’t delegate it) and your users nefariously cast it to a MutableState then, yeah:</p><p>States are <em>technically</em> always mutable.</p><p>But at that point, we can say the same of Kotlin’s List, as well.</p><pre>  val a = mutableListOf(1,2)<br>  val b = a.toList()<br>  val c = (b as MutableList&lt;Int&gt;)<br>  c.add(3)<br>  println(a)<br>  println(b)<br>  println(c)</pre><p>Can you guess what the above prints?</p><pre>[1, 2]<br>[1, 2, 3]<br>[1, 2, 3]</pre><p>However, if we do delegate our States (or our users aren’t trying to mess with us), then, no, States aren’t always mutable. In fact, they become the most basic and easy to understand building blocks in the language.<br><em>They’re just normal values.</em></p><pre>var a by mutableStateOf(1)<br>  private set</pre><p>In this example, a behaves just like a regular Int and can’t be modified outside of our class. If we want to pass it around:</p><pre>var a by mutableStateOf(1)<br>fun foo(bar: Int) {}<br>foo(a)</pre><p>Inside of the foo function, bar is a normal Int value and behaves like it; it can’t be modified at all.</p><h3>States have an affinity for their thread</h3><p>This one could definitely get you if you’re not aware of the State snapshot semantics. Modifying states from different threads or at the wrong time can land you in trouble. However, it’s not something I’ve encountered. States should stay close to your UI or ViewModel and not be passed around or involved in complex backgrounded task schemes. Coming from Android Views, it wasn’t difficult for me to completely avoid this issue without even thinking about it.</p><p>In my opinion, the example accompanying this complaint was either contrived or their code was poorly organized. They launched a coroutine with a non-Main dispatcher then have to switch back and update the state:</p><pre>private val _result = mutableStateOf(0)<br>val result: State&lt;Int&gt; get() = _result<br>fun performComputation(input: Int) {<br>  viewModelScope.launch(Dispatchers.Default) {<br>    val computedValue = heavyComputation(input)<br>    withContext(Dispatchers.Main) {<br>      _result.value = computedValue<br>    }<br>  }<br>}<br>private fun heavyComputation(input: Int): Int {<br>  // a computation-intensive task<br>}</pre><p>I think my design would differ a bit.<br>Things are simpler and oddity-free;<br>we just do our expensive work in the appropriate context.</p><pre>var result by mutableStateOf(0)<br>  private set<br>fun performComputation(input: Int) {<br>  viewModelScope.launch {<br>    result = heavyComputation(input)<br>  }<br>}<br>private suspend fun heavyComputation(input: Int): Int {<br>  withContext(Dispatchers.Default) {<br>    // a computation-intensive task<br>  }<br>}</pre><h3>Summary</h3><p>I’ve shown that the reasons to <em>always</em> prefer StateFlows over States don’t hold much water. There is some truth to all of them so I’ll reiterate:</p><p>You should evaluate your needs and make the right choice for you.</p><p>As for me, I think I’ll prefer the simpler and made-for-Compose States in my Compose UIs. With Kotlin and property delegation, the sky is the limit for creating easy-to-use APIs and Flows are just <em>too</em> versatile and <em>too</em> powerful to hassle with in my UIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd13554a57f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Dipxel Perfect]]></title>
            <link>https://wesalvaro.medium.com/android-dipxel-perfect-dcf7f96c579e?source=rss-49acf35f81ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcf7f96c579e</guid>
            <category><![CDATA[figma]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Wes Alvaro]]></dc:creator>
            <pubDate>Wed, 06 Dec 2023 07:52:35 GMT</pubDate>
            <atom:updated>2023-12-06T07:52:35.079Z</atom:updated>
            <content:encoded><![CDATA[<p>The Android DP unit is deceivingly simple.<br>In the most basic case, 1DP = 1PX.</p><p>Case closed, right?<br>Hardly…</p><h3>First, what is a DP?</h3><p>DP or “dip”s are density-independent pixels. This allows for designs to be written once but look great on a variety of different devices. “Density” here refers to the density of the pixels in the physical display.</p><p>Two devices with the same physical screen size may have drastically different pixel densities (lower-end phones usually have lower-end pixel densities). If we specified UI elements in terms of pixels, the layouts would end up looking much different on the devices even though they “should” look the same to the user due to them having the same physical size.</p><p>Pixel density itself has a physical range with the “default” being <strong>160ppi </strong>(or pixel-per-inch) and then going upwards of 400-500ppi! Using dips is really just a way to convert pixels into a physical size so that UIs look the same no matter what density your device has.</p><h3>Let’s use the Pixel 3 as an example.</h3><p>Below is a screenshot of the Pixel 3 with its original 440ppi and 1080⨉2160 resolution screen; 1dp is equal to 2.75 pixels.</p><figure><img alt="Screenshot of text demonstrating 440ppi screen." src="https://cdn-images-1.medium.com/max/1024/1*1X7Kz7x2u0l7hEaXqEAlAA.png" /></figure><p>And here is the same device but I’ve altered its pixel density in the Android Window Manager to a paltry 160ppi where 1dp is equal to 1 pixel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgPLMXZ5_24a01XYwe1PBA.png" /></figure><p>Strange! Now it looks “higher resolution” and the bottom bar changed to an launcher tray?!</p><p>It’s the same resolution, of course, but now we’re essentially just rendering the text at a smaller size. If we wanted to, we could get the text size back to its original size by multiplying our font size by 2.75.</p><p>The launcher tray appears because Android layouts should always be responsive to the display size of any device. In this case, at 160ppi and a resolution of 1080⨉2160, that <em>should</em> equate to a physical display size of 6.75&quot;⨉13.5&quot; which would be a tablet! However, we’re still working with the actual physical display size of the Pixel: 2.7&quot;⨉4.8&quot; so the launcher is all but unusable.</p><h3>The math</h3><p>Converting between pixels and dips is easy:</p><blockquote>px = dp * (ppi / 160)</blockquote><p>And the reverse is just as simple, solved for dp:</p><blockquote>dp = px * (160 / ppi)</blockquote><p><a href="https://developer.android.com/training/multiscreen/screendensities">Android classifies its devices by their density</a> with <em>mdpi</em> being the baseline. Application layouts and resources may change depending on device’s classification. Our Pixel 3 falls in between the <em>xhdpi</em> and <em>xxhdpi</em> densities:</p><blockquote>ldpi Resources for low-density (ldpi) screens (~120 dpi).<br>mdpi Resources for medium-density (mdpi) screens (~160 dpi).<br>hdpi Resources for high-density (hdpi) screens (~240 dpi).<br>xhdpi Resources for extra-high-density (xhdpi) screens (~320 dpi).<br>xxhdpi Resources for extra-extra-high-density (xxhdpi) screens (~480 dpi).<br>xxxhdpi Resources for extra-extra-extra-high-density (xxxhdpi) uses (~640 dpi).</blockquote><h3>For Designers</h3><p>Designers spend a lot of time crafting pixel perfect UI layouts. But engineers can’t build layouts in pixels because of the differences in densities that we’ve just talked about. So how can designers and engineers get along? <a href="https://m2.material.io/design/layout/pixel-density.html">The Material site has information on pixel density</a> but no details on how to apply that when designing.</p><h4>Figma</h4><p>Sadly, <a href="https://forum.figma.com/t/android-developers-dp-vs-px/7143">it seems Figma has no way to specify anything about pixel density</a>. 1 pixel is always “1dp” in Figma. To make matters worse, features like font padding can further distort text alignments from mock to implementation. A mock using a different resolution from a test device can also make things hard to compare and “eyeballing” is a pain.</p><p>Since Figma has no pixel density option, we have to sync up the sizes.</p><p><em>Remember:</em> Dips never change, nor do pixels.<br>It’s just the <em>density</em> of the pixels within the <em>physical</em> display that changes.</p><p>Using our Pixel 3 as an example, we can <strong>make our Figma mock match the size of the device’s screen</strong> (1080⨉2160) and then 1dp in our mocks is 2.75 pixels. So for the common min-touch target size of 48dp, that would be 132 pixels square.</p><p>But since engineers don’t design in pixels, and nobody wants to multiply things by 2.75, it might be better if the units on screen were dips, wouldn’t it? In that case, we’d need to scale <em>down</em> our mock size to 392⨉785 pixels (or 1080/2.75⨉2160/2.75) for our Pixel 3. At this size, 1dp is 1 pixel and is only off by 0.5 pixels in the horizontal.</p><p><em>Alternatively,</em> we can <strong>set the screen properties of the device</strong> as we did earlier for the two screenshots. With developer access, this is quite simple. There are only two commands we need to know:</p><ul><li>adb shell wm size</li><li>adb shell wm density</li></ul><p>Running these commands with our Pixel 3 connected, we’ll get the current settings of the device:</p><ul><li>adb shell wm size <br>Physical size: <strong>1080x2160</strong></li><li>adb shell wm density<br>Physical density: <strong>440</strong></li></ul><p>To change these values, just add them to the command. For example, if we wanted to change our Pixel 3 to a smaller size screen with 1dp equal to 1 pixel:</p><ul><li>adb shell wm size <strong>392x785</strong></li><li>adb shell wm density <strong>160</strong></li></ul><p>Now our Pixel 3 is an <em>mdpi</em> device!</p><figure><img alt="Pixel 3 display scaled down to mdpi." src="https://cdn-images-1.medium.com/max/392/1*h_ZuIMirS27rGMrb1FlrMw.png" /></figure><p>You can clearly see the screenshot size is smaller and the text, while physically the same size on screen, is not as clear.</p><p>Feel free to use whatever values make sense to you when designing and when validating that your designs were implemented correctly. By using consistent values, whatever you choose, you will be able to directly overlay screenshots from the device with your mocks exactly!</p><h3>As for SP…</h3><p>The only real thing to note here is that these are used for fonts and may be scaled separately from DP for people that might need a larger font only. The default on most devices is a scaling factor of 1 where 1sp equals 1dp.</p><p>Getting and changing the value is also easily done with ADB:</p><ul><li>adb shell settings <strong>get</strong> system font_scale</li><li>adb shell settings <strong>put</strong> system font_scale <strong>1.0</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcf7f96c579e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mockito’s sinister silent stub secret]]></title>
            <link>https://wesalvaro.medium.com/mockitos-sinister-silent-stub-secret-eeef5e5f6ec1?source=rss-49acf35f81ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/eeef5e5f6ec1</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Wes Alvaro]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 04:51:45 GMT</pubDate>
            <atom:updated>2023-03-02T05:23:23.883Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>tl;dr:</strong> Do <strong><em>not</em></strong> start your stubbing chain with Mockito’s when.</p><p>Let’s take a look at this simple test. So simple it has to pass:</p><pre>@Test<br>fun work_isTheAnswer() {<br>  whenever(foo.work()) doReturn 42<br><br>  assertThat(foo.work()).isEqualTo(42)<br>}</pre><p>But it <em>doesn’t</em>… it produces an off-by-one error?</p><pre>1) work_isTheAnswer<br>value of: work()<br>expected: 42<br>but was : 43<br> at com.testing.SomeTest.work_isTheAnswer</pre><h3>What happened?</h3><p>Mockito didn’t throw an error…<br>So it definitely stubbed our method to return 42, right? <strong><em>Yes!</em></strong></p><h4>Huh?</h4><p>Let’s take a look at the rest of the test setup:</p><pre>private val worker = mock&lt;Worker&gt;()<br>private val foo = Foo(worker)</pre><p>That’s not good, foo isn’t a mock.</p><h4>How did Mockito mock our method?</h4><p>Let’s take a look at our Foo class definition:</p><pre>class Foo(private val worker: Worker) {<br>  open fun work(): Int = worker.dig() + 1<br>}</pre><blockquote>That’s a weird setup…<br>Admittedly, this is a bit of a weird setup but equivalent code can be easily found in the wild. This sample is an extremely distilled version of code I reviewed.</blockquote><p>When we call when/whenever, Mockito actually has no idea what the mock object is. It simply looks for the most recent method call on <em>any</em> mock object and assumes its result was the argument to when.</p><p>In this example, we’ve mocked out the dependency worker of Foo for simpler testing but we ended up shooting ourselves in the foot. It’s not the work method of Foo that gets stubbed since it’s not a mock, but the dig method of its worker argument since that’s the most recent method called on a mock object.</p><p>Now the 43 result makes more sense:</p><ul><li>worker.dig() now returns 42</li><li>foo.work() now returns 42 + 1 = 43</li></ul><p>Yikes. 😬</p><h3>How do I avoid this?</h3><p>This pitfall isn’t super common, but it’s extremely confusing when you get stuck in it as we get no errors and in the worse case the test actually <em>passes</em>.</p><p>The good news is that avoiding this problem is super easy!</p><p>If you’re like me, you’ve always used when/whenever to start your stubbing chains as in our example using thenReturn/doReturn afterward. It always just seemed more logical than that odd alternative of starting chains with doReturn. I never liked having to doAnswer because it seemed so out of place.</p><p><strong>This issue has changed my opinion on this.<br></strong>I now would recommend we all change our practice and normalize always starting chains with doReturn/doAnswer/doThrow. On top of completely eliminating this pitfall, it has the added benefit of consistency.</p><h4>How does that help?</h4><p>The format totally changes when we start our chains this way:</p><pre>doReturn(42).whenever(foo).work()</pre><p>The important difference is our argument to whenever:<br>It’s foo and foo is <em>not</em> a mock.<br>Mockito can now check it and is <em>not</em> happy:</p><pre>org.mockito.exceptions.misusing.MissingMethodInvocationException: <br>when() requires an argument which has to be &#39;a method call on a mock&#39;.<br>For example:<br>    when(mock.getArticles()).thenReturn(articles);<br><br>Also, this error might show up because:<br>1. you stub either of: final/private/equals()/hashCode() methods.<br>   Those methods *cannot* be stubbed/verified.<br>   Mocking methods declared on non-public parent classes is not supported.<br>2. inside when() you don&#39;t call method on mock but on some other object.</pre><h4>What about in MockitoKotlin?</h4><p>Yeah, I don’t use regular Mockito syntax, either.<br>I much prefer the stubbing style of MockitoKotlin in Kotlin:</p><pre>val worker = mock&lt;Worker&gt; {<br>  on { work() } doReturn 42<br>}<br>// or when deferring your stubbing:<br>worker.stub {<br>  on { work() } doReturn 42<br>}</pre><p>It has two benefits:</p><ol><li>Being able to nicely and fully stub mocks as we define them.</li><li>In the case of deferred stubbing: Consistency with #1.</li></ol><p>I’m sad to report that the stub extension method does <strong><em>not</em></strong> currently check that its receiver is a mock. But I’m happy to report that I have opened <a href="https://github.com/mockito/mockito-kotlin/pull/479">PR#479</a> to add this check. After it’s merged, we will be able to safely use the syntax we love.</p><h3>Appendix</h3><p>And now, a message from a few things that <em>seem</em> like they would help…</p><h4>Using final methods doesn’t directly help</h4><p>You should never be using open methods. <strong>Period.</strong><br>If you think you need an open method, what you actually need is an abstract class with abstract methods or an interface with … normal methods.</p><p>In our example, the work method should not have been open. But even if we close our method, Mockito has no way of knowing if our method call was on a final method, so nothing changes. You may implement (as we have) an AndroidLint check that can detect this, though.</p><p>Even without a check, if we instill good practices around closing our classes, we’re going to be much less likely to make mistakes like this.</p><h4>Using different return values is luck</h4><p>The error in our example would not have occurred if work and dig had different return values. We can’t rely on that; it just means this error is rarer and more confusing when it occurs.</p><p>In the test that prompted me to write this, it was a couple boolean methods (instead of integers) that were evaluating flags. Pretty important stuff, and pretty standard to use booleans in that case.</p><p>If you do hit this pitfall but your true mock method returns something different than the one you passed to when/whenever, then you’ll get an error like this from Mockito:</p><pre>Integer cannot be returned by foo()<br>bar() should return boolean<br>***<br>If you&#39;re unsure why you&#39;re getting above error read on.<br>Due to the nature of the syntax above problem might occur because:<br>1. This exception *might* occur in wrongly written multi-threaded tests.<br>   Please refer to Mockito FAQ on limitations of concurrency testing.<br>2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - <br>   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.</pre><p>Still a confusing sight, but at least Mockito doesn’t do something wild. Also note #2 in the output. Even Mockito acknowledges the danger of this setup.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eeef5e5f6ec1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shipping gear around Japan]]></title>
            <link>https://wesalvaro.medium.com/shipping-gear-around-japan-ce283f12aa96?source=rss-49acf35f81ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce283f12aa96</guid>
            <category><![CDATA[scuba-diving]]></category>
            <category><![CDATA[shipping]]></category>
            <category><![CDATA[japan]]></category>
            <category><![CDATA[life-hacking]]></category>
            <category><![CDATA[japanese]]></category>
            <dc:creator><![CDATA[Wes Alvaro]]></dc:creator>
            <pubDate>Sat, 15 Oct 2022 18:38:16 GMT</pubDate>
            <atom:updated>2022-10-15T19:06:55.605Z</atom:updated>
            <content:encoded><![CDATA[<p>I have two sports I enjoy: scuba diving and snow boarding. The problem is that renting equipment is expensive and rental equipment is… never great and only sometimes decent. Having your own gear makes a world of difference, especially for diving, but owning your gear comes with its own challenges: storing, maintenance, and <em>shipping</em>…</p><p>Shipping domestically around Japan is a great deal and takes a load off of you (<em>literally</em>) when it comes time to travel.</p><p>Obviously, you can ship your equipment with you on the airplane but that means you’ll need to lug it to and from the airport. JAL does offer a deliver service (<a href="https://www.jal.co.jp/jp/ja/inter/option/empty/">JAL手ぶら宅配</a>, literally “empty handed” delivery service) but since I’m usually flying on an LCC (Low Cost Carrier) that’s not an option. When flying on an LCC, they have a total baggage weight limit around 7Kg with a checked bag starting at <a href="https://www.flypeach.com/en/lm/fares/fees_and_charges#domestic">~2,000yen and a 20Kg limit</a>. On the other hand, JAL has essentially no carry-on limit and <a href="https://www.jal.co.jp/jp/en/dom/baggage/checked/">one free checked bag up to 20Kg</a> (each Kg over is 400yen).</p><p><em>Shipping is actually cheaper and (in my opinion) much more convenient!</em></p><p>While I do trust airlines with my luggage in Japan, I also really like the fast and cheap service provided by shipping companies here. Having my stuff picked up from my apartment and dropped off at my hotel just makes it so much easier to relax while travelling. The downside is that shipping is obviously slower than checking a bag, so we must allow time for transit. Shipping in Japan is very fast and reliable but issues may arise. They can also hold your parcel for around a week (at no charge) so shipping earlier shouldn’t be a problem unless you procrastinate like I do.</p><h3>Crash course on shipping in Japan</h3><p>Shipping domestically in Japan is very fast (usually 1-3 days) and relatively cheap with generally great service/high-touch support. The price varies based on the size <em>and</em> weight of the items just like anywhere else.</p><p>You can specify the day <em>and</em> time window (8–noon and then 2 hour windows for the after noon until around 9) for a delivery and <em>they actually show up</em>. As mentioned, they can also hold delivery for around a week.</p><p>The weight is in <strong>kilograms</strong> and the size is measured in <strong>centimeters</strong> where you add the height, width, and length together for one number that gets bucketed, rounding up. For example:<br>a box that is 20cm <strong>× </strong>35cm <strong>× </strong>30cm = 20 + 35 + 30 = 85 = 100 size</p><h3>Shipping Snow Equipment</h3><p>By far the best deal (and best documented process) is shipping snow (or golf) equipment. With all the mountains in Japan, skiing is a pretty popular activity. The major delivery companies have streamlined the process (and the prices) to make your ski trip much less hectic. There’s nothing worse than trying to carry heavy, awkward snow gear onto a packed Tokyo train.</p><p>The two services I have used and would recommend are:</p><ul><li><a href="https://www.kuronekoyamato.co.jp/ytc/en/send/services/ski/">Ski Ta-Q-Bin</a> 「スキー宅急便」</li><li><a href="https://www.post.japanpost.jp/service/you_pack/ski/index_en.html">Ski Yu-Pack</a> 「スキーゆうパック」</li></ul><p>These services are run by the two major carriers Yamato (Kuro Neko) and JP Post, respectively. Because of how much content they have <em>in English</em> for these services, <strong>I’ll be brief.</strong></p><p>Both will deliver your stuff to the resort and return it to your apartment no problem. Both offer pick-up/drop-off locations (e.g. convenience stores) but you’ll get a discount bringing it directly to the distribution center/post office. The details and discounts are nicely documented on their sites <em>in English!</em></p><p>The prices are pretty comparable between the two companies and vary mostly on how much you want to ship, factoring in convenience. In my case, I have a snowboard bag in which I put my snowboard, boots, as well as all my winter gear. It ships one-way via Yamato for 2,060yen and via JP Post 2,070yen. So when I head to the mountains, I only need to dress warm and carry a backpack.</p><p>No more encumbered, crowded-city-navigating stress.</p><h3>Shipping Scuba Diving Equipment</h3><p>Shipping diving gear is, for some reason, much more obscure and less documented even though the sport seems pretty popular in Japan. There are more dive spots than you can shake a stick at but I don’t want to have to lug all my heavy stuff to them.</p><p>Before we even talk about prices and services, we have to talk (a lot) about what you <em>can</em> and <strong>cannot</strong> ship. Shippers are very particular about what is inside the parcels. This determines if the parcel gets on a <em>plane</em> (for impossibly fast delivery times) or on a <em>boat</em> (…in which case you’ll be needing rentals). Unlike the obviously inert contents for skiing, diving equipment <em>can</em> contain dangerous (to plane) items.</p><h4>🙅‍♂️ The following items are on the no-fly list:</h4><ul><li>Batteries「電池」</li><li>Gas「ガズ」</li><li>Tanks「タンク・ボンベ」</li></ul><p><strong>If they find these in your luggage, </strong>it’ll get put on a boat.<br><em>You don’t want that.</em></p><p>It’s imperitive that we describe the contents of our luggage accurately and completely. Depending on where you are shipping from, your counter agent will be more or less familiar with the items/terminology that comes with diving. Whenever I ship from my local Tokyo post office, I always get the third-degree. My form is never filled to their satisfaction but I don’t mind since I know they’re just trying to help me get my stuff to arrive without a hitch. When I leave, they always thank me and apologize for it taking so long.</p><p>The last time I went to drop off my stuff, I had already filled in the list of items copied from a pre-printed slip I got from a dive center in Yonaguni:</p><blockquote>ウェットスーツ・マスク・フィン ・BCジャケット・レギュレーター <br>（ボンベなし、タンクなし、ガスなし、電池なし）</blockquote><p>Admittedly, this wasn’t complete, but I thought it covered the stuff that <em>mattered</em> and I didn’t really have any extra space in the box. I was wrong. They actually broke out a visual guide with all kinds of information and had me go through it and confirm that none of the <em>bad</em> stuff was in there. After the (~15min) “interrogation”, the contents section of my shipping form overflowed (into another box, 品名追加) with all of the following:</p><blockquote>ウェットスーツ wetsuit<br>マスク mask<br>フィン fin<br>BCジャケット BC jacket<br>レギュレーター regulator<br>（ボンベなし、タンクなし、ガスなし、電池なし）<br>(no tanks, no tanks, no gas, no batteries)<br>ブーツ boots<br>メッシュバッグ mesh bag<br>服 clothing<br>食品 food<br>レンチ wrenches<br>ライト（リチウム電池なし） torch (no lithium batteries)<br>シグナルフロート（非ガス式）signal float (non-gas type)</blockquote><figure><img alt="Photo of my completed shipping item list." src="https://cdn-images-1.medium.com/max/1024/1*X0hx20Uc3D5sIsrA1EAZ5A.jpeg" /></figure><p>Your item list will obviously differ based on what you have in your luggage. But don’t sweat it. They’ll help you but make sure you don’t have any of the <em>bad</em> items inside. It’ll help to know the vocabulary and be able to clearly tell them they’re absent if they ask.</p><h4>So what other diving items are there?</h4><p>They graciously let me photograph their behind-the-counter guide so I’ve included it below. In the following photos are diving items numbered 1–27, their genre (ジャンレ), <strong>name for the shipping label</strong> (ラベルに記載された品名), commentary (解説), aviation-status (航空搭載可否), and supplementary information (補足). All the normal items are aviation-friendly (noted with the circle, maru, ○), a few are not (noted with the x, batsu, ×). The ones of particular interest are the ones that may or may not be allowed (noted with the triangle, san-kaku, △).</p><figure><img alt="Illustration of scuba diver and various basic equipment called out." src="https://cdn-images-1.medium.com/max/1024/1*ZdeXu6wA4MxjXxMWo0Z26Q.jpeg" /></figure><p>The first page with items numbered 1–10 has all the basic environmental protection items, as well as snorkel, fin, and mesh bag. They’re good to fly. The supplement on this page has a nice little illustration that covers these items and a few that spill onto page 2.</p><figure><img alt="Details on things like fins, regulators, and gauges." src="https://cdn-images-1.medium.com/max/1024/1*Jn0YUJPw3Lax4m8N7CssPg.jpeg" /></figure><p>Page 2 has three △ items: tanks, BCDs, and console gauges.</p><p>Whether filled or not, they won’t accept tanks (also called bonbe, ボンベ) on airplanes because who knows if they’ll explode. Understandable. But what’s weird is that they group アクアラング (the brand Aqualung™) into the same category. I guess it’s popular here? That’s why the △ and not an ×; they’ll inspect it to see if it’s just an Aqualung wetsuit or something. I’d just avoid writing that brand name on the form; you don’t need brand names...</p><p>As for BCDs, they’re fine as long as you don’t have any attached tanks for inflation but I’ve never seen one of those in the wild. If your BCD is only filled via inflator hose or your own lungs, you should write: <br>BCD（ボンベ、ガス類なし）<br>BCD (no tanks or gas)</p><p>I’ve never met a diver that uses a console gauge but I know they do exist. If you’re one of them, it can’t fly unless the battery is removed from the console.（電池なし）</p><p>The other two items are both regulators (they list the octopus オクトパスseparately) and they’re obviously fine to fly. If you have the carry on space (or more likely weight for an LCC), you might want to use that instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ArLj_Nf3NL0qILJ17GAObQ.jpeg" /></figure><p>Page 3 as mostly ○ items: inflator hose, weights, and weight belts.</p><p>Also on this page is the △ diving computer. As long as you have removed the battery, it’s are fine to fly.（電池なし）<br>(But I always bring mine with me on my wrist.)</p><figure><img alt="Details on cameras and accessories." src="https://cdn-images-1.medium.com/max/1024/1*-mCT3TOBt7_oTj3TxW5PNA.jpeg" /></figure><p>Page 4 has camera related items that, as long as you’ve removed the batteries, should be fine to fly.（電池なし）</p><figure><img alt="Details on BC alarms, DSMBs, rebreathers, and tanks." src="https://cdn-images-1.medium.com/max/1024/1*h0FP5aGR1hJPp-hR5SGlTQ.jpeg" /></figure><p>The last page has the only two absolutely never × items: rebreathers and small, mouth held tanks (SCORKLs). Sorry, they have to take a boat when shipping… Similarly with the △ DSMB (signal float), it’s fine as long as there are no tanks or gas in there with it.（ボンベ、ガス類なし）</p><h4>Sorted! So how do I actually ship it?</h4><p>Sadly, there is no special diving service available like there is for skiing and golfing… I just put all my gear in a rolling luggage and ship it <a href="https://www.post.japanpost.jp/service/you_pack/index_en.html">Yu-Pack from JP Post</a>. I can fit all my gear into a large (160cm) roller luggage and ship it one way from Tokyo to Okinawa for 2,540yen. The same luggage sent via <a href="https://www.kuronekoyamato.co.jp/ytc/en/send/services/takkyubin/">Ta-Q-Bin from Yamato</a> would cost around 4,160yen.</p><p>With the <strong>Yu-Pack</strong> service, you can drop it off at some other locations (like a Lawson) but they’ll only accept it there if it weighs less than 20Kg.<br>The maximum weight is 25Kg even if you take it to the post office.<br>The maximum size is 170cm (3,060yen).</p><p>With <strong>Ta-Q-Bin</strong>, the maximum weight is 30Kg and the maximum size is 200cm (5,260yen). And they do offer some discounts depending on where you drop it off (but only up to 180cm can be dropped off at a convenience store).</p><h3>Shipping Tips</h3><p>Just a few tips I’ve picked up...</p><h4>Shipping to a Post Office</h4><p>Instead of shipping to an address, you can <a href="https://www.post.japanpost.jp/service/sisho/index.html">ship to a post office</a> and they’ll let you pick it up at the window. This is handy when you’re not sure if you’ll be around to meet a delivery window and don’t have a problem popping over to the Post Office to collect your stuff.</p><p>When filling out the shipping slip, the “to” section is in this format:</p><blockquote>郵便番号<br>おところ１<br>おところ２<br>おところ３<br>おなまえ<br>でんわ</blockquote><p>When shipping to a post office, we’ll use its post code and <em>most</em> of its address for line 1. Instead of writing the full address, swap out the street address for the name of the post office plus 「留」. On line 2, write your post code and street address with your building name &amp; apartment number on line 3. Draw square brackets around your address. Yes, literally surround your address with [ ]. Finally, write your name and telephone number as normal.</p><p>If we’re shipping to the Onna Post Office in Okinawa, it would look like:</p><blockquote>９０４−０４１１<br>沖縄県国頭郡恩納村＿恩納郵便局留＿＿＿＿＿＿＿＿<br>⎡〒１２３ー４５６７東京都渋谷区渋谷１−２−３⎤＿<br>⎣東渋谷ナイスパラスプレースビル１２３室＿＿⎦＿<br>桃太郎＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿様<br>０３０−１２３４−５６７８</blockquote><h4>Don’t write your address twice</h4><p>In America, a return address isn’t always required and if it is, I just fill in my address again. One time when shipping my stuff home from skiing, I noticed other slips were simply filled out with the return address as 「同上」(dōjō) which translates to “same as above” or “ditto” in the same way you might have used “” to ditto something on a form. I still fill in my phone number a second time because that’s never a bad idea but not writing my address again is a nice time saver.</p><h4>You don’t need to write in Japanese</h4><p>While I <strong>highly</strong> suggest you put learning to write your address in Japanese at the top of your to-do list, it’s not <em>necessary </em>when it comes to shipping. In my experience, it makes things much smoother if you do write in Japanese <em>(especially for the contents of your parcel) </em>but it’s not absolutely necessary. For the kanji you don’t remember, the staff always seems happy to help if you ask… in Japanese. 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce283f12aa96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Annotations, how do they work?]]></title>
            <link>https://wesalvaro.medium.com/annotations-how-do-they-work-2b25b83852a?source=rss-49acf35f81ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b25b83852a</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dagger]]></category>
            <category><![CDATA[junit]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[interoperability]]></category>
            <dc:creator><![CDATA[Wes Alvaro]]></dc:creator>
            <pubDate>Thu, 06 Oct 2022 09:52:13 GMT</pubDate>
            <atom:updated>2022-10-06T10:17:22.761Z</atom:updated>
            <content:encoded><![CDATA[<p>Annotations are something most if not every Java or Kotlin developer uses but how they work can still be a mystery. I thought I more or less understood them until I started thinking about the Kotlin/Java interop story or Dagger qualifier code generation. How do <em>they</em> work? An exhaustive deep-dive into annotations isn’t necessary but we should shed some light on how they are handled for basic usage.</p><p>We can use some simple Kotlin code and reflection to answer all of our questions with real (if contrived) examples/demonstrations. The base for our experimentation is the following snippet:</p><pre>annotatation class MyAnnotation</pre><pre>@MyAnnotation<br>val value = Unit</pre><pre>println(::value.annotations)</pre><h3>Retention</h3><p><a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.6.4.2">JLS§9.6.4.2</a> | <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.annotation/-retention/">Kotlin “Spec”</a></p><p>Retention may seem intimidating but is probably the most straight-forward concept we’ll talk about so lets get it out of the way. The more complicated part comes later when we combine annotations with annotation processors.</p><p>There are three “levels” of retention:</p><ul><li>Source</li><li>Binary</li><li>Runtime</li></ul><p>Annotations retained only in the source can only be inspected by <em>source</em> processors, the compiler discards them and they definitely don’t appear for reflection at runtime.</p><p>Binary annotations can be used by tools such as Proguard that need to modify the <em>binary</em>. The Keep annotation is an example of an important binary retained annotation as we’ll never need to reflect on but we must access in the binary.</p><p>Runtime annotations are available for all purposes, even <em>reflection</em>. On Android, we don’t do so much reflection … do we need these?</p><p>By default (if we omit the Retention annotation),<br>Java usesBinary retention and Kotlin usesRuntime. 😒</p><h3>Target</h3><p><a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.6.4.1">JLS</a><a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.6.4.2">§9.6.4.</a>1 | <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.annotation/-target/">Kotlin “Spec”</a></p><p>In general, the Target annotation is fairly self-explanatory; it defines what are the allowed targets of our annotation class. In Java, these options come from <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/annotation/ElementType.html">ElementType</a> and in Kotlin, they come from the <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.annotation/-annotation-target/">AnnotationTarget</a>.</p><p>It’s important to note that Kotlin has quite a few more options for its targets. They are a proper superset of those in Java. This is because Kotlin has quite a few more places to put annotations and interop with Java makes this a bit confusing (and the motivation for this story/investigation).</p><h4>What if the Target annotation is omitted?</h4><p>In Java, the spec says that it “is applicable in all declaration contexts except type parameter declarations, and in no type contexts.” And in general, we shouldn’t concern ourselves with these two excluded contexts as they aren’t a common use case (if you know, you know).</p><p>In Kotlin, the documentation says that it “is applicable to the following elements: CLASS, PROPERTY, FIELD, LOCAL_VARIABLE, VALUE_PARAMETER, CONSTRUCTOR, FUNCTION, PROPERTY_GETTER, PROPERTY_SETTER.” That means that it is applicable to all of the targets except for: ANNOTATION_CLASS, TYPE_PARAMATER, TYPE, EXPRESSION, FILE, and TYPEALIAS. That’s more-or-less consistent with Java considering the extra options.</p><h3>Use-Site Target Specifiers</h3><p><a href="https://kotlinlang.org/docs/annotations.html#annotation-use-site-targets">Docs</a></p><p>This is something we <em>only</em> have to think about in Kotlin. Java has less options/ambiguities with where annotations can be applied, so we don’t need to specify the target when we <em>use</em> an annotation. However what happens when we annotate a constructor parameter/property/field in Kotlin?</p><pre>class MyClass(@MyAnnotation val myValue: Int) </pre><p>Use-site target specifiers to the rescue!</p><p>Using Kotlin for the first time, you might encounter this error when using a TestRule in a JUnit test:</p><pre>Invalid test class &#39;com.example.annotations.ExampleUnitTest&#39;:<br>  1. The @Rule &#39;myRule&#39; must be public.</pre><p>No problem, let’s make our property public… wait… It already is…</p><pre>class ExampleUnitTest {<br>    <em>@Rule </em>val myRule = MyRule()</pre><h4>What gives?</h4><p>A quick look at the generated Java byte code tells us what’s going on:</p><pre>// access flags 0x12<br>private final Lcom/example/annotations/MyRule; myRule<br>@Lorg/junit/Rule;()<br>@Lorg/jetbrains/annotations/NotNull;() // invisible</pre><pre>// access flags 0x11<br>public final getMyRule()Lcom/example/annotations/MyRule;<br>@Lorg/jetbrains/annotations/NotNull;() // invisible</pre><p>Yikes, our @Rule annotated myRule is private! We can see the public getter is not annotated at all. This leads to the error about our invalid test class. We can fix this with the get use-site target:</p><pre>class ExampleUnitTest {<br>    <em>@get:Rule </em>val myRule = MyRule()</pre><p>Now this says that the getter of the field myRule should be annotated, not the private field. The byte code reflects this change and JUnit is happy!</p><pre>// access flags 0x12<br>private final Lcom/example/annotations/MyRule; myRule<br>@Lorg/jetbrains/annotations/NotNull;() // invisible</pre><pre>// access flags 0x11<br>public final getMyRule()Lcom/example/annotations/MyRule;<br>@Lorg/junit/Rule;()<br>@Lorg/jetbrains/annotations/NotNull;() // invisible</pre><p>A use-site get target is the recommendation where I work but there is actually have another option to fix this error… Pause the story now to hazard a guess.</p><p>Using a getter to return a @Rule for a JUnit test is a little weird, wouldn’t you say? Have you ever done that in Java? To be honest, I didn’t even know it was an option. The Java version of our test would use a field but the idiomatic Kotlin uses a property and causes all this confusion. Instead, we could forget about that unnecessary getter and annotate our @Rule property as an @JvmField. Now our private field is public and JUnit is happy!</p><pre>// access flags 0x11<br>public final Lcom/example/annotations/MyRule; myRule<br>@Lorg/junit/Rule;()<br>@Lkotlin/jvm/JvmField;() // invisible<br>@Lorg/jetbrains/annotations/NotNull;() // invisible</pre><h4>What if the use-site target is omitted?</h4><p>If we don’t specify the target when we use an annotation, Kotlin will match the usage with the Target annotation. This doesn’t help in the above situation since the targets of Rule are field and method and <em>both</em> are applicable here. “If there are multiple applicable targets, the first applicable target from the following list is used:”</p><ul><li>param</li><li>property</li><li>field</li></ul><p>So our private field was annotated and not the public getter method.</p><h4>What happens if property is specified as the target?</h4><p>Good question! This is an interesting one as Kotlin says “annotations with this target are not visible to Java”. We can’t use the property use-site target with the Rule annotation (since it specified only fields and methods as possible targets) but we can add it to our custom annotation to see what happens to the byte code:</p><pre>// access flags 0x1A<br>private final static Lkotlin/Unit; value<br>@Lorg/jetbrains/annotations/NotNull;() // invisible</pre><pre>// DEPRECATED<br>// access flags 0x21009<br>public static synthetic getValue$annotations()V<br>@Lcom/example/annotations/MyAnnotation;()</pre><p>Neat. Creating this sythethic method allows Kotlin to access it for the property but it’s inaccessible from Java.</p><h3>Injection</h3><p>Other than the Java Override annotation, annotations for setting up injections may be the second biggest use-case. Three commonly used annotations that come from javax are Inject,Qualifier, and Named. The Inject annotation should be obvious, but maybe Qualifier or Named are new to you.</p><p>With a Qualifier, we can “qualify” provisions for use with Dagger do disambiguate two instances of the same type (e.g. two strings). Doing this is simple; we just slap a Qualifier annotation on our annotation class and voila!</p><pre>@Qualifier<br>annotation class MyQualifier</pre><p>Our dependency injection framework (let’s just assume Dagger) will now leverage our annotation when matching provided/bound values in our graph. For example, the following two strings are distinct in our graph:</p><pre>@Provides<br>@MyQualifier<br>fun getMyQualifiedString() = &quot;Hello world!&quot;<br>@Provides<br>fun getMyUnQualifiedString() = &quot;Goodnight, moon.&quot;</pre><p>(We can re-use our qualifier for any type, not just strings.)</p><p>The Named annotation is just a genericQualifier provided for us to use.</p><p>The Javax documentation of Qualifier says “A qualifier annotation:<br>is annotated with @Qualifier, @Retention(RUNTIME), and typically @Documented.” With Dagger (at least) this isn’t <em>actually</em> necessary; it will happily create our graph with SOURCE retained annotations. While I’m not saying we should do that, it’s likely this is vestigial direction from a Guice (reflection injection) world.</p><h3>Injection Interop</h3><p>Dagger uses Kapt for Kotlin annotation processing of the injection annotations. Because of this, you shouldn’t run into any issues with how the annotation is applied to its target. This means you shouldn’t need to add any use-site target specifiers (e.g.field or param).</p><h3>So, should I worry?</h3><p><strong>No!</strong> Annotations might <em>seem</em> intimidating but I hope this cleared up some questions you might have had about them and help you take command. Knowing the components of these annotation incantations and how they’re used by your tooling lets us more easily understand those cryptic errors.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b25b83852a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FontMetrics for Spanning Text]]></title>
            <link>https://wesalvaro.medium.com/fontmetrics-for-spanning-text-68a27084e739?source=rss-49acf35f81ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/68a27084e739</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Wes Alvaro]]></dc:creator>
            <pubDate>Tue, 17 May 2022 10:28:18 GMT</pubDate>
            <atom:updated>2022-05-17T10:41:29.732Z</atom:updated>
            <content:encoded><![CDATA[<p>Spanned Strings are very powerful in Android. ReplacementSpans are perhaps the most powerful; they allow for inserting images or highlights and combined with a LineHeightSpan, the possibilities for presenting your text are endless.</p><h3>Why isn’t everybody using Spanned Strings?</h3><p>Quite frankly, they’re hard to work with. Nobody wants to do font math when developing a layout but when it comes to laying out text inline, it’s pretty hard to escape.</p><p>In this story, we’ll dive into the various types you’ll see and what kind of font/drawing/painting values we’ll find…</p><h3>Paint</h3><p><a href="https://developer.android.com/reference/android/graphics/Paint">Paint</a> contains everything Android needs to know to draw both paths and text. We can access the FontMetrics contained within the Paint in both Int and Float forms.</p><h3>FontMetrics</h3><p>Inside the <a href="https://developer.android.com/reference/android/graphics/Paint.FontMetrics">FontMetrics</a> object, we’ll find top, bottom, ascent, descent, and leading(/ˈle-diŋ/ not /ˈlē-diŋ/). But what do these values represent? These values <em>never</em> change, are all relative to the baseline, and indicate the various maximum values for our selected font (this means that ascent and top will be negative!). Our font should be rendering most glyphs within the ascent and descent values but top and bottom are the actual height limits on the glyphs. The font’s height is the difference of descent and ascent; the font’s <em>line</em> <em>height</em> can be found by adding the leading to the difference of top and bottom. None of these values indicate the <em>size of our actual text</em>; remember:FontMetrics are always constant for a given Paint. We’ll talk about how to measure the actual text later.</p><h3>ReplacementSpan</h3><p>A ReplacementSpan will have the Paint and FontMetrics provided to its overridden methods:</p><pre>fun getSize(<br>  <em>paint</em>: Paint,<br>  <em>text</em>: CharSequence?,<br>  <em>start</em>: Int,<br>  <em>end</em>: Int,<br>  <em>fm</em>: Paint.FontMetricsInt?,<br>)<br>fun draw(<br>  <em>canvas</em>: Canvas,<br>  <em>text</em>: CharSequence,<br>  <em>start</em>: Int,<br>  <em>end</em>: Int,<br>  <em>x</em>: Float,<br>  <em>top</em>: Int,<br>  <em>y</em>: Int,<br>  <em>bottom</em>: Int,<br>  <em>paint</em>: Paint, // contains FontMetrics and FontMetricsInt<br>)</pre><p>In these methods, we can see that we have some new (and some duplicated?) values coming in: start, end, x, top, y, and bottom… First, the easy ones: start and end are the indices into text that we are replacing. The position (x, y) is the starting point for our text (where y is the baseline) in the canvas. The values top and bottom aren’t duplicated, they provide us vertical bounds in which we should draw our replacement span in the canvas. top and bottom will clip for the first and last lines of a TextView, respectively. For other lines, we can draw anywhere we like in the TextView Canvas (but we probably shouldn’t).</p><p>While not strictly required, it’s probably a good idea for your ReplacementSpan to also implement LineHeightSpan. If not, you may find that your ReplacementSpan never appears. This can happen in cases where there is no other content to influence the line height, so the line height of your TextView is zero unless you implement LineHeightSpan. We don’t actually have to do anything in the overridden chooseHeight method, though. It just signals to the Layout that we want some height.</p><h3>Visualization</h3><p>Whew, that was a lot. Maybe a diagram will help?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*rK2Ae2opjRveD2m6S9ny9w.png" /><figcaption>Visualization of the FontMetrics and Draw arguments for a ReplacementSpan.</figcaption></figure><p>Maybe a diagram is worse…<br>The “top” values are drawn <em>below</em> their value line. The “bottom” values are drawn <em>above</em> their value line. Confusing, but this is to prevent clipping.</p><p>In the above screenshot, we have a Spanned String split into three lines where each line has a debugging ReplacementSpan set on it. The text content is Top\nMid\nBot and there is an extra 20px of line height added. This setup allows us to follow along as the values change for each line.</p><p>Let’s break down the interesting parts.</p><ul><li>“A Top Draw” and “A Top FM” are the same (red + blue = purple).</li><li>“A Bottom Draw” and “A Bottom FM” differ by our extra 20px line height.</li><li>The same is true for the “B” line (I see purple again).</li><li>But oddly, the same is not true for the “C” line…</li></ul><p>“C Ascent” and “C Top Draw” happen to line up, but “C Top FM” is a bit further up. Weird. Other than that, I think we can agree that the values are more or less what we would expect. Now the only thing left is drawing our replacement where we want it.</p><h3>The Actual Values</h3><p>The values are displayed visually but we can also log them out to see the numbers underneath. Remember: The actual canvas locations are provided by the ReplacementSpan and the FontMetrics only provide us <em>relative</em> values to those for the specified font. This is why we have to add in y (our baseline) to the FontMetrics values.</p><p>As an added bonus, we can use the Paint object’s <a href="https://developer.android.com/reference/android/graphics/Paint#getTextBounds(java.lang.String,%20int,%20int,%20android.graphics.Rect)">getTextBounds</a> method to get “the smallest rectangle that encloses all of the characters”. In the above diagram, it’s the cyan rectangle. In the below values, it’s the textBounds. As the documentation says, not even the CharSequence overload takes a Spanned’s style spans into account. To do that, we’ll need to use a <a href="https://developer.android.com/reference/android/text/StaticLayout">StaticLayout</a>. Had we used more interesting strings in the demo, our values wouldn’t look so similar in the output below.</p><pre>val <em>sub </em>= <em>text</em>.subSequence(<em>start</em>, <em>end</em>)<br>android.util.Log.e(&quot;FontMetrics&quot;, &quot;&quot;&quot;Font Metrics(&quot;$<em>sub</em>&quot;):<br>  Top: $<em>top<br>  </em>Top FM: $<em>y</em>${<em>fm</em>.top}=${<em>y </em>+ <em>fm</em>.top}<br>  Ascent: $<em>y</em>${<em>fm</em>.ascent}=${<em>y </em>+ <em>fm</em>.ascent}<br>  Baseline: $<em>y<br></em>  Descent: $<em>y</em>+${<em>fm</em>.descent}=${<em>y </em>+ <em>fm</em>.descent}<br>  Bottom: $<em>bottom<br></em>  Bottom FM: $<em>y</em>+${<em>fm</em>.bottom}=${<em>y </em>+ <em>fm</em>.bottom}<br>  -- Meta<br>  Bounds: ${textBounds.toShortString()}<br>  Leading: ${<em>fm</em>.leading}<br>  Height: ${<em>fm</em>.descent - <em>fm</em>.ascent}<br>  Line Height: ${<em>fm</em>.bottom - <em>fm</em>.top + <em>fm</em>.leading}<br>&quot;&quot;&quot;.<em>trimIndent</em>())</pre><p>For my particular setup, I get:</p><pre>D/FontMetrics: &quot;A&quot;:<br>          Top: 0<br>          Top FM: 291-291=0<br>          Ascent: 291-255=36<br>          Baseline: 291<br>          Descent: 291+67=358<br>          Bottom: 386<br>          Bottom FM: 291+75=366<br>          -- Meta<br>          Bounds: [0,93][177,291]<br>          Leading: 0<br>          Height: 322<br>          Line Height: 366<br>D/FontMetrics: Font Metrics(&quot;B&quot;):<br>          Top: 386<br>          Top FM: 677-291=386<br>          Ascent: 677-255=422<br>          Baseline: 677<br>          Descent: 677+67=744<br>          Bottom: 772<br>          Bottom FM: 677+75=752<br>          -- Meta<br>          Bounds: [21,479][159,677]<br>          Leading: 0<br>          Height: 322<br>          Line Height: 366<br>D/FontMetrics: &quot;C&quot;:<br>          Top: 772<br>          Top FM: 1027-291=736<br>          Ascent: 1027-255=772<br>          Baseline: 1027<br>          Descent: 1027+67=1094<br>          Bottom: 1102<br>          Bottom FM: 1027+75=1102<br>          -- Meta<br>          Bounds: [12,825][168,1032]<br>          Leading: 0<br>          Height: 322<br>          Line Height: 366</pre><p>Notice that all of our FontMetrics (top, ascent, descent, bottom, and leading) stay the same for each line, but the Canvas positions (top, bottom, x, and y) from our ReplacementSpan change to allow us to render ourselves correctly. Had we not added the 20px extra line height to our TextView, the drawing Top values would be 0, 366, and 732, respectively.</p><p>I hope this helps clear up any confusion about FontMetrics!<br>Now you can create a ReplacementSpan with ease to power up your layouts.<br>In the next episode, we’ll go over how how to <em>replace</em> ReplacementSpan in a Jetpack Compose-based UI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68a27084e739" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating from SmartThings to Home Assistant on the Synology DS220+]]></title>
            <link>https://wesalvaro.medium.com/migrating-from-smartthings-to-home-assistant-on-synology-ds220-f87b65e315dd?source=rss-49acf35f81ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/f87b65e315dd</guid>
            <category><![CDATA[nas]]></category>
            <category><![CDATA[home-assistant]]></category>
            <category><![CDATA[home-automation]]></category>
            <category><![CDATA[synology]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Wes Alvaro]]></dc:creator>
            <pubDate>Sun, 16 Jan 2022 08:56:08 GMT</pubDate>
            <atom:updated>2023-02-04T07:53:54.070Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been unhappy with Samsung SmartThings for a while. It’s buggy, slow, hard to configure, pretty limited in customization, and impossible to backup/restore in case (err.. when) I screw it up.</p><p>I saw a random demo of Home Assistant on YouTube and was instantly intrigued. It seems much more manual and in many ways not as polished, but much more performant, open source, not tied to a proprietary backend, and has a very active and helpful community. But honestly, it looked no more difficult to get working than with SmartThings through its mobile app. Home Assistant does have a web UI and mobile app for configuring but I was very excited about its use of YAML files to store these configurations which makes it much easier to tweak and manually expand without having to painfully stumble around awkward mobile UIs.</p><p>Most recently, my SmartThings hub decided to turn lights on and then never turn them off. That was the straw that broke the proverbial camel’s back so I bit the bullet and switched to Home Assistant.</p><h4>Pros</h4><ul><li>Offline</li><li>Lots of integrations</li><li>Easy to manually configure</li><li>Easy to backup/restore</li></ul><h4>Cons</h4><ul><li>Not as polished</li><li>Google Assistant integration is a paid service<br>(although maybe I’ll try slogging through <a href="https://www.juanmtech.com/integrate-google-assistant-with-home-assistant-without-a-subscription/">this tutorial</a>)</li><li>Much more expensive (unless you already have a server)</li></ul><h4>My Requirements</h4><ul><li>Something on which to run Home Assistant<br>I went the Synology DS220+ Docker Container route</li><li>Zigbee/Zwave Dongle<br>Setting this up wasted a lot of time</li><li>A decent amount of time to fiddle with automations</li></ul><p>I’m going to recount my experience of setting up Home Assistant and getting my automations … mostly … working the way I had them on my SmartThings hub. When I initially setup my SmartThings hub, I tried to integrate lots of devices:</p><ul><li>Zigbee Lights<br>I have a few of two different model Osram Lightify RGB bulbs/strips.</li><li>Zigbee Motion/Temperature Sensors<br>I have some from Bosch that required a special script to work with SmartThings and were pretty flaky so I ended up buying the official SmartThings sensors.</li><li>Zigbee Outlet<br>Used to pre-warm and automatically turn off my kotatsu.</li><li>Switch Bot physical switch<br>Used to pre-warm a bath for me on the way home.</li><li>Several different IR blasters<br>In Japan IR controlled AC units and ceiling lights are the norm.</li></ul><p>It was nice to be able to integrate these into Google Home for controlling with the Google Assistant, but in the end, I mostly gave up and pretty much just have a couple self-sufficient automations that I use constantly: Motion activated, time-based color/brightness light automations. Hopefully, migrating these would be quick. 12 hours later, they’re <em>half</em> working but oh so much faster with Home Assistant compared to SmartThings.</p><p>Two things caused me grief:</p><ul><li>Getting the Zwave/Zigbee dongle working</li><li>Getting my automations working</li></ul><p>Two things were easy:</p><ul><li>Setting up the Synology DS220+</li><li>Setting up Docker with HomeAssistant</li></ul><p>Hopefully my experience will help you. I have a background in computer science and computer dabbling but I’m new to backends, setting up servers, Linux administration, and Docker.</p><h4>Setting up Home Assistant</h4><p>The steps for setting up the Synology DS220+ with Docker and the Home Assistant container are well documented elsewhere, so I’m not getting into that. You’ll definitely want to enable SSH access in the settings menu.</p><h4>Setting up the Zwave+Zigbee Dongle</h4><p>The Nortek HUSBZB-1 dongle came pretty well recommended for Home Assistant, so that’s what I went with. In the official setup instructions, they recommend (but do not require) <a href="https://github.com/walthowd/husbzb-firmware">upgrading the firmware</a> of the dongle. This was a huge time sink. I tried getting the script to work on my MacBook and my Windows Subsystem for Linux (WSL) to no avail. It only ever showed up once as a /dev device on my Mac and never showed up in WSL (yes, even after attaching it with usbipd-win). I tried getting <a href="https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers">these drivers</a>, but I couldn’t download them for whatever reason due to an Access Denied error. I never could get the Python script to recognize the device and eventually just gave up on upgrading the firmware. Luckily it seemed to work well-enough as is was. (I did eventually get the firmware upgraded, see further down for details.)</p><p>Plugging the dongle into the DS220+, it didn’t show up as a /dev device there, either. Eventually, I found a working driver on jadahl.com (sadly, jadahl’s website is now down, but I found them on <a href="https://github.com/robertklep/dsm7-usb-serial-drivers">GitHub</a>, now). I determined I needed the geminilake drivers for my DS220+ from the output of uname -a:</p><pre>uname -a<br># Linux NAS 4.4.180+ #42218 SMP Mon Oct 18 19:16:55 CST 2021 x86_64 GNU/Linux synology_geminilake_220+</pre><p>There was a lot of mention of installing these drivers via the Synology UI with an “SPK” file, but there was no SPK file to be found, just .ko files. Installation on the DS220+ on is still straightforward. Just download the right drivers for your DSM version (currently 7.1):</p><pre>cd /lib/modules<br>sudo wget https://raw.githubusercontent.com/robertklep/dsm7-usb-serial-drivers/main/modules/geminilake/dsm-7.1/cp210x.ko<br>sudo wget https://raw.githubusercontent.com/robertklep/dsm7-usb-serial-drivers/main/modules/geminilake/dsm-7.1/ch341.ko</pre><p>Insert the modules to get them installed then reboot:</p><pre>insmod /lib/modules/cp210x.ko &gt; /dev/null 2&gt;&amp;1<br>insmod /lib/modules/ch341.ko &gt; /dev/null 2&gt;&amp;1<br>sudo reboot</pre><p>After the reboot, we can run dmesg | grep tty and see the device loaded:</p><pre>[   69.733128] usb 1-2: cp210x converter now attached to ttyUSB0<br>[   69.782423] usb 1-2: cp210x converter now attached to ttyUSB1</pre><p>Nice. It looks like I only need the cp210x driver, so I might remove the extra ch341 driver later but it’s not hurting anything by being there, I reckon.</p><p>After the device is recognized, we need to pass it in to Home Assistant. This is actually much easier than I thought it was going to be. I stopped the running Home Assistant Docker container via the Synology UI and then ran it from the command line to pass in the dongle devices. You’ll probably need to change a permission before docker run will execute… Otherwise it may fail with a very esoteric error message. Love that. (Yes, I just used docker run instead of docker-compose since I didn’t find it necessary.)</p><pre>docker run ...<br># docker: unknown server OS: .<br># See &#39;docker run --help&#39;.<br>sudo chmod 666 /var/run/docker.sock</pre><p>As a side note, after I got everything working, I was actually able to update the dongle’s firmware on the DS220+ itself! You should be able to do that as well at this point before getting started with the integration in HA. I pulled the walthowd/husbzb-firmware Docker image in the Synology UI. Then ran it and successfully flashed the device from the command line:</p><pre>docker run \<br>  --rm --device=/dev/ttyUSB1:/dev/ttyUSB1 -it \<br>  walthowd/husbzb-firmware bash<br>./ncp.py scan<br># Connecting to.. /dev/ttyUSB1 57600 True False <br># {&quot;ports&quot;: [{&quot;port&quot;: &quot;/dev/ttyUSB1&quot;, &quot;vid&quot;: &quot;10C4&quot;, &quot;pid&quot;: &quot;8A2A&quot;, &quot;deviceType&quot;: &quot;zigbee&quot;, &quot;stackVersion&quot;: &quot;5.4.1-194&quot;}]}<br>./ncp.py flash -p /dev/ttyUSB1 -f ncp-uart-sw-6.7.8.ebl</pre><h4>Setting up Zwave and Zigbee in Home Assistant</h4><p>We can update our Home Assistant configurations.yaml to add Zwave and Zigbee integrations before launching it. We just need to add their corresponding sections (I use more friendly names for the Zwave and Zigbee devices in the HA Docker container: /dev/ttyZWAVE and /dev/ttyZIGBEE, respectively).</p><pre>zwave:<br>  usb_path: /dev/ttyZWAVE<br>  network_key: 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00<br>zha:<br>  usb_path: /dev/ttyZIGBEE<br>  database_path: /config/zigbee.db</pre><p>Similar to the above docker run command, we’ll launch Home Assistant and give it access to the dongle devices with their more understandable names:</p><pre>docker run \<br>  --name=homeassistant \<br>  --restart=always --net=host -d \<br>  -e TZ=Asia/Tokyo \<br>  -v /volume1/docker/homeassistant/config:/config \<br>  --device /dev/ttyUSB0:/dev/ttyZWAVE \<br>  --device /dev/ttyUSB1:/dev/ttyZIGBEE \<br>  homeassistant/home-assistant:stable</pre><p>After that, both of the integrations showed right up. Adding devices was easy. The hard part was then getting the actual lights to behave…</p><h4>Setting up motion light automations</h4><p>Setting up your automations, scripts, scenes, etc. will be very setup dependent, so I won’t go into any of that here, but I will mention the issue I ran into when setting up my Osram Lightify A19 RGB bulbs.</p><p>It seems that these bulbs have an issue turning them on and setting the color/brightness at the same time? I’m not sure, but I know with SmartThings, this was always annoying; they would turn on with full day-time brightness at night when I had set them to turn on much dimmer. This issue caused me to waste a lot of time when setting up the bulbs in Home Assistant but at least with HA, I have much more flexibility to control how things happen.</p><p>The service to handle all this was the light.turn_on service. In addition to turning on a light, it is also able to change the light properties for lights already turned on. I’m still working on getting this to work 100%, though. Currently, it’s only working on <em>one</em> of my two A19 bulbs. Wat. The non-working one, I can change its color through the Home Assistant UI but I can’t get it to change color in a service call during an automation.</p><p>I created my own Home Assistant automation blueprint based on the included motion_light.yaml. I changed it to turn on the bulb at 1% brightness, immediately change to the desired color (submarine red at night), then increase to the desired brightness. This keeps me from being blinded compared to SmartThings that would turn on the light to white at 100% brightness before ramping <em>down</em> to my desired brightness/color.</p><p>Like I said, it’s still not perfect but it’s a pretty good start. And after messing with everything for 12 hours, I was ready to go to bed.</p><h3>In summary</h3><p>Home Assistant has its quirks and doesn’t work out-of-the-box with Zwave/Zigbee on the Synology DS220+. After lots of headaches and Googling, I was able to get past most of my roadblocks. Hopefully the above helps you get up and going much more quickly.</p><p>I’ll update this if I figure anything else out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f87b65e315dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Switching from iTerm2 to Kitty]]></title>
            <link>https://wesalvaro.medium.com/switching-from-iterm2-to-kitty-b336c9b1d97c?source=rss-49acf35f81ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/b336c9b1d97c</guid>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[iterm2]]></category>
            <category><![CDATA[kitty]]></category>
            <dc:creator><![CDATA[Wes Alvaro]]></dc:creator>
            <pubDate>Wed, 15 Sep 2021 05:50:17 GMT</pubDate>
            <atom:updated>2022-02-24T09:06:17.874Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been a long-time, hardcore user of iTerm2 on Mac. One of the big reasons I love using my Mac everyday is because of iTerm2’s plethora of features. However, I’ve begun to feel like it has become sluggish and bloated. A lot of features I don’t even use and some I try to but they don’t work consistently. In the cases when I need to use Linux, what do I even use? I can’t stand Gnome Terminal. And my recent fascination with ligatures in fonts like Fira Code has left me wanting more typography support and speed.</p><p>In steps Kitty.</p><p>After looking through various terminal options for Mac (and also keeping in mind what is cross-platform) Kitty seemed like the perfect replacement. Here’s how I switched from iTerm2 with no looking back. I hope it helps you if you run into any of the issues or feature “requirements” that I did!</p><h3>Configuration</h3><p>The first thing about Kitty is that it has all of its configuration in a text file. This makes backup and restore on par with other dot files. And it obviously means configuring and testing the options isn’t as hand-holdy but that’s OK.</p><p><em>The par features I wanted:</em></p><ol><li>Font Customizing</li><li>Theming</li><li>Scripting / Extensions</li><li>Integration with Alfred (and other external tools)</li><li>Hot key / “Visor” window</li><li>Interacting with on-screen text</li><li>Image presentation</li><li>Password Manager</li></ol><h4>Font Customization (strong win: Kitty)</h4><p>Everyone has their own opinion on fonts, I’m currently using Fira Code with ligatures and the support that Kitty provides for fonts and their extra features is excellent. I can enable alternate zero and oldstyle numerals quite simply:</p><pre>font_features FiraCode-Retina +zero +onum</pre><p>And these settings can be applied to different fonts which makes sense because you can select glyphs from different ones. If you want some Nerd Font symbols in Kitty, we can easily assign those character codes to the Symbols Nerd Font (i.e. we don’t need any specific augmented font). This is amazing.</p><pre>symbol_map U+E000-U+F8FF Symbols Nerd Font</pre><p>Now Exa and other Nerd Font compatible apps works nicely:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nMHq6t3VZlXtxeOOowzpKQ.png" /></figure><h4>Theming (win: Kitty)</h4><p>Kitty has a built-in “kitten” to easily compare and setup themes:</p><pre>kitty +kitten themes</pre><h4>Scripting / Extensions (winner: meh)</h4><p>Both iTerm2 and Kitty have their oddities when it comes to scripting. Getting Kitty setup properly was confusing (I resorted to looking at the Kitty source code at one point…). In the end, I got it working and it works quite nicely. To enable the feature you have to set two options. First, set allow_remote_access yes in order to allow access from other applications. The second option is listen_on but if we enable it in the configuration file, Kitty will “helpfully” append on its PID which makes it inconvenient for scripting. To prevent Kitty from adding its PID, the option has to be set in the command line arguments. But for Mac users launching Kitty with Alfred or by just double-clicking, there can’t be any added arguments… Kitty supports this via <em>a different configuration file.</em></p><pre># ~/.config/kitty/macos-launch-services-cmdline<br>--listen-on=unix:/tmp/mykitty --single-instance</pre><p>The listen-on argument here is what we want. The single-instance is also a good idea, in my opinion.</p><p>After we launch Kitty, we can interact with it via commands like:</p><pre>kitty @ --to=unix:/tmp/mykitty &lt;SOME_KITTY_COMMAND_AND_OPTIONS&gt;</pre><p>This will come up as an example in the next section.</p><h4>Integration with Alfred (winner: tie)</h4><p>I use Alfred instead of Spotlight for its many features. I tried Raycast for the same reasons that I am trying Kitty now, but I’m not really sold on it, yet. To get Kitty to work as a custom terminal in Alfred, we’ll need an AppleScript. It took me a bit of searching and testing on my own to get it working how I like. What I ended up with is:</p><pre>on alfred_script(q)<br> tell application &quot;kitty&quot; to activate<br> do shell script &quot;/Applications/Kitty.app/Contents/MacOS/kitty @ --to=unix:/tmp/mykitty new-window --new-tab --cwd=current &quot;<br> do shell script &quot;/Applications/Kitty.app/Contents/MacOS/kitty @ --to=unix:/tmp/mykitty send-text \&quot;&quot; &amp; q &amp; &quot;<br>\&quot;&quot; <br>end alfred_script</pre><p>This activates kitty, opens a new window, and then sends the query with a new line. I’m not great (or even competent) at AppleScript, so I’m sure this could be improved. The query can be passed with the new-window command, but that causes the new window to close when the command completes.</p><h4>Hot key / “Visor” window (winner: iTerm2)</h4><p>I love the hotkey window feature of iTerm2. Always having the terminal instantly available in a consistent location is fantastic. However, this is not a feature of Kitty. It was suggested to use an Alfred hotkey to accomplish this and that works pretty well if you also assign Kitty to all desktops by right-clicking the icon in the dock.</p><h4>Interacting with on-screen text (winner: Kitty)</h4><p>Another feature of iTerm2 that I love is the ability to interact with arbitrary test presented on screen with triggers or auto-selection. This allows for really powerful features but it’s not always super reliable.</p><p>We use internal short-URLs and IDs for a wide range of things and I like to be able to click on them to open in different web front-ends. Kitty supports this through the “hints” kitten. Built-in is normal URL support, but I want some more obscure patterns and custom handling. I was able to use the regex hint type with a simple script to take care of it. The key mapping below (⌘+g, b) searches the screen content for bug links like b/12345 and then let’s me select one to open_as_http which is nice since our bug links commonly don’t have the http:// prefix.</p><pre>map cmd+g&gt;b kitten hints \<br>  --type=regex --regex=&#39;b/\d+&#39; --program=~/bin/open_as_http</pre><p>The open_as_http is a one line script:</p><pre>open -a &quot;Google Chrome&quot; <a href="http://$1/">http://$1</a></pre><h4>Image presentation (winner: tie)</h4><p>Yeah, it’s dumb, but I like to see images in the terminal. I do a lot of screenshot golden updates and this actually saves me a lot of time. iTerm2 has an imgcat tool to do this and it seems that the icat kitten is Kitty’s analog. Works pretty well. Unscientifically, it seemed faster.</p><h4>Password Manager (winner: tie)</h4><p>I have to type my password in the console a lot over the course of the day. iTerm2 has a built-in password manager, which is nice, but not necessary since Macs already have a powerful one built-in. The Keychain Access app is pretty easy-to-use and the command line security app is, as well.</p><p>Another Kitty user created a kitten to check for a password prompt then execute a command to fetch your password. The setup is pretty straightforward and you can configure the security options to your liking.</p><ol><li><a href="https://github.com/nerdrew/kittens/blob/master/password.py">Download the kitten from here</a> into ~/.config/kitty/kittens .</li><li>Add a keyboard mapping in your Kitty config.</li><li>Add a generic password entry via the Keychain Access app.</li><li>Try a sudo command and then hit your shortcut.</li></ol><p>My keyboard mapping uses the Name of the password entry:</p><pre>map cmd+BACKSLASH kitten \<br>  kittens/password.py \<br>    security find-generic-password -l &quot;YOUR PASSWORD NAME&quot; -w</pre><p>You can try out the security command on your own when testing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b336c9b1d97c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Dividers in Android Layouts]]></title>
            <link>https://wesalvaro.medium.com/adding-dividers-in-android-layouts-e8f1b85720db?source=rss-49acf35f81ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8f1b85720db</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[features]]></category>
            <category><![CDATA[views]]></category>
            <dc:creator><![CDATA[Wes Alvaro]]></dc:creator>
            <pubDate>Mon, 02 Aug 2021 03:58:53 GMT</pubDate>
            <atom:updated>2021-08-02T03:58:53.726Z</atom:updated>
            <content:encoded><![CDATA[<p>You’ve probably wanted to separate the items in your Android list-type layouts (e.g. LinearLayout, RecyclerView, and ListView) on more than one occasion. You might have used odd/negative margins/paddings or inserted unnecessary space/divider views. Did you know these views have support for dividers built in?</p><h3>RecyclerView</h3><p>For RecyclerViews, we can use an <a href="https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.ItemDecoration">ItemDecoration</a>. This decoration is actually applied to the whole item view and is the most powerful API we’ll talk about. For simple dividers, though, all we’re interested in is the getItemOffsets method.</p><p>There is a convenience class <a href="https://developer.android.com/reference/androidx/recyclerview/widget/DividerItemDecoration">DividerItemDecoration</a> to make it easy to create a divider by simply setting a drawable similar to how we setup a LinearLayout. However, this only works for linear RecyclerViews in one orientation. Much more functionality is possible by creating your own ItemDecoration subclass.</p><p>Another example of a useful ItemDecoration is the <a href="https://developer.android.com/reference/androidx/recyclerview/widget/ItemTouchHelper">ItemTouchHelper</a> which actually extends the functionality of the RecyclerView to support swipe to dismiss as well as dragging and dropping items.</p><h3>LinearLayout</h3><p>For LinearLayouts, we can set a <a href="https://developer.android.com/reference/android/widget/LinearLayout#attr_android:divider">divider</a>. We then control it with the property showDividers which can have any combination of the flags “beginning”, “middle”, and “end”.</p><p>There is <a href="https://issuetracker.google.com/24453303"><strong>a bug</strong> with horizontally oriented LinearLayout middle dividers</a> in RTL layouts. They are not rendered correctly and ruin your layout. As a workaround for transparent dividers: you can set the dividers to show at the beginning, middle, and end then subtract the extra spacing elsewhere in the layout. Far from ideal, but the bug has been opened and closed several times since 2015, so I’m not holding my breath for a fix. Perhaps moving to Jetpack Compose is the easiest fix.</p><h3>ListView</h3><p>While this view group is pretty much outdated by RecyclerViews, ListViews also support a <a href="https://developer.android.com/reference/android/widget/ListView#attr_android:divider">divider</a> as well as specifying its height via dividerHeight. It works similar to the LinearLayout but we specify if we want them to show at the beginning and end by two other attributes: headerDividerEnabled and footerDividerEnabled. Divider can be @null for making easy transparent divisions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8f1b85720db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Digging into logcat on-device]]></title>
            <link>https://wesalvaro.medium.com/digging-into-logcat-on-device-fa0e0c458cb8?source=rss-49acf35f81ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa0e0c458cb8</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[logs]]></category>
            <category><![CDATA[command-line]]></category>
            <dc:creator><![CDATA[Wes Alvaro]]></dc:creator>
            <pubDate>Tue, 22 Jun 2021 02:11:56 GMT</pubDate>
            <atom:updated>2021-06-22T02:11:56.203Z</atom:updated>
            <content:encoded><![CDATA[<p>We all know how to run adb logcat and some of us might have used a flag or two or piped the output to grep but what do we do if we need to access the contents of the log from on-device (e.g. when looking for the output file of <a href="https://medium.com/@wesalvaro/dump-android-thread-stack-traces-84c4d8a94785">our thread traces</a> during a UIAutomator test)?</p><p>We can access the logcat from shell via the (you probably guessed it)logcat command. This command is <a href="https://developer.android.com/studio/command-line/logcat">documented quite extensively</a> and provides quite a fair amount of options. It’s fairly straightforward to filter our log when we need to reconcile the results of some command we’ve previously executed in the shell.</p><p>If we’re trying to get the location to <a href="https://medium.com/@wesalvaro/dump-android-thread-stack-traces-84c4d8a94785">our thread traces</a>, we can use some options to logcat and a few piped on commands.</p><pre># logcat -d -s -b main &quot;tombstoned:E&quot; | \<br>    tail -n+2 | \<br>    tail -n1 | \<br>    awk &#39;{ print $NF }<br>/data/anr/trace_12</pre><p>The built-in logcat comes with lots of options but I also wanted to change the output format and create profiles based on my debugging task. To handle that, I created <a href="https://github.com/wesalvaro/nyandroidlogcat">a simple utility with Go</a>. I’m also working on an interactive, Curses-based version but the library I’m using for that right now has some bugs. Maybe you’ll find it’s useful for you, too!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa0e0c458cb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>