Post on 22-Jun-2015
description
Till Vollmer MindMeister
What is [Google] Gears?
Browser Plug-inLocal databaseLocal Store (URLs)Tools ClassesJavaScript LibraryVersion (09/01 2008 : V 0.4.X)
Plug-in for?
WindowsWindows XP/VistaFirefox 1.5+ and Internet Explorer 6.0+
Mac OS XMac OS X 10.4+Firefox 1.5+Safari (very! experimental)
LinuxLinux Firefox 1.5+32-bit processor (64-bit not supported)
ToolsDaten URL Inhalte
Classes in JavaScript
DatabaseFactory
LocalServer
TimerResultSet ManagedResourceStor
WorkerPool
ResourceStore
FileSubmitter
Desktop
HTTPRequest
Geolocation
Blob
<script src="gears_init.js"></script><script> if (!window.google || !google.gears) { location.href = "http://gears.google.com/?action=install&message=<your welcome message>" + "&return=<your website url>"; }</script>
Initialize/Instance
(function() { if (window.google && google.gears) { return; } var factory = null; if (typeof GearsFactory != 'undefined') { factory = new GearsFactory(); } else { try { factory = new ActiveXObject('Gears.Factory'); if (factory.getBuildInfo().indexOf('ie_mobile') != -1) { factory.privateSetGlobalObject(this); } } catch (e) { if ((typeof navigator.mimeTypes != 'undefined') && navigator.mimeTypes["application/x-googlegears"]) { factory = document.createElement("object"); factory.style.display = "none"; factory.width = 0; factory.height = 0; factory.type = "application/x-googlegears"; document.documentElement.appendChild(factory); } } } if (!factory) { return; } if (!window.google) { google = {}; }
if (!google.gears) { google.gears = {factory: factory}; }})();
gears_init.js
Factory class Object create(className, classVersion) string getBuildInfo() readonly attribute string version
Example:var db = google.gears.factory.create('beta.database');db.open('database-test');
Factory
className Google Gears class created
beta.database Database
beta.httprequest HttpRequest
beta.localserver LocalServer
beta.timer Timer
beta.workerpool WorkerPool
Database class void open([name]) ResultSet execute(sqlStatement, [argArray]) void close() readonly attribute int lastInsertRowId
ResultSet class boolean isValidRow() void next() void close() int fieldCount() string fieldName(int fieldIndex) variant field(int fieldIndex) variant fieldByName(string fieldName)
Database
var db = google.gears.factory.create('beta.database');db.open('database-test');db.execute('create table if not exists Test' + ' (Phrase text, Timestamp int)');db.execute('insert into Test values (?, ?)', ['Monkey!', new Date().getTime()]);var rs = db.execute('select * from Test order by Timestamp desc');
while (rs.isValidRow()) { alert(rs.field(0) + '@' + rs.field(1)); rs.next();}rs.close();
Database Example
Database Remarks
SQLiteFulltext SearchTransactions (begin, commit)Execute can fail (retry?)
db.execute('BEGIN');db.execute('INSERT INTO recipe_aux (dish, rating) VALUES (?, ?)', ['soup', 3]);db.execute('INSERT INTO recipe (rowid, dish, ingredients) ' + 'VALUES (last_insert_rowid(), ?, ?)', ['soup', 'meat carrots celery noodles']);db.execute('COMMIT');
Stores
ManagedResourceStoreURL to a manifestManifest states what will be fetched
ResourceStoreOn the fly storeDynamic things
Warning: if store is "enabled" it will deliver items all the time, also if online
LocalServer class boolean canServeLocally(string url) ResourceStore createStore(string name,...) ResourceStore openStore(string name, ...) void removeStore(string name, ...) ManagedResourceStore createManagedStore(string name,...) ManagedResourceStore openManagedStore(string name, ...) void removeManagedStore(string name,...)
LocalServer
ManagedResourceStore class readonly attribute string name readonly attribute string requiredCookie readwrite attribute boolean enabled readwrite attribute string manifestUrl readonly attribute int lastUpdateCheckTime readonly attribute int updateStatus readonly attribute string lastErrorMessage readonly attribute string currentVersion event void oncomplete(Object details) event void onerror(Error error) event void onprogress(Object details) void checkForUpdate()
ManagedResourceStore
ResourceStore class readonly attribute string name readonly attribute string requiredCookie readwrite attribute boolean enabled int capture(string urlOrUrlArray,completionCallback) void abortCapture(int captureId) void remove(string url) void rename(string srcUrl, string destUrl) void copy(string srcUrl, string destUrl) boolean isCaptured(string url) void captureFile(fileInputElement, url) string getCapturedFileName(url) string getHeader(string url, string name) string getAllHeaders(string url) FileSubmitter createFileSubmitter()
ResourceStore
{ // version of the manifest file format "betaManifestVersion": 1,
// version of the set of resources described in this manifest file "version": "my_version_string",
// optional // If the store specifies a requiredCookie, when a request would hit // an entry contained in the manifest except the requiredCookie is // not present, the local server responds with a redirect to this URL. "redirectUrl": "login.html",
// URLs to be cached (URLs are given relative to the manifest URL) "entries": [ { "url": "main.html", "src": "main_offline.html" }, { "url": ".", "redirect": "main.html" }, { "url": "main.js" } { "url": "formHandler.html", "ignoreQuery": true }, ]}
Manifest Example
var localServer=google.gears.factory.create('beta.localserver');var store=localServer.createManagedStore('test-store');store.manifestUrl='site-manifest.txt';store.checkForUpdate();
// site-manifest.txt{ "betaManifestVersion": 1, "version": "site_version_string", "entries": [ { "url": "site.html" }, { "url": "gears_init.js" } ]}
Example Store
WorkerPool
Own "Thread"UI Thread will not be disturbed (longer tasks)NO! DOM im Worker (window, document)
No XMLHttpRequest, setTimeout=> extra classes
Code isolation, but Parent/Child MessagingSame origin policy (can be overridden)
WorkerPool class callback onmessage(messageText, senderId, [messageObject:{text,sender,origin}]) callback onerror(errorObject:{message}) int createWorker(scriptText) int createWorkerFromUrl(scriptUrl) void sendMessage(messageText, destWorkerId) void allowCrossOrigin()
WorkerPool
// main.jsvar workerPool = google.gears.factory.create('beta.workerpool');workerPool.onmessage = function(a, b, message) { alert('Received message from worker ' + message.sender + ': ' + message.text);};var childWorkerId = workerPool.createWorkerFromUrl('worker.js');workerPool.sendMessage('Hello, world!', childWorkerId);
// worker.jsvar wp = google.gears.workerPool;wp.onmessage = function(a, b, message) { wp.sendMessage('Received: ' + message.text, message.sender);}
WorkerPool Example
HttpRequest class void open(method, url) void setRequestHeader(name, value) void send([postData]) void abort() string getResponseHeader(name) string getAllResponseHeaders() callback onreadystatechange readonly attribute int readyState readonly attribute string responseText readonly attribute int status readonly attribute string statusText
var request = google.gears.factory.create('beta.httprequest');request.open('GET', '/index.html');request.onreadystatechange = function() { if (request.readyState == 4) { console.write(request.responseText); }};request.send();
HTTPRequest
Timer class int setTimeout(fullScript, msecDelay) int setTimeout(function, msecDelay) int setInterval(fullScript, msecDelay) int setInterval(function, msecDelay) void clearTimeout(timerId) void clearInterval(timerId)
var timer = google.gears.factory.create('beta.timer');timer.setTimeout(function() { alert('Hello, from the future!'); }, 1000);
Timer
Desktop class bool createShortcut(name, url, icons, [description])
var desktop = google.gears.factory.create('beta.desktop');desktop.createShortcut("Test Application", "http://example.com/index.html", {"128x128": "http://example.com/icon128x128.png", "48x48": "http://example.com/icon48x48.png", "32x32": "http://example.com/icon32x32.png", "16x16": "http://example.com/icon16x16.png"}, "An application at http://example.com/index.html");
Desktop
Geolocation class readonly attribute Position lastPosition void getCurrentPosition(successCallback, [errorCallback], [options]) int watchPosition(successCallback, [errorCallback], [options]) void clearWatch(int watchId) boolean getPermission([siteName], [imageUrl], [extraMessage])
addtional classes: Position, Address, PositionOptions, PositionError
Geolocation
Blob classreadonly attribute int lengthBlob slice(offset, length)
Blob
Architecture of application
Source: Google
Modal vs. modeless
ModalUser switches between online and offlineSudden disconnect -> bad
ModelessComplex to implementBackground sync - CPU time?Do things twice (online AND offline)
Gears on Rails
Simple PluginTransformation of controller actions -> JSJSON responses
http://code.google.com/p/gearsonrails
Final remarks
SQL InjectionStores (enabled?)https/http problems
Future
ChromeFirefox 3SafariInternet Explorer ?
HTML 5 spec
Infos
http://code.google.com/apis/gearshttp://code.google.com/p/gearsonrails
Adobe Air
ConsRuntime needs installComplex security (sandboxing)Not all JS is "sandbox" readySigned code
ProsNearly desktop applicationMore possibilities
Tools
Commandline toolsadt - create a packageadl - run a project (without signing) air debug launcher
Anatomy of application
Descriptor fileHTML/Flash fileOther ressources
<?xml version="1.0" encoding="UTF-8"?><application xmlns="http://ns.adobe.com/air/application/1.0"> <id>examples.html.HelloWorld</id> <version>0.1</version> <filename>HelloWorld</filename> <initialWindow> <content>HelloWorld.html</content> <visible>true</visible> <width>400</width> <height>200</height> </initialWindow></application>
Descriptor file
<html><head> <title>Hello World</title> <script type="text/javascript" src="AIRAliases.js"></script> <script type="text/javascript"> function appLoad(){ air.trace("Hello World"); } </script></head><body onLoad="appLoad()"> <h1>Hello World</h1></body></html>
HTML file
Classes in AirAir.net: ServiceMonitor SocketMonitor URLMonitorData: EncryptedLocalStore SQLCollationType SQLColumnNameStyle SQLColumnSchema SQLConnection SQLError SQLErrorEvent SQLErrorOperation SQLEvent SQLIndexSchema SQLMode SQLResult SQLSchema SQLSchemaResult SQLStatement SQLTableSchema SQLTransactionLockType SQLTriggerSchema SQLUpdateEvent SQLViewSchemaDesktop: Clipboard ClipboardFormats ClipboardTransferMode DockIcon Icon InteractiveIcon NativeApplication NotificationType SystemTrayIconDisplay: BitmapData NativeMenu NativeMenuItem
Screen Stage StageDisplayState StageQualityEvents: ActivityEvent AsyncErrorEvent BrowserInvokeEvent DataEvent DRMAuthenticateEvent DRMStatusEvent Event EventDispatcher FileListEvent HTTPStatusEvent InvokeEvent IOErrorEvent NetStatusEvent OutputProgressEvent ProgressEvent SecurityErrorEvent StatusEvent TimerEventFile: File FileMode FileStreamFunctions: trace() navigateToURL() sendToURL()Geom: Matrix Point RectangleMedia: ID3Info Microphone Sound
SoundChannel SoundLoaderContext SoundMixer SoundTransformNative window: NativeWindow NativeWindowBounds... NativeWindowDisplay... NativeWindowDisplay... NativeWindowInitOpt... NativeWindowResize... NativeWindowSystemC... NativeWindowTypeNet: FileFilter LocalConnection NetConnection NetStream ObjectEncoding Responder SharedObject SharedObjectFlu.... Socket URLLoader URLLoaderDataFormat URLRequest URLRequestDefaults URLRequestHeader URLRequestMethod URLStream URLVariables XMLSocketSystem: Capabilities Security System UpdaterUi: Keyboard
KeyLocation MouseUtils: ByteArray CompressionAlgorithm Endian HTMLLoader HTMLPDFCapability Timer XMLSignatureValidator
MindMeister
Our decisionWe did not want to have Flash in thereAir is NOT Flash, but extra installGears seemed to be more easierWill be adopted in HTML5Chrome?
Thank you!