File Format for Phonegap [duplicate] - iphone

I'm trying to work with files on IOS, using Phonegap[cordova 1.7.0].
I read how to access files and read them on the API Documentation of phone gap. But I don't know, when the file is read where will it be written ? & How can I output the text, image, or whatever the text is containing on the iPhone screen?
Here's the code I'm using:
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.file(gotFile, fail);
}
function gotFile(file){
readDataUrl(file);
readAsText(file);
}
function readDataUrl(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as data URL");
console.log(evt.target.result);
};
reader.readAsDataURL(file);
}
function readAsText(file) {
var reader = new FileReader();
reader.onloadend = function(evt) {
console.log("Read as text");
console.log(evt.target.result);
};
reader.readAsText(file);
}
function fail(evt) {
console.log(evt.target.error.code);
}

As of Cordova 3.5 (at least), FileReader objects only accept File objects, not FileEntry objects (I'm not sure about prior releases).
Here's an example that will output the contents a local file readme.txt to the console. The difference here from Sana's example is the call to FileEntry.file(...). This will provide the File object needed for the call to the FileReader.readAs functions.
function readFile() {
window.requestFileSystem(window.LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getFile('readme.txt',
{create: false, exclusive: false}, function(fileEntry) {
fileEntry.file(function(file) {
var reader = new window.FileReader();
reader.onloadend = function(evt) {console.log(evt.target.result);};
reader.onerror = function(evt) {console.log(evt.target.result);};
reader.readAsText(file);
}, function(e){console.log(e);});
}, function(e){console.log(e);});
}, function(e) {console.log(e);});
}

That's what worked for me in case anyone needs it:
function ReadFile() {
var onSuccess = function (fileEntry) {
var reader = new FileReader();
reader.onloadend = function (evt) {
console.log("read success");
console.log(evt.target.result);
document.getElementById('file_status').innerHTML = evt.target.result;
};
reader.onerror = function (evt) {
console.log("read error");
console.log(evt.target.result);
document.getElementById('file_status').innerHTML = "read error: " + evt.target.error;
};
reader.readAsText(fileEntry); // Use reader.readAsURL to read it as a link not text.
};
console.log("Start getting entry");
getEntry(true, onSuccess, { create: false });
};

If you are using phonegap(Cordova) 1.7.0, following page will work in iOS, replace following template in index.html
<!DOCTYPE html>
<html>
<head>
<title>FileWriter Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-1.7.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
//
function onDeviceReady() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", {create: true, exclusive: false}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwriteend = function(evt) {
console.log("contents of file now 'some sample text'");
writer.truncate(11);
writer.onwriteend = function(evt) {
console.log("contents of file now 'some sample'");
writer.seek(4);
writer.write(" different text");
writer.onwriteend = function(evt){
console.log("contents of file now 'some different text'");
}
};
};
writer.write("some sample text");
}
function fail(error) {
console.log(error.code);
}
</script>
</head>
<body>
<h1>Example</h1>
<p>Write File</p>
</body>
</html>

Related

Show HTML in window with OK button in VSCode extension

I need to insert text after the cursor if the user agrees. I can't find anything in the documentation for my task.
Mission of my extension:
user writes code
then he calls the extension
it sends all code to a server
returns and shows some code in an additional window with an "OK" button
pressing the "OK" button inserts the server's response after the cursor
I have a problem with point 4. I can't find a method to show the additional window with an "OK" button.
All code from extension.js:
function activate(context) {
console.log('"showText" active');
const commandId = 'extension.showText'
let disposable = vscode.commands.registerCommand(commandId, function () {
const text = editor.document.getText()
let options = {
method: 'GET',
uri: 'http://example.com:8081/',
body: {
text: text
},
json: true
}
rp(options)
.then(function (respString) {
console.log(respString);
// what should I call here?
// vscode.window.showInformationMessage(respString);
})
.catch(function(err) {
console.log(err);
});
});
context.subscriptions.push(disposable);
}
exports.activate = activate;
function deactivate() {
console.log('showText disactive');
}
module.exports = {
activate,
deactivate
}
It is not duplicate of How to handle click event in Visual Studio Code message box? because I need HTML page. And this decision just shows text message with confim button.
My decision is:
webview-sample
Webview API
My example:
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const workspace = vscode.workspace;
const window = vscode.window;
const rp = require("request-promise");
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
/**
* #param {vscode.ExtensionContext} context
*/
function activate(context) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Extension activated');
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
const commandId = 'extension.showText'
let disposable = vscode.commands.registerCommand(commandId, function () {
const editor = window.activeTextEditor;
const text = editor.document.getText();
console.log('For editor "'+ editor._id +'"');
let options = {
method: 'POST',
uri: URL,
body: {
text: text
},
json: true
};
rp(options)
.then(function (res) { // res
const panel = window.createWebviewPanel(
'type_id', // Identifies the type of the webview. Used internally
'Title', // Title of the panel displayed to the user
vscode.ViewColumn.Two, // Editor column to show the new webview panel in.
{
// Enable scripts in the webview
enableScripts: true
} // Webview options. More on these later.
);
panel.webview.html = res;
// Handle messages from the webview
// закрывать когда выбираешь другое окошко
window.onDidChangeActiveTextEditor(
ev => {
// console.log(ev._id, editor._id, editor);
ev && ev._id && ev._id != editor._id && panel.dispose();
}
)
// закрывать когда закрываешь окно
workspace.onDidCloseTextDocument(
textDocument => {
console.log("closed => " + textDocument.isClosed)
panel.dispose();
},
null,
context.subscriptions
);
// любая клавиша кроме enter - фильтр по префиксу
// если enter - поиск подсказок
workspace.onDidChangeTextDocument(
ev => {
console.log(ev);
if (ev && ev.contentChanges && ev.contentChanges.length
&& (ev.contentChanges[0].text || ev.contentChanges[0].rangeLength)) {
// do smth
} else {
console.error('No changes detected. But it must be.', ev);
}
},
null,
context.subscriptions
);
panel.webview.onDidReceiveMessage(
message => {
switch (message.command) {
case 'use':
console.log('use');
editor.edit(edit => {
let pos = new vscode.Position(editor.selection.start.line,
editor.selection.start.character)
edit.insert(pos, message.text);
panel.dispose()
});
return;
case 'hide':
panel.dispose()
console.log('hide');
return;
}
},
undefined,
context.subscriptions
);
panel.onDidDispose(
() => {
console.log('disposed');
},
null,
context.subscriptions
)
})
.catch(function(err) {
console.log(err);
});
});
context.subscriptions.push(disposable);
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {
console.log('Extension disactivated');
}
module.exports = {
activate,
deactivate
}
The example of res:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
</head>
<body>
<p id="text">Text</p>
<button onclick="useAdvise()">Use</button>
<button onclick="hideAdvise()">Hide</button>
<script>
const vscode = acquireVsCodeApi();
function useAdvise(){
let text_ = $(document).find("#text").text();
vscode.postMessage({command: 'use',text: text_})
}
function hideAdvise(){
vscode.postMessage({command: 'hide'})
}
</script>
</body>
</html>

html2canvas screenshot size controle

I use this code from taking a screenshot & save it to pdf, I want to control the screenshot size like 400x700px.
<script type="text/javascript">
function genPDF() {
html2canvas(document.getElementById("all_content"), {
onrendered: function (canvas) {
var img = canvas.toDataURL("image/png");
var doc = new jsPDF();
doc.addImage(img, 'JPEG',20,20);
doc.save("Businesscard-<?php echo $sss_name; ?>.pdf");
}
});
}
</script>
Add height and width attribute to get you desired outcome :
function genPDF() {
html2canvas(document.getElementById("all_content"), {
onrendered: function (canvas) {
canvas.setAttribute('width',400); /*this->add*/
canvas.setAttribute('height',700); /*this->add*/
var img = canvas.toDataURL("image/png");
var doc = new jsPDF();
doc.addImage(img, 'JPEG');
doc.save("Businesscard-<?php echo $sss_name; ?>.pdf");
}
});
}

How to get rid of the loading progress in Facebook Instant Games with Phaser

I am developping a game for Facebook instant games with Phaser 2 CE, and i don't like the loading progress shown at the starting point, how can i get rid of it ?
I am using the default example given in the Quick Start page
FBInstant.initializeAsync()
.then(function() {
var images = ['phaser2'];
for (var i=0; i < images.length; i++) {
var assetName = images[i];
var progress = ((i+1)/images.length) * 100;
game.load.image('./assets/' + assetName + '.png');
// Informs the SDK of loading progress
FBInstant.setLoadingProgress(progress);
}
});
You can try something like given in this example like the code bellow then create your game, i know it's not clean but it works
FBInstant.initializeAsync()
.then(function() {
FBInstant.setLoadingProgress(50);
FBInstant.setLoadingProgress(100);
});
I have tryed something interesting but it doesn't answers the question according to this example
var sprite;
var PixelW = window.innerWidth;
var PixelH = window.innerHeight;
var game = new Phaser.Game(PixelW, PixelH, Phaser.AUTO, 'game', { preload: preload, create: create, update: update });
function preload() {
game.load.onLoadStart.add(loadStart, this);
game.load.onFileComplete.add(fileComplete, this);
startLoading();
}
function startLoading () {
game.load.image('logo1', 'assets/sprites/phaser1.png');
game.load.image('logo2', 'assets/sprites/phaser2.png');
game.load.image('dude', 'assets/sprites/phaser-dude.png');
game.load.image('ship', 'assets/sprites/phaser-ship.png');
game.load.image('mushroom', 'assets/sprites/mushroom.png');
game.load.image('mushroom2', 'assets/sprites/mushroom2.png');
game.load.image('diamond', 'assets/sprites/diamond.png');
game.load.image('bunny', 'assets/sprites/bunny.png');
game.load.start();
}
function create() {
game.stage.backgroundColor = 0x3b5998;
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
sprite = game.add.sprite(game.world.centerX, game.world.centerY, 'dude');
sprite.inputEnabled = true;
sprite.events.onInputDown.add(myHandler, this);
var text = game.add.text(10, 10, PixelW + " " + " " + PixelH, { font: "65px Arial", fill: "#ffff00", align: "center" });
}
function loadStart() {
}
// This callback is sent the following parameters:
function fileComplete(progress, cacheKey, success, totalLoaded, totalFiles) {
FBInstant.setLoadingProgress(progress);
//console.log(cacheKey + " " + progress);
}
function myHandler() {
sprite.anchor.setTo(0.5, 0.5);
sprite.x = Math.floor(Math.random() * PixelW);
sprite.y = Math.floor(Math.random() * PixelH);
}
function update() {
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script src="https://connect.facebook.net/en_US/fbinstant.6.0.js"></script>
<script src="phaser.min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<script type="text/javascript">
var p = 0;
FBInstant.initializeAsync()
.then(function() {
//FBInstant.setLoadingProgress(50);
//FBInstant.setLoadingProgress(100);
});
// Once all assets are loaded, tells the SDK
// to end loading view and start the game
FBInstant.startGameAsync()
.then(function() {
// Retrieving context and player information can only be done
// once startGameAsync() resolves
var contextId = FBInstant.context.getID();
var contextType = FBInstant.context.getType();
var playerName = FBInstant.player.getName();
var playerPic = FBInstant.player.getPhoto();
var playerId = FBInstant.player.getID();
// Once startGameAsync() resolves it also means the loading view has
// been removed and the user can see the game viewport
// game.start();
});
</script>
<div id="game"></div>
<script src="game.js" type="text/javascript"></script>
</body>
</html>
I use the methods below, I increase the loading percent after each file is loaded with Phaser. Also I include a try catch so that when testing local game play the game does not crash.
preload: function () {
try{
FBInstant.initializeAsync()
.then(function() {
});
}
catch(err) {
console.log('FB Instant Games Error: No Internet Connected');
}
this.load.image('gameItem1', 'assets/sprite/game_item1.png');
this.load.image('gameItem2', 'assets/sprite/game_item2.png');
}
And then...
startFacebookGame: function(){
try{
FBInstant.startGameAsync()
.then(function() {
// Retrieving context and player information can only be done
// once startGameAsync() resolves
var contextId = FBInstant.context.getID();
var contextType = FBInstant.context.getType();
var playerName = FBInstant.player.getName();
var playerPic = FBInstant.player.getPhoto();
var playerId = FBInstant.player.getID();
// Once startGameAsync() resolves it also means the loading view has
// been removed and the user can see the game viewport
});
}
catch(err) {
console.log('Analytics Connection Error');
}
},
fileComplete: function(progress, cacheKey, success, totalLoaded, totalFiles) {
try{
FBInstant.setLoadingProgress(progress);
}
catch(err) {
console.log('FB Instant Games progress Failed: No Internet Connected.');
}
//console.log("Progress: " + progress);
},
Here's how I do it. You can build out from there.
function preload() {
// Load some assets
FBInstant.setLoadingProgress(100)
}
function create() {
FBInstant
.startGameAsync()
.then(() => {
// Here you can now get users name etc.
console.log(this)
})
}
FBInstant.initializeAsync()
.then(() => {
new Phaser.Game({
type: Phaser.AUTO,
width: window.innerWidth,
height: window.innerHeight,
scene: {
preload,
create
}
})
})

how to use tern in codemirror to add my special text for every word in my editor?

I want to use tern (to add type for every word in my own language ) so I add to my html page this :
<link rel="stylesheet" href="plugin/codemirror/addon/tern/tern.css">
<link rel="stylesheet" href="plugin/codemirror/addon/dialog/dialog.css">
<script src="plugin/codemirror/addon/tern/tern.js"></script>
<script src="plugin/codemirror/addon/dialog/dialog.js"></script>
what I try :
I try alot But nothing work :( ,
I try to write :
"Ctrl-I": function(cm) { CodeMirror.tern.getServer(cm).showType(cm); }, but not work
and I try to write like demo:
<script>
function getURL(url, c) {
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if (xhr.status < 400) return c(null, xhr.responseText);
var e = new Error(xhr.responseText || "No response");
e.status = xhr.status;
c(e);
};
}
var server;
getURL("//ternjs.net/defs/ecma5.json", function(err, code) {
if (err) throw new Error("Request for ecma5.json: " + err);
server = new CodeMirror.TernServer({defs: [JSON.parse(code)]});
editor.setOption("extraKeys", {
"Ctrl-Space": function(cm) { server.complete(cm); },
"Ctrl-I": function(cm) { server.showType(cm); },
"Ctrl-O": function(cm) { server.showDocs(cm); },
"Alt-.": function(cm) { server.jumpToDef(cm); },
"Alt-,": function(cm) { server.jumpBack(cm); },
"Ctrl-Q": function(cm) { server.rename(cm); },
"Ctrl-.": function(cm) { server.selectName(cm); }
})
editor.on("cursorActivity", function(cm) { server.updateArgHints(cm); });
});
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: "javascript"
});
But nothing work
so can any body help me what functions I must to call to add my own tern to my own words ???

How to add annotations in video using video.js

is it possible to add annotation in my video using Video.js?
Below is my work out
<link href="http://vjs.zencdn.net/4.4/video-js.css" rel="stylesheet">
<script src="http://vjs.zencdn.net/4.4/video.js"></script>
<video id="my_video_1" class="video-js vjs-default-skin" controls
preload="auto" width="640" height="264" poster="my_video_poster.png"
data-setup="{}">
<source src="my_video.mp4" type='video/mp4'>
<source src="my_video.webm" type='video/webm'>
</video>
<script>
var Plugin = videojs.getPlugin('plugin');
var ExamplePlugin = videojs.extend(Plugin, {
constructor: function(player, options) {
Plugin.call(this, player, options);
player.on('timeupdate', function(){
var Component = videojs.getComponent('Component');
var TitleBar = videojs.extend(Component, {
constructor: function(player, options) {
Component.apply(this, arguments);
if (options.text)
{
this.updateTextContent(options.text);
}
},
createEl: function() {
return videojs.createEl('div', {
className: 'vjs-title-bar'
});
},
updateTextContent: function(text) {
if (typeof text !== 'string') {
text = 'hello world';
}
videojs.emptyEl(this.el());
videojs.appendContent(this.el(), text);
}
});
videojs.registerComponent('TitleBar', TitleBar);
var player = videojs('my-video');
player.addChild('TitleBar', {text: 'hellow people!'});
});
}
});
videojs.registerPlugin('examplePlugin', ExamplePlugin);
videojs('#my-video', {}, function(){
this.examplePlugin();
});
</script
</html>
//copy and paste this code it will surely work.