I'm using Chrome (Version 19.0.1084.46). I enabled the Gamepad API in chrome://flags. I plugged in some game pads, but navigator.webkitGamepads is always an array of length 4 containing only undefined.
navigator.webkitGamepads
GamepadList
0: undefined
1: undefined
2: undefined
3: undefined
length: 4
__proto__: GamepadList
What do I need to do to test out using gamepads? I'm on Ubuntu Linux if that matters.
I was having trouble with this as well (on Ubuntu 10.04 with Chrome 21.0.1163.0 dev). I ran across this from a thread on chromium-discussions:
Note that you need to press a face button on the gamepad before data
will be available. This is due to fingerprinting concerns.
I wrote a quick test page that seems to work if you hold a controller button down while refreshing the page. I'm using a Gamestop-branded Xbox 360 wired controller with the xboxdrv driver.
Also, one other important thing to note - Chrome treats these Gamepad objects like snapshots of the controller state. So if you pass around the actual Gamepad object, you'll never get updated information. Chrome seems to only poll the controller when you call the navigator.webkitGamepads[x] getter (see line 23 in my test page).
SPECIAL NOTE: The GamePad API is handled in two completely different ways by Firefox and Google Chrome. Because of this, you need to include code to test for your browser's identity, and handle the cases accordingly.
When the navigator.getGamePads() method is invoked, an array of objects is returned, and those objects contain information about the identity of your gamepads/joysticks, and the state of the axes/buttons thereof.
Here's the issue: on Firefox, the method hands the array to your calling code, and you can then examine that array repeatedly, to look for changes of axis/button state in your own code. Firefox behaves in the expected manner, and updates the objects you've received with new axis/button data, as and when it becomes available.
Google Chrome, on the other hand, treats the array totally differently. Chrome treats the array as a one-time snapshot of the status of your gamepads/joysticks, and if you want to fetch new data, you have to perform another invocation of navigator.getGamePads(), to fetch a new snapshot, discarding the old one.
As a consequence, you need something like this to make your code work on both browsers (assuming that the variable 'gp' is the variable in which you previously stored the return value from your first invocation of navigator.getGamePads() ...)
var ua = navigator.userAgent;
if (ua.toLowerCase().indexOf("chrome") != -1)
gp = navigator.getGamePads();
Why the two browsers behave so differently, is a topic for another thread, but I suspect it has much to do with the fact that the GamePad API is still somewhat experimental, and the fine detail of the standard applicable thereto has not yet been finalised.
In my case, running Chrome on Windows 7 64-bit (but the 32-bit version, for some strange reason best known to my computer's manufacturer, who installed it in this fashion), the array returned by navigator.getGamePads() currently contains only as many entries as there are actual gamepads/joysticks plugged into my computer. If you're experiencing something different on Chrome under Linux, then you need to take this into account also, by testing to see if you have any null values in the array.
Another factor to take into account, is that when selecting a gamepad/joystick, the standard in place calls for the index property of the GamePad object to be referenced, and used thereafter to index into the array. The reason for this is covered in more detail in this document:
W3C page : Editor's Draft on the GamePad interface
However, whilst the implementation of this works as documented above in my incarnation of Google Chrome, you may have to check your version experimentally to see if it behaves the same as mine. If it doesn't, adjust your code accordingly until such time as the standard is finalised, and proper conformity thereto is enforced in all modern browsers and all OS incarnations thereof.
So, when you're selecting a particular gamepad/joystick to work with, the code will look something like this (with the variable 'gid' as your index selector):
var gLen = this.gamePads.length;
done = false;
idx = 0;
while (!done)
{
if (this.gamePads[idx] !== null)
{
if (gid == this.gamePads[idx].index)
{
//Here, choose this GamePad as the selected GamePad, based upon the index number as per the W3C recommendation ...
selectedGamePadIndex = gid;
selectedGamePad = this.gamePads[idx];
done = true;
//End if
}
//End if
}
//Update counter in case we haven't selected one of the available GamePads above ...
idx++;
if (idx >= gLen)
done = true; //Exit loop altogether if we've exhausted the list of available GamePads
//End while
}
I actually implemented the above code (along with some tidying up at the end) as a method for a custom object, but the principle remains the same regardless of the implementation minutiae. (I'll confess at this juncture that I have a habit of writing my own short libraries to handle tasks like this!)
Another issue to watch out for, is the manner in which the gamepad API maps the physical data sources of your gamepad/joystick to the axis/button elements of the GamePad object, and the values contained therein. I have a Microsoft Sidewinder Pro USB joystick, and the mappings for this device on my computer are seriously weird, viz:
Axes 0/1: Joystick handle (as expected)
Axes 2/3: Not assigned
Axes 4/5: 4 not assigned, 5 assigned to twist grip
Axes 6/7: 6 assigned to round slider, 7 not assigned
Axes 8/9: 8 not assigned, 9 assigned to hat switch (er, WHAT???)
Yes, that's right, analogue axis 9 is assigned to the hat switch, and seriously odd values are returned, viz:
Hat switch centred: +1.2
Hat switch up: -1.0
Hat switch down: +0.1
Hat switch left: +0.7
Hat switch right: -0.42
Quirks like this are something you should be alert to as you experiment with the GamePad API. Even worse, a so-called "standard" GamePad (defined in that document I linked to above) may report as standard on some browsers, but not on others, or worse still, report as standard on browser X in Windows, but not on the same browser X in Linux! While this will induce much hair-tearing frustration as you try to fight your way through this software equivalent of bramble thicket, getting badly scratched by some of the thorns along the way, you can at least take comfort in the fact that browser developers are working to try and ameliorate this, but it'll take time, because other things take priority (such as making sure your browser doesn't become an easy target for ransomware to hijack, which will ruin you day immensely if it happens).
This didn't work for me but maybe it helps you? Pulled from here.
function updateStatus() {
window.webkitRequestAnimationFrame(updateStatus);
var gamepads = navigator.webkitGamepads;
var data = '';
for (var padindex = 0; padindex < gamepads.length; ++padindex)
{
var pad = gamepads[padindex];
if (!pad) continue;
data += '<pre>' + pad.index + ": " + pad.id + "<br/>";
for (var i = 0; i < pad.buttons.length; ++i)
data += "button" + i + ": " + pad.buttons[i] + "<br/>";
for (var i = 0; i < pad.axes.length; ++i)
data += "axis" + i + ": " + pad.axes[i] + "<br/>";
}
document.body.innerHTML = data;
}
window.webkitRequestAnimationFrame(updateStatus);
Or as a hard alternative, there's the Javascript Joystick Plug-in (demo here) but I don't think that works in Linux.
Related
I'm using Chrome's performance tab to study the performance of a page, and I occasionally get a warning like:
DevTools: CPU profile parser is fixing 4 missing samples.
Does anyone know what this means? Googling for this warning has returned no results so far...
As coming across with and having this situation, possible helpful things to consider are as below.
As Chrome 58 is released in 2017, some changes are done related to the analyzing performance. For example:
Timeline panel is renamed as Performance panel.
Profiles panel is renamed as Memory panel.
Record Javascript CPU Profile menu is moved into Dev Tools → Three dots at right → More tools → Javascript Profiler. (Old version of Javascript Profiler)
In addition of these, the warning message that is seen (DevTools: CPU profile parser is fixing N missing samples.) is being written to the console window when there is single (program) sample between two call stacks sharing the same bottom node. Also, the samples count should be greater than or equal to 3 according to the source code.
Comments written above _fixMissingSamples method in the CPUProfileDataModel.js file explains this situtation as below;
// Sometimes sampler is not able to parse the JS stack and returns
// a (program) sample instead. The issue leads to call frames belong
// to the same function invocation being split apart.
// Here's a workaround for that. When there's a single (program) sample
// between two call stacks sharing the same bottom node, it is replaced
// with the preceeding sample.
In the light of these information, we can trace the code and examine the behavior.
CPUProfileDataModel.js
let prevNodeId = samples[0];
let nodeId = samples[1];
let count = 0;
for (let sampleIndex = 1; sampleIndex < samplesCount - 1; sampleIndex++) {
const nextNodeId = samples[sampleIndex + 1];
if (nodeId === programNodeId && !isSystemNode(prevNodeId) && !isSystemNode(nextNodeId) &&
bottomNode(idToNode.get(prevNodeId)) === bottomNode(idToNode.get(nextNodeId)) {
++count;
samples[sampleIndex] = prevNodeId;
}
prevNodeId = nodeId;
nodeId = nextNodeId;
}
if (count) {
Common.console.warn(ls`DevTools: CPU profile parser is fixing ${count} missing samples.`);
}
It seems that, it simply compares previous and next node related to current node as if they has the same bottom node (actually comparing parent nodes). Also previous and next node shouldn't be a system (program/gc/idle function) node and current node should be the 'program' node. If it is the case, then the current node in samples array is set to previous node.
idle: Waiting to do process
program: Native code execution
garbage collector: Accounts for Garbage Collection
Also, disabling Javascript samples from Performance → Capture Settings result fewer details & call stacks because of omitting all the call stacks. The warning message shouldn't appear in this case.
But, since this warning is about the sampler that says cannot parse the JS stack and call frames being split apart, it doesn't seem very important thing to consider.
Resources:
https://github.com/ChromeDevTools/devtools-frontend/tree/master/front_end/sdk
https://github.com/ChromeDevTools/devtools-frontend/blob/master/front_end/sdk/CPUProfileDataModel.js
https://chromium.googlesource.com/chromium/blink/+/master/Source/devtools/front_end/sdk/
https://developers.google.com/web/tools/chrome-devtools/evaluate-performance
https://developers.google.com/web/updates/2016/12/devtools-javascript-cpu-profile-migration
I have a webpage that uses HTML LocalStorage. It is common to have multiple tabs/windows of this page open at the same time. Since these all use the same LocalStorage and LocalStorage does not provide transactions or similar, I would like to implement some form of mutual exclusion to prevent the different tabs/windows to overwrite each other's data in an uncontrolled manner.
I tried to just port my test of the Burns/Lynch mutual exclusion algorithm to the browser by simply storing the boolean[] F in LocalStorage.
Things work perfectly in FireFox, but Chrome allows an average of about 1.3 processes (mostly just one, sometimes two and very rarely even 3 or more) into the critical section at the same time, and Internet explorer allows an average of 2 processes (mostly 1, 2, or 3, sometimes even more) in.
Since the algorithm has been proven correct and my implementation is super-trivial and I've tested the heck out of it otherwise, the only reason that I can come up with for why this is happening is that in Chrome and IE there is a delay between when I write to LocalStorage in one tab/window and when the new value will be visible in all other tabs/windows.
Is this possible? If so, is there any documentation or are there any guarantees on these delays? Or, better yet, is there some kind of "commit"- or "flush()"-call that I can use to force the changes to propagate immediately?
UPDATE:
I put together a little jsfiddle to test out the round-trip times:
// Get ID
var myID;
id = window.localStorage.getItem("id");
if (id==1) { myID = 1; window.localStorage.setItem("id", 0); }
else { myID = 0; window.localStorage.setItem("id", 1); }
// Initialize statistics variables
var lastrun = (new Date()).getTime();
var totaldelay = 0;
var count = 0;
var checks = 0;
document.documentElement.innerHTML = "ID: "+myID;
// Method that checks the round-trip time
function check() {
window.setTimeout(check, 1); // Keep running
value = window.localStorage.getItem("state");
checks++;
if (value==myID) return;
window.localStorage.setItem("state", myID);
now = new Date().getTime();
totaldelay += now - lastrun;
count++;
lastrun = now;
document.documentElement.innerHTML = "ID: "+myID+"<br/>"+
"Number of checks: "+checks+"<br/>"+
"Number of round-trips: "+count+"<br/>"+
"Checks per round-trip: "+checks/count+"<br/>"+
"Average round-trip time:"+totaldelay/count;
}
// Go!
window.setTimeout(check, 1000);
If I run this fiddle in two different windows, I get the following numbers in the second window I opened:
Browser | Checks per round-trip | Average round-trip time
------------------+-----------------------+-------------------------
Firefox 24.3.0 | 1.00 | 6.1 ms
Chrome 46.0.2490 | 1.06 | 5.5 ms
IE 10 | 17.10 | 60.2 ms
Turns out Internet Explorer again wins the competition for worst piece of software ever written...
There's actually a severe bug in IE11 (and I'm seeing issues with IE10 also) that basically makes it impossible to use LocalStorage reliably if the user opens more than one tab: Each tab essentially gets its own cached version of the same storage location and the synchronization between that cache and the actual storage is flaky at best (if it happens at all). One cannot at all rely on data making it to the other tab/window, basically ever.
Here's the official bug-report: IE 11 - Local Storage - Synchronization issues
(Which, naturally, is just one of a huge list of other issues with LocalStorage support in IE)
I love how this issue was opened in 2013 and even acknowledged, but still hasn't been fixed...
Unfortunately none of the three work-arounds posted make things any better in my tests.
In other words: Cross-tab/window communication using LocalStorage is basically impossible in IE10/11.
Surprisingly, the synchronization of cookies across windows/tabs seems to be a lot more stable (at least in my tests with IE10). So maybe that can be used as a work-around.
The Reference Source page for stringbuilder.cs has this comment in the ToString method:
if (chunk.m_ChunkLength > 0)
{
// Copy these into local variables so that they
// are stable even in the presence of ----s (hackers might do this)
char[] sourceArray = chunk.m_ChunkChars;
int chunkOffset = chunk.m_ChunkOffset;
int chunkLength = chunk.m_ChunkLength;
What does this mean? Is ----s something a malicious user might insert into a string to be formatted?
The source code for the published Reference Source is pushed through a filter that removes objectionable content from the source. Verboten words are one, Microsoft programmers use profanity in their comments. So are the names of devs, Microsoft wants to hide their identity. Such a word or name is substituted by dashes.
In this case you can tell what used to be there from the CoreCLR, the open-sourced version of the .NET Framework. It is a verboten word:
// Copy these into local variables so that they are stable even in the presence of race conditions
Which was hand-edited from the original that you looked at before being submitted to Github, Microsoft also doesn't want to accuse their customers of being hackers, it originally said races, thus turning into ----s :)
In the CoreCLR repository you have a fuller quote:
Copy these into local variables so that they are stable even in the presence of race conditions
Github
Basically: it's a threading consideration.
In addition to the great answer by #Jeroen, this is more than just a threading consideration. It's to prevent someone from intentionally creating a race condition and causing a buffer overflow in that manner. Later in the code, the length of that local variable is checked. If the code were to check the length of the accessible variable instead, it could have changed on a different thread between the time length was checked and wstrcpy was called:
// Check that we will not overrun our boundaries.
if ((uint)(chunkLength + chunkOffset) <= ret.Length && (uint)chunkLength <= (uint)sourceArray.Length)
{
///
/// imagine that another thread has changed the chunk.m_ChunkChars array here!
/// we're now in big trouble, our attempt to prevent a buffer overflow has been thawrted!
/// oh wait, we're ok, because we're using a local variable that the other thread can't access anyway.
fixed (char* sourcePtr = sourceArray)
string.wstrcpy(destinationPtr + chunkOffset, sourcePtr, chunkLength);
}
else
{
throw new ArgumentOutOfRangeException("chunkLength", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
}
chunk = chunk.m_ChunkPrevious;
} while (chunk != null);
Really interesting question though.
Don't think that this is the case - the code in question copies to local variables to prevent bad things happening if the string builder instance is mutated on another thread.
I think the ---- may relate to a four letter swear word...
I want a simple client/server setup with two Windows Phones, and I'm using the following code to set up the server:
auto providerTask = create_task(RfcommServiceProvider::CreateAsync(RfcommServiceId::FromUuid(GetServiceGUID())));
providerTask.then([this](RfcommServiceProvider^ p) -> task < void >
{
this->provider = p;
this->listener = ref new StreamSocketListener();
listener->ConnectionReceived += ref new Windows::Foundation::TypedEventHandler < Windows::Networking::Sockets::StreamSocketListener ^,
Windows::Networking::Sockets::StreamSocketListenerConnectionReceivedEventArgs ^ >
(this, &ConnectionManager::OnConnectionReceived);
return create_task(listener->BindServiceNameAsync(provider->ServiceId->AsString())).then([this]()
{
this->provider->StartAdvertising(listener);
});
}).then([](task<void> t)
{
//handle exceptions at the end of the chain
try
{
t.get();
}
catch (Platform::Exception^ ex)
{
if (ex->HResult == 0x9000000F)
{
OutputDebugString(L"Bluetooth is disabled.\n");
}
else throw ex;
}
});
GetServiceGUID() just returns the identifier I created for my App with VS's built-in GUID tool; the same one is also declared in the app manifest.
On the second device I'm looking for servers like this:
auto query = RfcommDeviceService::GetDeviceSelector(RfcommServiceId::FromUuid(GetServiceGUID()));
create_task(DeviceInformation::FindAllAsync(query))
.then([this](DeviceInformationCollection^ services)
{
if (services->Size > 0)
{
OutputDebugString(L"We've found a server!\n");
OutputDebugString(services->First()->Current->Name->Data());
}
});
The call to FindAllAsync always returns an empty collection, even though both devices are shown as paired in the settings. However, if I use RfcommServiceId::ObexObjectPush instead of FromUuid when setting up the server and later when enumerating devices, it works fine. Does anyone know why this is happening?
What do the AQS selector strings look like in both cases?
The problem is either:
The selector doesn't match the interface on the system unexpectedly
Basically the filter is used to match properties on the devices interfaces currently in KM PnP state. If an interface's properties match what is logically being requested in the selector, then it is added to the device information collection.
Maybe try FindAllAsync without a selector, then see what interfaces are currently being enumerated by KM PnP. Request the properties that are in the selector. Once you see the interface that you think you should be seeing, logically figure out why it is not matching with the selector.
The device is not paired.
If the device is not paired, then there won't be any devnodes or interfaces to represent it. Hence it cannot be discovered by FindAllAsync
The device is paired, but does not have the profile you think it has.
The Bluetooth bus driver will only create PnP state for profiles it understands. The PnP state is required for FindAllAsync to find it. RFCOMM is a basic one, so it should work though.
Anyway, start with writing some test code as outlined in 1. That will give you some infortmation to get further in your investigation.
Also, checkout the new Windows 10 API changes for Windows.Devices.Enumeration. There are new ways to discover Bluetooth devices.
-Sam
To iterate over the properties of an Object in AS3 you can use for(var i:String in object) like this:
Object:
var object:Object = {
thing: 1,
stuff: "hats",
another: new Sprite()
};
Loop:
for(var i:String in object)
{
trace(i + ": " + object[i]);
}
Result:
stuff: hats
thing: 1
another: [object Sprite]
The order in which the properties are selected however seems to vary and never matches anything that I can think of such as alphabetical property name, the order in which they were created, etc. In fact if I try it a few different times in different places, the order is completely different.
Is it possible to access the properties in a given order? What is happening here?
I'm posting this as an answer just to compliment BoltClock's answer with some extra insight by looking directly at the flash player source code. We can actually see the AVM code that specifically provides this functionality and it's written in C++. We can see inside ArrayObject.cpp the following code:
// Iterator support - for in, for each
Atom ArrayObject::nextName(int index)
{
AvmAssert(index > 0);
int denseLength = (int)getDenseLength();
if (index <= denseLength)
{
AvmCore *core = this->core();
return core->intToAtom(index-1);
}
else
{
return ScriptObject::nextName (index - denseLength);
}
}
As you can see when there is a legitimate property (object) to return, it is looked up from the ScriptObject class, specifically the nextName() method. If we look at those methods within ScriptObject.cpp:
Atom ScriptObject::nextName(int index)
{
AvmAssert(traits()->needsHashtable());
AvmAssert(index > 0);
InlineHashtable *ht = getTable();
if (uint32_t(index)-1 >= ht->getCapacity()/2)
return nullStringAtom;
const Atom* atoms = ht->getAtoms();
Atom m = ht->removeDontEnumMask(atoms[(index-1)<<1]);
if (AvmCore::isNullOrUndefined(m))
return nullStringAtom;
return m;
}
We can see that indeed, as people have pointed out here that the VM is using a hash table. However in these functions there is a specific index supplied, which would suggest, at first glance, that there must then be specific ordering.
If you dig deeper (I won't post all the code here) there are a whole slew of methods from different classes involved in the for in/for each functionality and one of them is the method ScriptObject::nextNameIndex() which basically pulls up the whole hash table and just starts providing indices to valid objects within the table and increments the original index supplied in the argument, so long as the next value points to a valid object. If I'm right in my interpretation, this would be the cause behind your random lookup and I don't believe there would be any way here to force a standardized/ordered map in these operations.
Sources
For those of you who might want to get the source code for the open source portion of the flash player, you can grab it from the following mercurial repositories (you can download a snapshop in zip like github so you don't have to install mercurial):
http://hg.mozilla.org/tamarin-central - This is the "stable" or "release" repository
http://hg.mozilla.org/tamarin-redux - This is the development branch. The most recent changes to the AVM will be found here. This includes the support for Android and such. Adobe is still updating and open sourcing these parts of the flash player, so it's good current and official stuff.
While I'm at it, this might be of interest as well: http://code.google.com/p/redtamarin/. It's a branched off (and rather mature) version of the AVM and can be used to write server-side actionscript. Neat stuff and has a ton of information that gives insight into the workings of the AVM so I thought I'd include it too.
This behavior is documented (emphasis mine):
The for..in loop iterates through the properties of an object, or the elements of an array. For example, you can use a for..in loop to iterate through the properties of a generic object (object properties are not kept in any particular order, so properties may appear in a seemingly random order)
How the properties are stored and retrieved appears to be an implementation detail, which isn't covered in the documentation. As ToddBFisher mentions in a comment, though, a data structure commonly used to implement associative arrays is the hash table. It's even mentioned in this page about associative arrays in AS3, and if you inspect the AVM code as shown by Ascension Systems, you'll find exactly such an implementation. As described, there is no notion of order or sorting in typical hash tables.
I don't believe there is a way to access the properties in a specific order unless you store that order somehow.