Hyperloop eventlistener example - appcelerator

I try to make a flac file player with Appcelerator and Hyperloopusing the OrigamiEngine
It works as I can play, pause and stop the player. But I can't get the "addEventListener" mode working. I read some examples and something about the delegate methods. But I'm not a native iOS coder and all my tryings failed.
Can anybody tells me how to code the eventlistener for the didChangeState function?
This is my unfortunately not working code
//Application Window Component Constructor
function ApplicationWindow() {
Ti.Media.audioSessionCategory = Ti.Media.AUDIO_SESSION_CATEGORY_PLAYBACK;
var NSURL = require('Foundation/NSURL');
var ORGMEngine = require('OrigamiEngine/ORGMEngine');
var audioPlayer = new ORGMEngine();
var self = Ti.UI.createWindow({
backgroundColor : '#ffffff'
});
var startStopButton = Ti.UI.createButton({
title : 'Start/Stop Streaming',
top : 100,
width : 200,
height : 40
});
var pauseResumeButton = Ti.UI.createButton({
title : 'Pause/Resume Streaming',
top : 140,
width : 200,
height : 40,
enabled : false
});
self.add(startStopButton);
self.add(pauseResumeButton);
startStopButton.addEventListener('click', function() {
console.log('audioPlayer.currentState: ' + audioPlayer.currentState);
// When paused, playing returns false.
// If both are false, playback is stopped.
if (audioPlayer.currentState == 1) {
audioPlayer.stop();
audioPlayer.release();
pauseResumeButton.enabled = false;
} else {
var url = NSURL.URLWithString('http://faq.fantasticlibrary.de/test.flac');
audioPlayer.playUrl(url);
setTimeout(function(){
console.log(audioPlayer.metadata());
}, 10000);
pauseResumeButton.enabled = true;
}
});
pauseResumeButton.addEventListener('click', function() {
console.log('audioPlayer.currentState: ' + audioPlayer.currentState);
if (audioPlayer.currentState == 1) {
audioPlayer.pause();
} else {
audioPlayer.resume();
}
});
var StateChangeDelegate = Hyperloop.defineClass('MyDelegate', 'NSObject', ['ORGMEngineDelegate']);
StateChangeDelegate.addMethod({
selector: 'engine:didChangeState:',
instance: true,
arguments: ['ORGMEngine', 'ORGMEngineState'],
callback: function (engine, state) {
if (this.didChangeState) {
this.didChangeState(engine, state);
}
}
});
var delegate = new StateChangeDelegate();
delegate.didChangeState = function(ORMEngine,state) {
console.log('does the state change???');
};
self.addEventListener('close', function() {
audioPlayer.stop();
audioPlayer.release();
});
return self;
}
module.exports = ApplicationWindow;
Running demo project to download: http://lightapps.de/files/flactest.zip

Try it:
delegate.on('didChangeState', function(ORMEngine,state){
console.log('does the state change???');
});
I can't test this in the moment, but i think that will work for you.

Related

Chartjs animate x-axis displaying data incorrectly in mac device

I am working with chartjs, I am trying to animate chart from right to left or left to right on load.
var canvas = document.getElementById('chart_canvas');
var ctx = canvas.getContext('2d');
// Generate random data to plot
var DATA_POINT_NUM = 10;
var data = {
labels: [],
datasets: [
{
data: [],
},
]
}
for (var i=0; i<DATA_POINT_NUM; i++) {
data.datasets[0].data.push(Math.random()*10);
data.labels.push(String.fromCharCode(65+i));
}
var oldDraw = Chart.controllers.line.prototype.draw;
Chart.controllers.line.prototype.draw = function(animationFraction) {
var animationConfig = this.chart.options.animation;
if (animationConfig.xAxis === true) {
var ctx = this.chart.chart.ctx;
var hShift = (1-animationFraction)*ctx.canvas.width;
ctx.save();
ctx.setTransform(1, 0, 0, 1, hShift,0);
if (animationConfig.yAxis === true) {
oldDraw.call(this, animationFraction);
} else {
oldDraw.call(this, 1);
}
ctx.restore();
} else if (animationConfig.yAxis === true) {
oldDraw.call(this, animationFraction);
} else {
oldDraw.call(this, 1);
}
}
var lineChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
animation: {
duration: 5000,
xAxis: true,
yAxis: true,
}
}
});
Example 1
The above code works fine on windows, but I'm facing issue on mac devices.While animating from left to right the data displays incorrectly means that the data moves to upward from x axis.How to fix this issue?
I am attaching screenshot.
Screenshot
Please change setTransform to transform.
Try the following code
var canvas = document.getElementById('chart_canvas');
var ctx = canvas.getContext('2d');
// Generate random data to plot
var DATA_POINT_NUM = 10;
var data = {
labels: [],
datasets: [
{
data: [],
},
]
}
for (var i=0; i<DATA_POINT_NUM; i++) {
data.datasets[0].data.push(Math.random()*10);
data.labels.push(String.fromCharCode(65+i));
}
var oldDraw = Chart.controllers.line.prototype.draw;
Chart.controllers.line.prototype.draw = function(animationFraction) {
var animationConfig = this.chart.options.animation;
if (animationConfig.xAxis === true) {
var ctx = this.chart.chart.ctx;
var hShift = (1-animationFraction)*ctx.canvas.width;
ctx.save();
ctx.transform(1, 0, 0, 1, hShift,0);
if (animationConfig.yAxis === true) {
oldDraw.call(this, animationFraction);
} else {
oldDraw.call(this, 1);
}
ctx.restore();
} else if (animationConfig.yAxis === true) {
oldDraw.call(this, animationFraction);
} else {
oldDraw.call(this, 1);
}
}
var lineChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
animation: {
duration: 5000,
xAxis: true,
yAxis: true,
}
}
});

How To Exit app by double tap on back button in NativeScript Apps

Exit app on double tap on back button in Nativescript
Please help me with snippet of code
Here is the solution that I have found:
var frameModule = require("ui/frame");
var application = require("application")
var activity = application.android.startActivity ||
application.android.foregroundActivity ||
frameModule.topmost().android.currentActivity ||
frameModule.topmost().android.activity;
var lastPress;
activity.onBackPressed = function() {
var timeDelay = 500
if (lastPress + timeDelay > java.lang.System.currentTimeMillis()) {
var startMain = new android.content.Intent(android.content.Intent.ACTION_MAIN);
startMain.addCategory(android.content.Intent.CATEGORY_HOME);
startMain.setFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(startMain);
// If you want to kill the app totally, use these codes instead of above
// activity.finish();
// java.lang.System.exit(0);
} else {
frameModule.topmost().goBack();
}
lastPress = java.lang.System.currentTimeMillis();
}
Hope this helps.
for Angular
import * as application from 'tns-core-modules/application';
exitapp=0
ngOnInit() {
application.android.on(application.AndroidApplication.activityBackPressedEvent, this.handleBackButton, this);
}
handleBackButton(args: any) {
this.ngZone.run(() => {
args.cancel = true;
if (this.routerExtensions.canGoBack()) {
this.routerExtensions.back();
}else{
this.exitapp++
this.getData.toast('Press again to exit')
if(this.exitapp==2){
application.android.foregroundActivity.finish();
}
setTimeout(()=>{
this.exitapp=0
},2000)
}
})
}

Performance issue when zooming (Leaflet 0.7.3)

I'm facing a performance problem with Leaflet (version 0.7.3). I'm working with an OSM map that I use to display a bunch of CircleMarkers linked by decorated Polylines (with arrow pattern every 25px). Loading take a little time but the main problem is that when I zoom the map I start facing severe lag (from the zoom level 16) and, beyond a certain limit (say 18 most of the time), browser just freeze and eventually crash (tested with chrome and firefox). I tried with a bunch of 1,000 linked markers, then I dropped to a set of around 100, but still the same concern... Of course, with 10 markers or less I don't have any problem.
Did you already face a similar trouble? How can I optimize Leaflet performances so that I can use an accurate zoom (beyond level 16) with more than 100 linked CircleMarkers ? I also wonder why performances are dropping so badly when zooming, while marker amount stay the same...
Thank you in advance for your answers,
Lenalys.
Cannot get the PolylineDecorator plugin to work on jsfiddle.
But here is the code that generate markers :
Map initialization :
var map;
function initializeMap(){
"use strict";
var layer;
var layer2;
function layerUrl(key, layer) {
return "http://wxs.ign.fr/" + key
+ "/geoportail/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&"
+ "LAYER=" + layer + "&STYLE=normal&TILEMATRIXSET=PM&"
+ "TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=image%2Fjpeg";
}
layer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png',
{
attribution: '© OpenStreetMap contributors',
maxZoom: 18
});
layer2 = L.tileLayer(
layerUrl(IGN_AMBIENTE_KEY, "GEOGRAPHICALGRIDSYSTEMS.MAPS"),
{attribution: '© IGN'}
);
var baseMaps = {
"Terrestre": layer,
"Bathymetrique": layer2
};
map = L.map('map', {
layers: [layer],
zoom: 8,
center: [42.152796, 9.139150],
zoomControl: false
});
L.control.layers(baseMaps).addTo(map);
//add zoom control with your options
L.control.zoom({
position:'topright' //topleft
}).addTo(map);
L.control.scale({
position:'bottomleft',
imperial : false
}).addTo(map);
}
Data Sample :
var jsonData ={"12":[{"id_stm_device":"7","individual_name":"cerf3","latitude":"42.657283333333","longitude":"9.42362","temperature":null,"pulse":null,"battery":"20","date_time":"2015-03-17 15:37:12"},
{"id_stm_device":"7","individual_name":"cerf3","latitude":"42.657381666667","longitude":"9.42365","temperature":null,"pulse":null,"battery":"20","date_time":"2015-03-17 16:42:16"},
{"id_stm_device":"7","individual_name":"cerf3","latitude":"42.657381666667","longitude":"9.4236933333333","temperature":null,"pulse":null,"battery":"20","date_time":"2015-03-17 17:47:21"},
{"id_stm_device":"7","individual_name":"cerf3","latitude":"42.657283333333","longitude":"9.4237383333333","temperature":null,"pulse":null,"battery":"20","date_time":"2015-03-17 19:57:23"}],
"13":[{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.61683","longitude":"9.4804633333333","temperature":"17.45","pulse":null,"battery":"80","date_time":"2015-04-08 07:45:20"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.538858333333","longitude":"9.48169","temperature":"14.37","pulse":null,"battery":"80","date_time":"2015-04-08 08:00:29"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.458748333333","longitude":"9.500225","temperature":"14.46","pulse":null,"battery":"80","date_time":"2015-04-08 08:15:49"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.3302","longitude":"9.5374583333333","temperature":"15.19","pulse":null,"battery":"80","date_time":"2015-04-08 08:31:05"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.170133333333","longitude":"9.5272116666667","temperature":"15.48","pulse":null,"battery":"80","date_time":"2015-04-08 08:46:20"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.07959","longitude":"9.47688","temperature":"15.97","pulse":null,"battery":"80","date_time":"2015-04-08 09:01:31"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.076163333333","longitude":"9.4828633333333","temperature":"20.42","pulse":null,"battery":"80","date_time":"2015-04-08 09:16:59"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.07194","longitude":"9.4908866666667","temperature":"17.36","pulse":null,"battery":"80","date_time":"2015-04-08 09:32:17"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.072583333333","longitude":"9.4901516666667","temperature":"17.36","pulse":null,"battery":"80","date_time":"2015-04-08 09:47:32"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.07238","longitude":"9.4904266666667","temperature":"19.38","pulse":null,"battery":"80","date_time":"2015-04-08 10:02:42"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.072298333333","longitude":"9.4904983333333","temperature":"17.46","pulse":null,"battery":"80","date_time":"2015-04-08 10:17:55"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.095093333333","longitude":"9.5148383333333","temperature":"17.47","pulse":null,"battery":"80","date_time":"2015-04-08 10:33:12"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.112881666667","longitude":"9.5133133333333","temperature":"19.3","pulse":null,"battery":"80","date_time":"2015-04-08 10:48:23"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.112875","longitude":"9.513285","temperature":"22.71","pulse":null,"battery":"80","date_time":"2015-04-08 11:03:57"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.141096666667","longitude":"9.5078216666667","temperature":"23.73","pulse":null,"battery":"80","date_time":"2015-04-08 11:19:12"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.282186666667","longitude":"9.5505183333333","temperature":"18.97","pulse":null,"battery":"80","date_time":"2015-04-08 11:34:28"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.405126666667","longitude":"9.531145","temperature":"20.71","pulse":null,"battery":"80","date_time":"2015-04-08 11:49:42"},
{"id_stm_device":"8","individual_name":"cerf5","latitude":"42.482063333333","longitude":"9.480665","temperature":"21.7","pulse":null,"battery":"80","date_time":"2015-04-08 12:05:07"}]}
var oJSON = JSON.parse(jsonData);
var colors = [
"#400080",
"#008000",
"#EC7600",
"#E40341",
"#0D5E5E",
"#919191",
"#FF3C9D",
"#A70A0E",
"#00BFBF",
"#7171FF"
];
var classes = [
"color1",
"color2",
"color3",
"color4",
"color5",
"color6",
"color7",
"color8",
"color9",
"color10"
];
var lastMarkers = [];
var layers = new Array();
var polyline;
var decorator;
window.graphicsDevices = [];
var offsetLatitude = 0.003333;
var offsetLongitude = 0.011666;
Marker instanciation :
function printGPSOnMap(oJSON){
var nbKeys = 0;
for (var key in oJSON) {
nbKeys++;
var classe = classes[(key-1)%classes.length];
var color = colors[(key-1)%colors.length];
var positionInfo = [];
if (oJSON.hasOwnProperty(key)) {
var aInfo = oJSON[key];
var marker;
var latlngs = Array();
var startMarker = lastMarkers[key];
if(startMarker !== undefined && startMarker != null) {
var myIcon = L.divIcon({className: "myCircle "+classe, iconSize : [ 20, 20 ] });
startMarker.setIcon(myIcon);
latlngs.push(startMarker.getLatLng());
}
for(var i = 0; i < aInfo.length; i++) {
var oInfos = aInfo[i];
var sIdIndividual = oInfos["id_individual"];
var sLongitude = oInfos["longitude"];
var sLatitude = oInfos["latitude"];
var sTemperature = oInfos["temperature"];
var sPulse = oInfos["pulse"];
var sBattery = oInfos["battery"];
var sDatetime = oInfos["date_time"];
var sIndividualName = oInfos["individual_name"];
var id_device = oInfos["id_stm_device"];
var popupMsg = "...";
latlngs.push(L.marker([sLatitude,sLongitude]).getLatLng());
marker = new MyCustomMarker([sLatitude,sLongitude], {
icon : L.divIcon({
className : "myCircle "+classe + ((i == aInfo.length-1) ? ' myCircleEnd' : ''),
iconSize : [ 20, 20 ]
})
});
marker.bindPopup(popupMsg, {
showOnMouseOver: true
});
marker.bindLabel(key, {
noHide: true,
direction: 'middle',
offset: [offset[0], offset[1]]
});
positionInfo.push(marker);
}
lastMarkers[key] = marker;
}
if(latlngs.length > 1)
{
polyline = L.polyline(latlngs, {className: classe, weight: 2,opacity: 0.4}).addTo(map);
decorator = L.polylineDecorator(polyline, {
patterns: [
// define a pattern of 10px-wide arrows, repeated every 20px on the line
{offset: 0, repeat: '25px', symbol: new L.Symbol.arrowHead({pixelSize: 10, pathOptions: {fillOpacity:
0.76, color: color, weight: 1}})}
]}).addTo(map);
}
if(!window.graphicsDevices.hasOwnProperty(key))
window.graphicsDevices[key] = [];
for(var i = 0; i < positionInfo.length; i++) {
window.graphicsDevices[key].push(positionInfo[i]);
positionInfo[i].addTo(map);
if(latlngs.length > 1){
window.graphicsDevices[key].push(polyline);
polyline.addTo(map);
window.graphicsDevices[key].push(decorator);
decorator.addTo(map);
}
}
}//foreach key
}
Code for the custom marker :
var MyCustomMarker = L.Marker.extend({
bindPopup: function(htmlContent, options) {
if (options && options.showOnMouseOver) {
// call the super method
L.Marker.prototype.bindPopup.apply(this, [htmlContent, options]);
// unbind the click event
this.off("click", this.openPopup, this);
// bind to mouse over
this.on("mouseover", function(e) {
// get the element that the mouse hovered onto
var target = e.originalEvent.fromElement || e.originalEvent.relatedTarget;
var parent = this._getParent(target, "leaflet-popup");
// check to see if the element is a popup, and if it is this marker's popup
if (parent == this._popup._container)
return true;
// show the popup
this.openPopup();
}, this);
// and mouse out
this.on("mouseout", function(e) {
// get the element that the mouse hovered onto
var target = e.originalEvent.toElement || e.originalEvent.relatedTarget;
// check to see if the element is a popup
if (this._getParent(target, "leaflet-popup")) {
L.DomEvent.on(this._popup._container, "mouseout", this._popupMouseOut, this);
return true;
}
// hide the popup
this.closePopup();
}, this);
}
},
_popupMouseOut: function(e) {
// detach the event
L.DomEvent.off(this._popup, "mouseout", this._popupMouseOut, this);
// get the element that the mouse hovered onto
var target = e.toElement || e.relatedTarget;
// check to see if the element is a popup
if (this._getParent(target, "leaflet-popup"))
return true;
// check to see if the marker was hovered back onto
if (target == this._icon)
return true;
// hide the popup
this.closePopup();
},
_getParent: function(element, className) {
var parent = null;
if(element != null) parent = element.parentNode;
while (parent != null) {
if (parent.className && L.DomUtil.hasClass(parent, className))
return parent;
parent = parent.parentNode;
}
return false;
}
});
Have you gauged performance in canvas mode?
Use L_PREFER_CANVAS = true before initializing your leaflet map container.Might be able to help you possibly.

Titanium up caret and menu item on actioinbar not working

I have the following code for a window. I'm trying to implement the up caret so a user can go to the previous window by tapping the title.
The up caret appears, but when i tap it, nothing happens, it only glows.
The menu item i added doesn't show either.
Is there something i'm not doing right?
function ConfirmOrder(_args) {
var actionBar;
var self = Ti.UI.createWindow({
title : "Confirm Order",
backgroundColor :'transparent',
orientation : 'vertical'
});
self.addEventListener("open", function() {
actionBar = self.activity.actionBar;
if (actionBar) {
actionBar.title = "Confirm Order";
actionBar.displayHomeAsUp = true; // shows up caret
actionBar.onHomeIconItemSelected = function() {
self.close();
};
} else {
alert('actionbar not accessible');
}
self.activity.onCreateOptionsMenu = function(e) {
var menu = e.menu;
var menuItem1 = menu.add({
title : L('settings'),
icon : "images/Setting.png",
showAsAction : Ti.Android.SHOW_AS_ACTION_IF_ROOM
});
menuItem1.addEventListener("click", function(e) {
alert("Settings Options Menu");
});
};
});
var imgView = Ti.UI.createImageView({
top : '3%',
image : Titanium.App.Properties.getString('image'),
height : '30%',
width : '60%'
});
var bottom = Titanium.UI.createView({
top : '37%',
height : '55%',
orientation : 'vertical',
touchEnabled : false,
backgroundImage : '/images/bg2.jpg',
});
var buttonsView = Titanium.UI.createView({
bottom : '0%',
height : '10%',
orientation : 'horizontal',
touchEnabled : false,
});
var confirmButton = Ti.UI.createButton({
right : '5%',
bottom : '10%',
width : '40%',
height : '70%',
color : 'white',
font : {fontSize:20, fontWeight:'bold', fontColor:'white', fontFamily:'Helvetica Neue'},
title : 'Confirm'
});
confirmButton.addEventListener('click', function(evt) {
// blah blah blah
});
var cancelButton = Ti.UI.createButton({
left : '5%',
bottom : '10%',
width : '40%',
height : '70%',
color : 'white',
font : {fontSize:20, fontWeight:'bold', fontColor:'white', fontFamily:'Helvetica Neue'},
title : 'Cancel'
});
cancelButton.addEventListener('click', function(evt) {
// blah blah blah
});
// add buttons to buttons container
buttonsView.add(confirmButton);
buttonsView.add(cancelButton);
// add parent containers to windows
self.add(imgView);
self.add(bottom);
self.add(buttonsView);
return self;
};
module.exports = ConfirmOrder;
Thanks all
I can't quite put my finger on it because it looks very similar to how i do it. However the only thing that i have different is that I have another check to ensure that you can get the activity, could it fall into this trap?
if (! self.getActivity()) {
Ti.API.error("Can't access action bar on a lightweight window.");
} else {
actionBar = self.activity.actionBar;
if (actionBar) {
actionBar.title = "Confirm Order";
actionBar.displayHomeAsUp = true; // shows up caret
actionBar.onHomeIconItemSelected = function() {
self.close();
};
} else {
alert('actionbar not accessible');
}
}
If the other options aren't working either I would remove them to see if they are somehow causing the up caret to error.
Hope that helps

In ExtJS, How to inject enableKeyEvents = true in component?

This is my code,
myText.enableKeyEvents = true; // **
myText.on('keyup', function(t){ console.log(t.getValue()); });
It not work, I think it may has some invoke method.
Any one has an idea ?
Full code
// function
var txfJump = function(txf){
var next = txf.nextSibling();
if(next.xtype == 'textfield'){
txf.enableKeyEvents = true;
txf.on('keyup', function(t, e){
if(t.getValue().length == t.maxLength){
next.focus();
}
});
txfJump(next);
}
};
// form
var p = new Ext.Panel({
title : 'test panel',
width : 400,
defaults: {
xtype : 'textfield',
},
items : [
{ ref : 'one', maxLength : 5 },
{ ref : 'two', maxLength : 5 },
{ ref : 'three',maxLength : 5 },
{
xtype : 'button',
text : 'SAMPLE'
},
{ ref : 'four', maxLength : 5 },
],
renderTo: Ext.getBody()
});
Ext.onReady(function(){
txfJump(p.one);
});
It's not possible without hackish tricks. Having read the TextField's source, i found out, that there is a private method initEvents, that sets up the callbacks for the html-elements if and only if enableKeyEvents is set. So, changing enableKeyEvents after initEvents was called has no effect, until it is called again.
To inject it, one could try to trigger a re-rendering of the component, or one could copy the behaviour of the relevant parts of TextField's initEvent. But there doesn't seem to be an official way.
you have to call txf.initEvents(), this needs to be called after txf.enableKeyEvents = true;
var txfJump = function(txf){
var next = txf.nextSibling();
if(next.xtype == 'textfield'){
txf.enableKeyEvents = true;
txf.initEvents(); //<----- this is what you have missing
txf.on('keyup', function(t, e){
if(t.getValue().length == t.maxLength){
next.focus();
}
});
txfJump(next);
}
You should pass "enableKeyEvents": true when getting new Ext.form.TextField instance. Here is the example usage
var textField = new Ext.form.TextField({
. // your configs
.
enableKeyEvents: true,
.
.
})

Resources