range - Dave's Blog

Search
My timeline on Mastodon

Tiny browser features: JSBrowser zoom

2018 May 10, 3:49

JSBrowser is a basic browser built as a Win10 JavaScript UWP app around the WebView HTML element. Its fun and relatively simple to implement tiny browser features in JavaScript and in this post I'm implementing zoom.

My plan to implement zoom is to add a zoom slider to the settings div that controls the scale of the WebView element via CSS transform. My resulting zoom change is in git and you can try the whole thing out in my JSBrowser fork.

Slider

I can implement the zoom settings slider as a range type input HTML element. This conveniently provides me a min, max, and step property and suits exactly my purposes. I chose some values that I thought would be reasonable so the browser can scale between half to 3x by increments of one quarter. This is a tiny browser feature after all so there's no custom zoom entry.

<a><label for="webviewZoom">Zoom</label><input type="range" min="50" max="300" step="25" value="100" id="webviewZoom" /></a>

To let the user know this slider is for controlling zoom, I make a label HTML element that says Zoom. The label HTML element has a for attribute which takes the id of another HTML element. This lets the browser know what the label is labelling and lets the browser do things like when the label is clicked to put focus on the slider.

Scale

There are no explicit scale APIs for WebView so to change the size of the content in the WebView we use CSS.

        this.applyWebviewZoom = state => {
const minValue = this.webviewZoom.getAttribute("min");
const maxValue = this.webviewZoom.getAttribute("max");
const scaleValue = Math.max(Math.min(parseInt(this.webviewZoom.value, 10), maxValue), minValue) / 100;

// Use setAttribute so they all change together to avoid weird visual glitches
this.webview.setAttribute("style", [
["width", (100 / scaleValue) + "%"],
["height", "calc(" + (-40 / scaleValue) + "px + " + (100 / scaleValue) + "%)"],
["transform", "scale(" + scaleValue + ")"]
].map(pair => pair[0] + ": " + pair[1]).join("; "));
};

Because the user changes the scale at runtime I accordingly replace the static CSS for the WebView element with the script above to programmatically modify the style of the WebView. I change the style with one setAttribute call to do my best to avoid the browser performing unnecessary work or displaying the WebView in an intermediate and incomplete state. Applying the scale to the element is as simple as adding 'transform: scale(X)' but then there are two interesting problems.

The first is that the size of the WebView is also scaled not just the content within it. To keep the WebView the same effective size so that it still fits properly into our browser UI, we must compensate for the scale in the WebView width and height. Accordingly, you can see that we scale up by scaleValue and then in width and height we divide by the scaleValue.

transform-origin: 0% 0%;

The other issue is that by default the scale transform's origin is the center of the WebView element. This means when scaled up all sides of the WebView would expand out. But when modifying the width and height those apply relative to the upper left of the element so our inverse scale application to the width and height above aren't quite enough. We also have to change the origin of the scale transform to match the origin of the changes to the width and height.

PermalinkCommentsbrowser css-transform javascript JS jsbrowser uwp webview win10

WinRT Toast from PowerShell

2016 Jun 15, 3:54

I've made a PowerShell script to show system toast notifications with WinRT and PowerShell. Along the way I learned several interesting things.

First off calling WinRT from PowerShell involves a strange syntax. If you want to use a class you write [-Class-,-Namespace-,ContentType=WindowsRuntime] first to tell PowerShell about the type. For example here I create a ToastNotification object:

[void][Windows.UI.Notifications.ToastNotification,Windows.UI.Notifications,ContentType=WindowsRuntime];
$toast = New-Object Windows.UI.Notifications.ToastNotification -ArgumentList $xml;
And here I call the static method CreateToastNotifier on the ToastNotificationManager class:
[void][Windows.UI.Notifications.ToastNotificationManager,Windows.UI.Notifications,ContentType=WindowsRuntime];
$notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($AppUserModelId);
With this I can call WinRT methods and this is enough to show a toast but to handle the click requires a little more work.

To handle the user clicking on the toast I need to listen to the Activated event on the Toast object. However Register-ObjectEvent doesn't handle WinRT events. To work around this I created a .NET event wrapper class to turn the WinRT event into a .NET event that Register-ObjectEvent can handle. This is based on Keith Hill's blog post on calling WinRT async methods in PowerShell. With the event wrapper class I can run the following to subscribe to the event:

function WrapToastEvent {
param($target, $eventName);

Add-Type -Path (Join-Path $myPath "PoshWinRT.dll")
$wrapper = new-object "PoshWinRT.EventWrapper[Windows.UI.Notifications.ToastNotification,System.Object]";
$wrapper.Register($target, $eventName);
}

[void](Register-ObjectEvent -InputObject (WrapToastEvent $toast "Activated") -EventName FireEvent -Action {
...
});

To handle the Activated event I want to put focus back on the PowerShell window that created the toast. To do this I need to call the Win32 function SetForegroundWindow. Doing so from PowerShell is surprisingly easy. First you must tell PowerShell about the function:

Add-Type @"
using System;
using System.Runtime.InteropServices;
public class PInvoke {
[DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hwnd);
}
"@
Then to call:
[PInvoke]::SetForegroundWindow((Get-Process -id $myWindowPid).MainWindowHandle);

But figuring out the HWND to give to SetForegroundWindow isn't totally straight forward. Get-Process exposes a MainWindowHandle property but if you start a cmd.exe prompt and then run PowerShell inside of that, the PowerShell process has 0 for its MainWindowHandle property. We must follow up process parents until we find one with a MainWindowHandle:

$myWindowPid = $pid;
while ($myWindowPid -gt 0 -and (Get-Process -id $myWindowPid).MainWindowHandle -eq 0) {
$myWindowPid = (gwmi Win32_Process -filter "processid = $($myWindowPid)" | select ParentProcessId).ParentProcessId;
}
PermalinkComments.net c# powershell toast winrt

Tweet from David Risney

2016 Jun 9, 4:02
Movie written by algorithm turns out to be hilarious and intense http://arstechnica.com/the-multiverse/2016/06/an-ai-wrote-this-movie-and-its-strangely-moving/ 
PermalinkComments

Unicode Clock

2016 Jan 24, 2:00

I've made a Unicode Clock in JavaScript.

Unicode has code points for all 30 minute increments of clock faces. This is a simple project to display the one closest to the current time written in JavaScript.

Because the code points are all above 0xFFFF, I make use of some ES6 additions. I use the \u{XXXXXX} style escape sequence since the old style JavaScript escape sequence \uXXXX only supports code points up to 0xFFFF. I also use the method String.codePointAt rather than String.charCodeAt because the code points larger than 0xFFFF are represented in JavaScript strings using surrogate pairs and charCodeAt gives the surrogate value rather than codePointAt which gives the code point represented by the pair of surrogates.

"🕛".codePointAt(0)
128347
"🕛".charCodeAt(0)
55357

🕐🕑🕒🕓🕔🕕🕖🕗🕘🕙🕚🕛🕜🕝🕞🕟🕠🕡🕢🕣🕤🕥🕦🕧

The ordering of the code points does not make it simple to do this. I initially guessed the first code point in the range would be 12:00 followed by 12:30, 1:00 and so on. But actually 1:00 is first followed by all the on the hour times then all the half hour times.

PermalinkCommentsjavascript Unicode

Retweet of KernelMag

2016 Jan 16, 6:11
An oral history of A Special Thing, with @JimmyPardo & @ScottAukerman: http://trib.al/eIKf1DA  pic.twitter.com/W8dPw9cYt2
PermalinkComments

Tweet from David_Risney

2015 Oct 7, 2:17
On whistleblower Edward Scissorhands: "to cast him out… simply because he has scissors for hands… that's strange" http://kottke.org/15/09/whistleblower-edward-scissorhands …
PermalinkComments

RIP CadburdyShe died yesterday. Besides the normal grief its...

2015 Apr 8, 2:43


RIP Cadburdy

She died yesterday. Besides the normal grief its strange being the adult and dealing with a deceased pet.

PermalinkComments

RIP CadburdyShe died yesterday. Besides the normal grief its...

2015 Apr 8, 2:43


RIP Cadburdy

She died yesterday. Besides the normal grief its strange being the adult and dealing with a deceased pet.

PermalinkComments

Retweet of anatudor

2015 Mar 22, 10:24
Collection can be found here - over 100 demos showing what can be done with just 1 range input http://codepen.io/collection/DgYaMj/8/ … pic.twitter.com/CAndEDATj9
PermalinkComments

fuckyeahpeeweeherman:Pee-wee Herman’s next adventure is coming...

2015 Mar 17, 3:28


fuckyeahpeeweeherman:

Pee-wee Herman’s next adventure is coming to Netflix.

Netflix says the film will be called “Pee-wee’s Big Holiday” and will feature Pee-wee taking his first-ever vacation after meeting a mysterious stranger.

Reubens created the quirky character in the 1980s when he was a member of the Groundlings improv group.

Netflix currently streams the Pee-wee films “Pee-wee’s Big Adventure” and “Big Top Pee-wee,” as well as the TV show “The Pee-wee Herman Show” and “Pee-wee’s Playhouse.”

“Pee-wee’s Big Holiday” is being produced by Judd Apatow and directed by John Lee. Reubens is writing the movie’s script with Paul Rust.

Netflix says production will begin this year.

PermalinkComments

fuckyeahpeeweeherman:Pee-wee Herman’s next adventure is coming...

2015 Mar 17, 3:28


fuckyeahpeeweeherman:

Pee-wee Herman’s next adventure is coming to Netflix.

Netflix says the film will be called “Pee-wee’s Big Holiday” and will feature Pee-wee taking his first-ever vacation after meeting a mysterious stranger.

Reubens created the quirky character in the 1980s when he was a member of the Groundlings improv group.

Netflix currently streams the Pee-wee films “Pee-wee’s Big Adventure” and “Big Top Pee-wee,” as well as the TV show “The Pee-wee Herman Show” and “Pee-wee’s Playhouse.”

“Pee-wee’s Big Holiday” is being produced by Judd Apatow and directed by John Lee. Reubens is writing the movie’s script with Paul Rust.

Netflix says production will begin this year.

PermalinkComments

Retweet of JustRogDigiTec

2015 Feb 12, 6:29
Historical note for #mshtml is that cells did Excel style col/row indexing. Either single A7, or range A7:C12, Try it http://jsfiddle.net/16xcvwag/1/ 
PermalinkComments

Retweet of DrPizza

2015 Feb 11, 12:38
btw, @fxshaw, if Microsoft wants to rebrand with my new logo, I'm sure we can come to a suitable arrangement. http://cdn.arstechnica.net/wp-content/uploads/2015/02/cool-microsoft1-300x150.png …
PermalinkComments

The Strange & Curious Tale of the Last True Hermit

2014 Aug 21, 3:02

The story of Chris Knight, living in isolation in the woods of Maine for 27 years.

'Anyone who reveals what he's learned, Chris told me, is not by his definition a true hermit. Chris had come around on the idea of himself as a hermit, and eventually embraced it. When I mentioned Thoreau, who spent two years at Walden, Chris dismissed him with a single word: “dilettante.”'

'But still, I pressed on, there must have been some grand insight revealed to him in the wild…”Get enough sleep.”'

I don’t want to brag, but I’ve been telling that people all along and I didn’t have to live alone in the woods for decades.

PermalinkCommentshermit

From Inside Edward Snowden’s Life as a Robot: Wizner had...

2014 Jun 23, 7:04


From Inside Edward Snowden’s Life as a Robot:

Wizner had to jump on a phone call during a meeting with his whistleblower client. When he got off the phone, he found that Snowden had rolled the bot into civil liberties lawyer Jameel Jaffer’s office and was discussing the 702 provision of the Foreign Intelligence Surveillance Act. “It was kind of cool,” Wizner says.

It is neat but they’re marketing video is at times strangely terrifying. Put different music on when the Susan-bot comes up behind the unknowing Mark and this could be a horror movie trailer.

PermalinkCommentsedward-snowden beam robot telepresence

Shout Text Windows 8 App Development Notes

2013 Jun 27, 1:00

My first app for Windows 8 was Shout Text. You type into Shout Text, and your text is scaled up as large as possible while still fitting on the screen, as you type. It is the closest thing to a Hello World app as you'll find on the Windows Store that doesn't contain that phrase (by default) and I approached it as the simplest app I could make to learn about Windows modern app development and Windows Store app submission.

I rely on WinJS's default layout to use CSS transforms to scale up the user's text as they type. And they are typing into a simple content editable div.

The app was too simple for me to even consider using ads or charging for it which I learned more about in future apps.

The first interesting issue I ran into was that copying from and then pasting into the content editable div resulted in duplicates of the containing div with copied CSS appearing recursively inside of the content editable div. To fix this I had to catch the paste operation and remove the HTML data from the clipboard to ensure only the plain text data is pasted:

        function onPaste() {
var text;

if (window.clipboardData) {
text = window.clipboardData.getData("Text").toString();
window.clipboardData.clearData("Html");
window.clipboardData.setData("Text", util.normalizeContentEditableText(text));
}
}
shoutText.addEventListener("beforepaste", function () { return false; }, false);
shoutText.addEventListener("paste", onPaste, false);

I additionally found an issue in IE in which applying a CSS transform to a content editable div that has focus doesn't move the screen position of the user input caret - the text is scaled up or down but the caret remains the same size and in the same place on the screen. To fix this I made the following hack to reapply the current cursor position and text selection which resets the screen position of the user input caret.

        function resetCaret() {
setTimeout(function () {
var cursorPos = document.selection.createRange().duplicate();
cursorPos.select();
}, 200);
}

shoutText.attachEvent("onresize", function () { resetCaret(); }, true);
PermalinkCommentsdevelopment html javascript shout-text technical windows windows-store

Number 1 and Benford’s Law - Numberphile (by...

2013 Jun 25, 4:40


Number 1 and Benford’s Law - Numberphile (by numberphile)

I’d heard of Benford’s Law before but it sounded totally counter intuitive to me. This video does a good job explaining why one shows up as the leading digit in sets of random numbers that span large ranges.

PermalinkCommentsmath video benfords-law

This might be the strangest release of classic Chicago label...

2013 May 17, 5:43


This might be the strangest release of classic Chicago label Trax yet! The clue’s in the title - it’s Daft Punk brassified. We get four classics by the world’s most famous Gallic robot duo: “Harder, Better, Faster, Stronger” gets turned into a 1940s Dick Tracy-style riff-off with every form of trumpet imaginable, “Around The World” mixes wind instruments with that famous vocal mantra, “Da Funk” features plenty of sassy brass and “One More Time” wraps things up on a swingin’, jazzy high.

PermalinkCommentsSoundCloud Iamjasonalexander Brass Music music cover daft-punk

IKEA's New Catalogs: Less Pine, More Pixels - WSJ.com

2012 Aug 24, 3:15

CGI for the IKEA catalog:

That couch catching your eye in the 2013 edition of IKEA’s new catalog may not be a couch at all. It is likely the entire living room was created by a graphic artist. In fact, much of the furniture and settings in the 324-page catalog are simply a collection of pixels and polygons arranged on a computer.

PermalinkComments3d photo graphics ikea

paulftompkins: So! Here is the trailer for a web series I’ll be...

2012 May 6, 7:31


paulftompkins:

So! Here is the trailer for a web series I’ll be hosting, where I chat with cool people over actual alcoholic drinks. We’ve shot a dozen of these so far and I am grateful to have been asked to host them.  I got to have interesting conversations with strangers and friends alike.

It goes live on Monday 5/7!

Internet terms!

PermalinkCommentshumor paul-f-tompkins interview youtube video
Older Entries Creative Commons License Some rights reserved.