Is it possible to show a screen with a Nativescript
I searched the Internet for very little information.
Found the code.
const GameViewController = (UIViewController as any).extend(
{
get willPopCb() { return this._willPopCb; },
set willPopCb(x) { this._willPopCb = x; },
viewDidLoad: function(){
UIViewController.prototype.viewDidLoad.apply(this, arguments);
this.view = SKView.alloc().initWithFrame(this.view.bounds);
if(this.view instanceof SKView){
const scene = BattlefieldScene.alloc().initWithSize(
this.view.bounds.size
);
scene.view.backgroundColor = UIColor.alloc().initWithRedGreenBlueAlpha(0,1,0,1);
scene.scaleMode = SKSceneScaleMode.AspectFill;
this.view.presentScene(scene);
this.view.showsPhysics = false;
this.view.ignoresSiblingOrder = true;
this.view.showsFPS = true;
this.view.showsNodeCount = true;
}
},
willMoveToParentViewController: function(parent: UIViewController|null){
if(parent === null){
if(this.willPopCb){
this.willPopCb();
}
}
}
},
{
name: "GameViewController",
protocols: [],
exposedMethods: {}
}
);
Now, I can not understand how to display this controller
Thank you in advance
Try,
import * as utils from "tns-core-modules/utils/utils";
const gameViewController = GameViewController.alloc().init();
const app = utils.ios.getter(UIApplication, UIApplication.sharedApplication);
app.keyWindow.rootViewController.presentViewControllerAnimatedCompletion(gameViewController, true, null);
Related
I am trying to make an electron based browser whose search engine is the rising "you.com". I got the website to load and even managed to get some basic navigation buttons, forward and back, but I am struggling to incorporate a tab system some what chrome like - as in the fact that I should be able to have a toolbar at the top with tabs and I should be able to close and open etc.
On top of that I am trying to throw in a .crx chrome extension using electron extensions but that doesn't seem to work.
I installed electron tabs which was successful and then I went on to install electron extensions. I then tried to add the tab functionality so when I pressed the new tab button a new tab would be opened, but when I did this only text appeared, saying "tab1 tab2 etc. not an actual tab".
I think it is a problem with my main.js.
const { app, BrowserWindow } = require('electron');
const path = require('path');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
});
mainWindow.loadURL('https://you.com/');
mainWindow.webContents.on('dom-ready', () => {
mainWindow.webContents.executeJavaScript(`
// Create the navigation toolbar
const backButton = document.createElement('a');
backButton.href = '#';
backButton.innerHTML = '« Back';
backButton.onclick = () => { history.back(); return false; };
const forwardButton = document.createElement('a');
forwardButton.href = '#';
forwardButton.innerHTML = 'Forward »';
forwardButton.onclick = () => { history.forward(); return false; };
const toolbar = document.createElement('div');
toolbar.className = 'toolbar';
toolbar.appendChild(backButton);
toolbar.appendChild(forwardButton);
const body = document.getElementsByTagName('body')[0];
body.insertBefore(toolbar, body.firstChild);
// Create the new tab button
let tabCount = 1;
const newTabButton = document.createElement('a');
newTabButton.href = '#';
newTabButton.innerHTML = 'New Tab';
newTabButton.onclick = () => {
const tabName = 'Tab ' + tabCount++;
const tabButton = document.createElement('a');
tabButton.href = '#';
tabButton.innerHTML = tabName;
tabButton.onclick = () => {
mainWindow.loadURL('https://you.com/');
return false;
};
const removeTabButton = document.createElement('a');
removeTabButton.href = '#';
removeTabButton.innerHTML = 'X';
removeTabButton.style.float = 'right';
removeTabButton.onclick = () => {
const tabToRemove = document.getElementById(tabName);
const previousTab = tabToRemove.previousSibling;
const nextTab = tabToRemove.nextSibling;
if (previousTab) {
mainWindow.loadURL(previousTab.getAttribute('url'));
} else if (nextTab) {
mainWindow.loadURL(nextTab.getAttribute('url'));
} else {
mainWindow.loadURL('https://you.com/');
}
tabToRemove.remove();
return false;
};
const tab = document.createElement('a');
tab.href = '#';
tab.innerHTML = tabName;
tab.id = tabName;
tab.setAttribute('url', 'https://you.com/');
tab.onclick = () => {
mainWindow.loadURL(tab.getAttribute('url'));
return false;
};
tab.appendChild(removeTabButton);
const tabs = document.getElementById('tabs');
tabs.appendChild(tab);
return false;
};
// Add the new tab and navigation buttons to the toolbar
toolbar.appendChild(newTabButton);
// Create the tabs container
const tabs = document.createElement('div');
tabs.id = 'tabs';
tabs.className = 'tabs';
// Add the tabs container to the page
body.insertBefore(tabs, body.firstChild);
`);
});
}
app.whenReady().then(() => {
createWindow();
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
And the extension just does not show up or work.
It could also be my render.js.
var backButton = document.createElement('a');
backButton.href = '#';
backButton.innerHTML = '« Back';
backButton.onclick = () => { history.back(); return false; };
var forwardButton = document.createElement('a');
forwardButton.href = '#';
forwardButton.innerHTML = 'Forward »';
forwardButton.onclick = () => { history.forward(); return false; };
var toolbar = document.createElement('div');
toolbar.className = 'toolbar';
toolbar.appendChild(backButton);
toolbar.appendChild(forwardButton);
var body = document.getElementsByTagName('body')[0];
body.insertBefore(toolbar, body.firstChild);
Working navigation buttons
Not working tabs
I've got a project that is built on the serverless Twilio Voice JavaScript quickstart. Here's a link to the quickstart.
https://www.twilio.com/docs/voice/sdks/javascript/get-started#information
Below is the chunk of code where it allows the user to select an audio output device. Is it possible to select more than one audio output device, so my users can hear their phones ring through their speakers AND their headsets at the same time?
function updateDevices(selectEl, selectedDevices) {
selectEl.innerHTML = '';
device.audio.availableOutputDevices.forEach(function (device, id) {
let isActive = selectedDevices.size === 0 && id === 'default';
selectedDevices.forEach(function (device) {
if (device.deviceId === id) {
isActive = true;
}
});
const option = document.createElement('option');
option.label = device.label;
option.setAttribute('data-id', id);
if (isActive) {
option.setAttribute('selected', 'selected');
}
selectEl.appendChild(option);
});
}
function updateAllAudioDevices() {
if (device) {
updateDevices(speakerDevices, device.audio.speakerDevices.get());
updateDevices(ringtoneDevices, device.audio.ringtoneDevices.get());
}
}
async function getAudioDevices() {
await navigator.mediaDevices.getUserMedia({ audio: true });
updateAllAudioDevices.bind(device);
}
function updateOutputDevice() {
const selectedDevices = Array.from(speakerDevices.children)
.filter((node) => node.selected)
.map((node) => node.getAttribute('data-id'));
device.audio.speakerDevices.set(selectedDevices);
}
function updateRingtoneDevice() {
const selectedDevices = Array.from(ringtoneDevices.children)
.filter((node) => node.selected)
.map((node) => node.getAttribute('data-id'));
device.audio.ringtoneDevices.set(selectedDevices);
}
function bindVolumeIndicators(call) {
call.on('volume', function (inputVolume, outputVolume) {
let inputColor = 'red';
if (inputVolume < 0.5) {
inputColor = 'green';
} else if (inputVolume < 0.75) {
inputColor = 'yellow';
}
inputVolumeBar.style.width = `${Math.floor(inputVolume * 300)}px`;
inputVolumeBar.style.background = inputColor;
let outputColor = 'red';
if (outputVolume < 0.5) {
outputColor = 'green';
} else if (outputVolume < 0.75) {
outputColor = 'yellow';
}
outputVolumeBar.style.width = `${Math.floor(outputVolume * 300)}px`;
outputVolumeBar.style.background = outputColor;
});
}
This seems like it should be very standard behavior.
I can display a scrollable PDF with:
var container = document.getElementById('viewerContainer');
var pdfViewer = new PDFJS.PDFViewer({
container: container,
});
PDFJS.getDocument(DEFAULT_URL).then(function (pdfDocument) {
pdfViewer.setDocument(pdfDocument);
});
and I can display the PDF page by page with something like:
PDFJS.getDocument(URL_ANNOTATED_PDF_EXAMPLE).then(function getPdfHelloWorld(pdf) {
pdf.getPage(pageNumber).then(function getPageHelloWorld(page) {
var scale = 1.5;
var viewport = page.getViewport(scale);
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
But can't seem to find any reference in the API to both allow scrolling and jumping to a particular page, besides:
pdfViewer.currentPageNumber = 3;
which doesn't work...
So I found a way to make this work (mixed with a little Angular code, "$scope.$watch...") I now have other problems with font decoding. But here is a solution that might help someone else.
var me = this;
PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK;
var container = document.getElementById('capso-court-document__container');
function renderPDF(url, container) {
function renderPage(page) {
var SCALE = 1;
var pdfPageView = new PDFJS.PDFPageView({
container: container,
id: page.pageIndex + 1,
scale: SCALE,
defaultViewport: page.getViewport(SCALE),
textLayerFactory: new PDFJS.DefaultTextLayerFactory(),
annotationLayerFactory: new PDFJS.DefaultAnnotationLayerFactory()
});
pdfPageView.setPdfPage(page);
return pdfPageView.draw();
}
function renderPages(pdfDoc) {
var pageLoadPromises = [];
for (var num = 1; num <= pdfDoc.numPages; num++) {
pageLoadPromises.push(pdfDoc.getPage(num).then(renderPage));
}
return $q.all(pageLoadPromises);
}
PDFJS.disableWorker = true;
return PDFJS.getDocument(url)
.then(renderPages);
}
$scope.$watch(function() {
return {
filingUrl: me.filingUrl,
whenPageSelected: me.whenPageSelected,
};
}, function(newVal, oldVal) {
if (newVal.filingUrl) {
//newVal.filingUrl = URL_EXAMPLE_PDF_ANNOTATED;
//newVal.filingUrl = URL_EXAMPLE_PDF_ANNOTATED_2;
//newVal.filingUrl = URL_EXAMPLE_PDF_MULTI_PAGE;
if (newVal.filingUrl !== oldVal.filingUrl &&
newVal.whenPageSelected &&
newVal.whenPageSelected.page) {
scrollToPage(newVal.whenPageSelected.page);
}
//HACK - create new container for each newly displayed PDF
container.innerHTML = '';
var newContainerForNewPdfSelection = document.createElement('div');
container.appendChild(newContainerForNewPdfSelection);
renderPDF(newVal.filingUrl, newContainerForNewPdfSelection).then(function() {
if (newVal.whenPageSelected &&
newVal.whenPageSelected.page) {
scrollToPage(newVal.whenPageSelected.page);
}
});
}
}, true);
function scrollToPage(pageNumber) {
var pageContainer = document.getElementById('pageContainer' + pageNumber);
if (pageContainer) {
container.scrollTop = pageContainer.offsetTop;
} else {
console.warn('pdf pageContainer doesn\'t exist for index', pageNumber);
}
}
I'm developing an application for ipad and iphone using Titanium. You can navigate between different views. 1st view (the main view where you can go to another views) will be only on portrait mode, the rest of views can be in any orientation.
For this, I use different windows:
var winPortrait = Ti.UI.createWindow({
orientationModes : [Ti.UI.PORTRAIT],
fullscreen : false,
navBarHidden : true,
backgroundColor : "#00669c",
});
var appWindow = Titanium.UI.createWindow({
width : Ti.UI.FILL,
height : Ti.UI.FILL,
fullscreen : false,
navBarHidden : true,
backgroundColor : "#00669c",
backgroundImage : "Default-Portrait.png",
orientationModes : [Ti.UI.PORTRAIT, Ti.UI.LANDSCAPE_LEFT, Ti.UI.LANDSCAPE_RIGHT]
});
This works ok. When I open each window, orientation changes works ok.
To explain my problem, I'm going to specify the steps I do to reproduce it.
I'm viewing a screen on landscape:
I click to go to main view (portrait only) with device in landscape.
Main view is shown in portrait mode.
I rotate the device to portrait.
I go to the view again with device in portrait:
If I change device orientation, I receive the orientation change event, app detects is landscape mode and draw elements like landscape, but window or view (I don't know) its drawing like portrait, so it doesn't adjust correctly:
This doesn't occur on ios 7, but when I've tried with ios 5.1, it happens (I doesn't have a device with ios 6.x to try it)
Do you know how can I solve it or is a SO problem?
Thank you very much.
UPDATE
This is a simplification of the code I use:
In app.js:
var appWindow = Titanium.UI.createWindow({
width : Ti.UI.FILL,
height : Ti.UI.FILL,
fullscreen : false,
navBarHidden : true,
backgroundColor : "#00669c",
backgroundImage : "Default-Portrait.png",
orientationModes : [Ti.UI.PORTRAIT, Ti.UI.LANDSCAPE_LEFT, Ti.UI.LANDSCAPE_RIGHT]
});
var winPortrait = Ti.UI.createWindow({
orientationModes : [Ti.UI.PORTRAIT],
fullscreen : false,
navBarHidden : true,
backgroundColor : "#00669c",
});
var openView = function(e) {
currentView = e.win;
if (winPortraitHomeOpened && e.win != 'Home') {
appWindow.backgroundImage = '';
appWindow.addEventListener('open', function() {
//alert("appwindowopen")
if (appWindow != null) {
appWindow.height = Ti.UI.FILL;
appWindow.width = Ti.UI.FILL;
}
});
appWindow.open();
}
// Dependiendo de la vista, abre una ventana u otra
if (e.win == 'Home') {
winPortrait.open();
winPortraitHomeOpened = true;
setTimeout(function() {
var Home = require('/views/Home2');
activeView = Home.Constructor(winPortrait);
addActiveViewCloseWin();
}, 10);
} else if (e.win == 'test') {
var Test = require('/views/test/test');
activeView = Test.Constructor(appWindow, true);
}
if (currentView != 'Home') {
addActiveViewCloseWin();
}
};
var addActiveViewCloseWin = function() {
var anim_invisible = Titanium.UI.createAnimation({
opacity : 0,
duration : 300
});
var anim_visible = Titanium.UI.createAnimation({
opacity : 1,
duration : 300
});
if (winPortraitHomeOpened && currentView == 'Home') {
winPortrait.add(activeView);
} else {
appWindow.add(activeView);
}
if (lastActiveView != null) {
Trace.info("lastActiveView != null");
lastActiveView.animate(anim_invisible);
setTimeout(function() {
activeView.animate(anim_visible);
lastActiveView.close();
lastActiveView = activeView;
}, 300);
} else {
activeView.animate(anim_visible);
lastActiveView = activeView;
}
activeView.updateOrientation();
setTimeout(function() {
if (currentView == 'Home') {
appWindow.close();
} else {
if (winPortraitHomeOpened) {
winPortrait.close();
winPortraitHomeOpened = false;
}
}
}, 500);
};
Ti.Gesture.addEventListener('orientationchange', function(e) {
// Comprobar que ha cambiado de orientación. Se envían varios eventos juntos
var _currentOrientacion = 0;
if (utils.isLandscape())
_currentOrientacion = 1;
if (_currentOrientacion == orientacion) {
return;
}
orientacion = _currentOrientacion;
// Se actualiza las dimensiones y la orientación de los elementos
if (!winPortraitHomeOpened && !winPortraitConfOpened) {
if (appWindow != null) {
appWindow.height = Ti.UI.FILL;
appWindow.width = Ti.UI.FILL;
}
}
if (activeView != null) {
activeView.updateOrientation();
}
});
The code of Test.js:
exports.Constructor = function(parent) {
var view = Ti.UI.createView({
height : utils.getScreenHeight(),
width : utils.getScreenWidth(),
backgroundColor : 'red'
});
var cabeceraView = Cabecera.Constructor(view);
view.add(cabeceraView);
cabeceraView.setTitle('Prueba');
var backButton = Ti.UI.createImageView({
image : utils.imagesFolder() + "common/returnHome.png",
//top : view.height / 4,
left : utils.todp(8),
height : utils.todp(25),
width : utils.todp(65)
});
view.add(backButton);
backButton.addEventListener('click', function() {
openView({
win : 'Home'
});
});
var updateFechaCabecera = function() {
fechaView.setFecha('XXXX-XX-XX');
};
view.updateFechaCabecera = updateFechaCabecera;
var fechaView = Fecha.Constructor(view);
view.add(fechaView);
updateFechaCabecera();
// Vista ocupa todo salvo cabecera y fecha
var mainView = Ti.UI.createView({
height : utils.getScreenHeight() - utils.getCabeceraHeight() - utils.getFechaHeight(),
width : '100%',
top : utils.getCabeceraHeight() + utils.getFechaHeight(),
backgroundColor : "transparent",
});
view.add(mainView);
// Create a Label.
var aLabel = Ti.UI.createLabel({
text : 'aLabel',
color : 'pink',
font : {
fontSize : 40
},
textAlign : 'center'
});
// Add to the parent view.
mainView.add(aLabel);
var updateOrientation = function() {
Trace.info("updateOrientation de interconexines height width " + utils.getScreenHeight() + ' ' + utils.getScreenWidth());
view.height = utils.getScreenHeight();
view.width = utils.getScreenWidth();
if (utils.isPortrait()) {
aLabel.text = "PORTRAIT";
} else {
aLabel.text = "LANDSCAPE";
}
};
view.updateOrientation = updateOrientation;
var cerrar = function() {
Trace.info('cerrar Template');
view.visible = false;
view.hide();
if (cabeceraView != null) {
cabeceraView.close();
view.remove(cabeceraView);
cabeceraView = null;
}
if (fechaView != null) {
fechaView.close();
view.remove(fechaView);
fechaView = null;
}
// Eliminamos los elementos de la vista
if (view != null) {
utils.removeChildrens(view);
parent.remove(view);
};
view = null;
};
view.close = cerrar;
return view;
};
Have you tried to remove orientationModes in var winPortrait?
Your code should look like this:
var winPortrait = Ti.UI.createWindow({
fullscreen : false,
navBarHidden : true,
backgroundColor : "#00669c",
});
I'm writing an extension that involving adding an item to Firefox's context menu, but it appends to the end of the menu and I couldn't find any pointers customizing item's position using Addon SDK (insertBefore/insertAfter), I know how this can be done using XUL, but I'm trying to do it using Addon SDK or some sort of Addon SDK/XUL combination
This is the code snippet related to context menu
main.js
var pageMod = require("sdk/page-mod");
var data = require("sdk/self").data;
var tabs = require("sdk/tabs");
var cm = require("sdk/context-menu");
pageMod.PageMod({
include: "*.youtube.com",
contentScriptFile: data.url("page.js"),
onAttach: function (worker) {
worker.port.emit('link', data.url('convertbutton.png'));
}});
cm.Item({
label: "Convert File",
image: data.url("bighdconverterlogo128png.png"),
context: [
cm.URLContext(["*.youtube.com"]),
cm.PageContext()
],
contentScriptFile: data.url("menu.js"),
onMessage: function(vUrl){
tabs.open(vUrl);
}
});
data/menu.js
self.on("click", function(){
self.postMessage('http://hdconverter.co/' + 'c.php?url=' + window.location.href);
});
Thanks
i dont know about sdk but for non-sdk addons its easy. but because you dont have the boiler plate setup its going to look long. add this code to your addon at the bottom:
var positionToInsertMenu = 0; //set the position you want it at here
var myLabelText = 'Convert File';
const {interfaces: Ci,utils: Cu} = Components;
Cu.import('resource://gre/modules/Services.jsm');
/*start - windowlistener*/
var windowListener = {
//DO NOT EDIT HERE
onOpenWindow: function (aXULWindow) {
// Wait for the window to finish loading
let aDOMWindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
aDOMWindow.addEventListener("load", function () {
aDOMWindow.removeEventListener("load", arguments.callee, false);
windowListener.loadIntoWindow(aDOMWindow, aXULWindow);
}, false);
},
onCloseWindow: function (aXULWindow) {},
onWindowTitleChange: function (aXULWindow, aNewTitle) {},
register: function () {
// Load into any existing windows
let XULWindows = Services.wm.getXULWindowEnumerator(null);
while (XULWindows.hasMoreElements()) {
let aXULWindow = XULWindows.getNext();
let aDOMWindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
windowListener.loadIntoWindow(aDOMWindow, aXULWindow);
}
// Listen to new windows
Services.wm.addListener(windowListener);
},
unregister: function () {
// Unload from any existing windows
let XULWindows = Services.wm.getXULWindowEnumerator(null);
while (XULWindows.hasMoreElements()) {
let aXULWindow = XULWindows.getNext();
let aDOMWindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
windowListener.unloadFromWindow(aDOMWindow, aXULWindow);
}
//Stop listening so future added windows dont get this attached
Services.wm.removeListener(windowListener);
},
//END - DO NOT EDIT HERE
loadIntoWindow: function (aDOMWindow, aXULWindow) {
if (!aDOMWindow) {
return;
}
var contentAreaContextMenu = aDOMWindow.document.getElementById('contentAreaContextMenu');
var myMenuItem;
if (contentAreaContextMenu) {
var menuItems = contentAreaContextMenu.querySelector('menuitem');
[].forEach.call(menuItems, function(item) {
if (item.getAttribute('label') == myLabelText) {
myMenuItem = item;
}
});
contentAreaContextMenu.removeChild(myMenuItem);
if (contentAreaContextMenu.childNodes.length >= positionToInsertMenu) { //position is greater then number of childNodes so append to end
contentAreaContextMenu.appendChild(myMenuItem);
} else {
contentAreaContextMenu.insertBefore(myMenuItem, contentAreaContextMenu.childNodes[thePosition]);
}
}
},
unloadFromWindow: function (aDOMWindow, aXULWindow) {
if (!aDOMWindow) {
return;
}
var myMenuItem = aDOMWindow.document.getElementById('myMenuItem');
if (myMenuItem) {
myMenuItem.parentNode.removeChild(myMenuItem);
}
}
};
windowListener.register();
on unload of your addon add this:
windowListener.unregister();
i copied pasted from a template and modded it real fast. for position to be accurate you probably have to consider which menuitems are hidden and which are not