unity-chromium-extension-3.2.0+15.04.20150119/0000755000015301777760000000000012457233063021125 5ustar pbusernogroup00000000000000unity-chromium-extension-3.2.0+15.04.20150119/common-project-config.pri0000644000015301777760000000262312457232627026050 0ustar pbusernogroup00000000000000#----------------------------------------------------------------------------- # Common configuration for all projects. #----------------------------------------------------------------------------- # we don't like warnings... QMAKE_CXXFLAGS += -Werror # Disable RTTI QMAKE_CXXFLAGS += -fno-exceptions -fno-rtti TOP_SRC_DIR = $$PWD TOP_BUILD_DIR = $${TOP_SRC_DIR}/$(BUILD_DIR) include(coverage.pri) #----------------------------------------------------------------------------- # setup the installation prefix #----------------------------------------------------------------------------- INSTALL_PREFIX = /usr # default installation prefix # default prefix can be overriden by defining PREFIX when running qmake isEmpty(PREFIX) { message("====") message("==== NOTE: To override the installation path run: `qmake PREFIX=/custom/path'") message("==== (current installation path is `$${INSTALL_PREFIX}')") } else { INSTALL_PREFIX = $${PREFIX} message("====") message("==== install prefix set to `$${INSTALL_PREFIX}'") } INSTALL_LIBDIR = $${INSTALL_PREFIX}/lib isEmpty(LIBDIR) { message("====") message("==== NOTE: To override the library installation path run: `qmake LIBDIR=/custom/path'") message("==== (current installation path is `$${INSTALL_LIBDIR}')") } else { INSTALL_LIBDIR = $${LIBDIR} message("====") message("==== install prefix set to `$${INSTALL_LIBDIR}'") } unity-chromium-extension-3.2.0+15.04.20150119/coverage.pri0000644000015301777760000000363712457232627023452 0ustar pbusernogroup00000000000000# Coverage CONFIG(coverage) { OBJECTS_DIR = MOC_DIR = TOP_SRC_DIR = $$PWD LIBS += -lgcov QMAKE_CXXFLAGS += --coverage QMAKE_LDFLAGS += --coverage QMAKE_EXTRA_TARGETS += coverage cov QMAKE_EXTRA_TARGETS += clean-gcno clean-gcda coverage-html \ generate-coverage-html clean-coverage-html coverage-gcovr \ generate-gcovr generate-coverage-gcovr clean-coverage-gcovr clean-gcno.commands = \ "@echo Removing old coverage instrumentation"; \ "find -name '*.gcno' -print | xargs -r rm" clean-gcda.commands = \ "@echo Removing old coverage results"; \ "find -name '*.gcda' -print | xargs -r rm" coverage-html.depends = clean-gcda check generate-coverage-html generate-coverage-html.commands = \ "@echo Collecting coverage data"; \ "lcov --directory $${TOP_SRC_DIR} --capture --output-file coverage.info --no-checksum --compat-libtool"; \ "lcov --extract coverage.info \"*/messaging-host/*.cpp\" -o coverage.info"; \ "lcov --remove coverage.info \"moc_*.cpp\" --remove coverage.info \"tests/*.cpp\" -o coverage.info"; \ "LANG=C genhtml --prefix $${TOP_SRC_DIR} --output-directory coverage-html --title \"Code Coverage\" --legend --show-details coverage.info" clean-coverage-html.depends = clean-gcda clean-coverage-html.commands = \ "lcov --directory $${TOP_SRC_DIR} -z"; \ "rm -rf coverage.info coverage-html" coverage-gcovr.depends = clean-gcda check generate-coverage-gcovr generate-coverage-gcovr.commands = \ "@echo Generating coverage GCOVR report"; \ "gcovr -x -r $${TOP_SRC_DIR} -o $${TOP_SRC_DIR}/coverage.xml -e \".*/moc_.*\" -e \"tests/.*\" -e \".*\\.h\"" clean-coverage-gcovr.depends = clean-gcda clean-coverage-gcovr.commands = \ "rm -rf $${TOP_SRC_DIR}/coverage.xml" QMAKE_CLEAN += *.gcda *.gcno coverage.info coverage.xml } unity-chromium-extension-3.2.0+15.04.20150119/tests/0000755000015301777760000000000012457233063022267 5ustar pbusernogroup00000000000000unity-chromium-extension-3.2.0+15.04.20150119/tests/tests.pro0000644000015301777760000000005012457232627024153 0ustar pbusernogroup00000000000000TEMPLATE = subdirs SUBDIRS = \ unit unity-chromium-extension-3.2.0+15.04.20150119/tests/unit/0000755000015301777760000000000012457233063023246 5ustar pbusernogroup00000000000000unity-chromium-extension-3.2.0+15.04.20150119/tests/unit/unit.pro0000644000015301777760000000006212457232627024752 0ustar pbusernogroup00000000000000TEMPLATE = subdirs SUBDIRS = \ messaging-host unity-chromium-extension-3.2.0+15.04.20150119/tests/unit/messaging-host/0000755000015301777760000000000012457233063026176 5ustar pbusernogroup00000000000000unity-chromium-extension-3.2.0+15.04.20150119/tests/unit/messaging-host/tst_connection_host.pro0000644000015301777760000000031112457232627033006 0ustar pbusernogroup00000000000000include(messaging-host.pri) TEMPLATE = app TARGET = connection-host QT += \ core SOURCES = \ $${SRC_DIR}/connection.cpp \ connection-host.cpp HEADERS = \ $${SRC_DIR}/connection.h \ unity-chromium-extension-3.2.0+15.04.20150119/tests/unit/messaging-host/tst_webapps-handler.pro0000644000015301777760000000105112457232627032670 0ustar pbusernogroup00000000000000include(messaging-host.pri) TARGET = tst_webapps-handler QMAKE_CXXFLAGS += -std=c++11 CONFIG += \ link_pkgconfig \ qt QT += \ core \ testlib PKGCONFIG += \ glib-2.0 \ gobject-2.0 \ libunity_webapps-0.2 \ libunity-webapps-repository \ DEFINES += UCX_UNDER_TEST SOURCES += \ $${SRC_DIR}/webapps-handler.cpp \ tst_webapps-handler.cpp HEADERS += \ $${SRC_DIR}/webapps-handler.h check.commands = "xvfb-run -s '-screen 0 640x480x24' -a ./$${TARGET}" check.depends = $${TARGET} QMAKE_EXTRA_TARGETS += check unity-chromium-extension-3.2.0+15.04.20150119/tests/unit/messaging-host/tst_service.cpp0000644000015301777760000001170612457232627031246 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical Ltd. * * This file is part of unity-chromium-extension * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ #include "service.h" #include #include #include class Handler1: public QObject { Q_OBJECT public: Handler1() {} public Q_SLOTS: QVariantMap sayHello(const QVariantMap ¶ms); QVariantMap countArguments(const QVariantMap ¶ms); }; QVariantMap Handler1::sayHello(const QVariantMap ¶ms) { QVariantMap reply; reply.insert("greeting", QString("Hello %1").arg(params.value("name").toString())); return reply; } QVariantMap Handler1::countArguments(const QVariantMap ¶ms) { QVariantMap reply; // We subtract one, because that's the "method" field reply.insert("count", params.count() - 1); return reply; } class Handler2: public QObject { Q_OBJECT public: Handler2() {} public Q_SLOTS: QVariantMap listArguments(const QVariantMap ¶ms); }; QVariantMap Handler2::listArguments(const QVariantMap ¶ms) { QVariantMap reply; QStringList arguments = params.keys(); arguments.removeAll("method"); reply.insert("arguments", arguments); return reply; } class ServiceTest: public QObject { Q_OBJECT public: ServiceTest(); private Q_SLOTS: void testNoHandlers(); void testNonExisting(); void testHandling(); }; ServiceTest::ServiceTest(): QObject(0) { } void ServiceTest::testNoHandlers() { UnityWebapps::Service service; QSignalSpy messageHandled(&service, SIGNAL(messageHandled(const QVariantMap &))); QVariantMap message; message.insert("method", QString("sayHello")); message.insert("name", QString("Tom")); service.handleMessage(message); QCOMPARE(messageHandled.count(), 0); QVERIFY(service.isIdle()); } void ServiceTest::testNonExisting() { UnityWebapps::Service service; QSignalSpy messageHandled(&service, SIGNAL(messageHandled(const QVariantMap &))); Handler1 handler1; service.addHandler(&handler1); QVariantMap message; message.insert("method", QString("nonExistingMethod")); service.handleMessage(message); QCOMPARE(messageHandled.count(), 0); QVERIFY(service.isIdle()); // Add the second service (it still should fail) Handler2 handler2; service.addHandler(&handler2); service.handleMessage(message); QCOMPARE(messageHandled.count(), 0); QVERIFY(service.isIdle()); } void ServiceTest::testHandling() { UnityWebapps::Service service; QSignalSpy messageHandled(&service, SIGNAL(messageHandled(const QVariantMap &))); QSignalSpy isIdleChanged(&service, SIGNAL(isIdleChanged())); QVERIFY(service.isIdle()); Handler1 handler1; service.addHandler(&handler1); QVariantMap message; message.insert("method", QString("sayHello")); message.insert("name", QString("Tom")); service.handleMessage(message); QCOMPARE(messageHandled.count(), 1); QVariantMap reply = messageHandled.at(0).at(0).toMap(); QCOMPARE(reply.value("greeting").toString(), QString("Hello Tom")); messageHandled.clear(); QCOMPARE(isIdleChanged.count(), 2); isIdleChanged.clear(); QVERIFY(service.isIdle()); // Make sure it continues to work when we add a second handler Handler2 handler2; service.addHandler(&handler2); service.handleMessage(message); QCOMPARE(messageHandled.count(), 1); reply = messageHandled.at(0).at(0).toMap(); QCOMPARE(reply.value("greeting").toString(), QString("Hello Tom")); messageHandled.clear(); QCOMPARE(isIdleChanged.count(), 2); isIdleChanged.clear(); QVERIFY(service.isIdle()); // Test a method from the second handler message.clear(); message.insert("method", QString("listArguments")); message.insert("number", 1); message.insert("string", QString("Hello")); message.insert("boolean", false); service.handleMessage(message); QCOMPARE(messageHandled.count(), 1); reply = messageHandled.at(0).at(0).toMap(); QVERIFY(reply.contains("arguments")); QStringList expectedArguments; expectedArguments << "number" << "string" << "boolean"; QCOMPARE(reply.value("arguments").toStringList().toSet(), expectedArguments.toSet()); messageHandled.clear(); QCOMPARE(isIdleChanged.count(), 2); isIdleChanged.clear(); QVERIFY(service.isIdle()); } QTEST_MAIN(ServiceTest); #include "tst_service.moc" unity-chromium-extension-3.2.0+15.04.20150119/tests/unit/messaging-host/messaging-host.pri0000644000015301777760000000021712457232627031647 0ustar pbusernogroup00000000000000include(../../../common-project-config.pri) CONFIG += \ debug SRC_DIR = $${TOP_SRC_DIR}/messaging-host INCLUDEPATH += \ $${SRC_DIR} unity-chromium-extension-3.2.0+15.04.20150119/tests/unit/messaging-host/tst_webapps-handler.cpp0000644000015301777760000002426212457232627032663 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical Ltd. * * This file is part of unity-chromium-extension * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ extern "C" { #include #include } #include "webapps-handler.h" #include #include #include // {{{ mock implementations struct AppInfo { bool install; bool allowed; bool dontask; UnityWebappsApplicationStatus status; QString name; QString domain; }; QMap _mock_app_info; UnityWebappsApplicationRepository *unity_webapps_application_repository_new_default() { return (UnityWebappsApplicationRepository*)g_object_new(G_TYPE_OBJECT, 0); } gboolean unity_webapps_application_repository_prepare(UnityWebappsApplicationRepository *repository) { Q_UNUSED(repository); return true; } GList * unity_webapps_application_repository_resolve_url(UnityWebappsApplicationRepository *repository, const gchar *url) { Q_UNUSED(repository); if (!_mock_app_info.contains(QString::fromUtf8(url))) { return 0; } return g_list_append((GList*)0, (gpointer)g_strdup(url)); } UnityWebappsApplicationStatus unity_webapps_application_repository_get_resolved_application_status( UnityWebappsApplicationRepository *repository, const gchar *application ) { Q_UNUSED(repository); if (!_mock_app_info.contains(QString::fromUtf8(application))) { return UNITY_WEBAPPS_APPLICATION_STATUS_UNRESOLVED; } return _mock_app_info.value(QString::fromUtf8(application)).status; } const gchar * unity_webapps_application_repository_get_resolved_application_name(UnityWebappsApplicationRepository *repository, const gchar *application) { Q_UNUSED(repository); if (!_mock_app_info.contains(QString::fromUtf8(application))) { return 0; } return g_strdup(_mock_app_info.value(QString::fromUtf8(application)).name.toLocal8Bit().constData()); } const gchar * unity_webapps_application_repository_get_resolved_application_domain(UnityWebappsApplicationRepository *repository, const gchar *application) { Q_UNUSED(repository); if (!_mock_app_info.contains(QString::fromUtf8(application))) { return 0; } return g_strdup(_mock_app_info.value(QString::fromUtf8(application)).domain.toLocal8Bit().constData()); } gboolean unity_webapps_permissions_get_domain_allowed(const gchar *domain) { Q_FOREACH(const QString &key, _mock_app_info.keys()) { AppInfo appInfo = _mock_app_info.value(key); if (appInfo.domain == QLatin1String(domain)) { return appInfo.allowed; } } return false; } gboolean unity_webapps_permissions_get_domain_dontask(const gchar *domain) { Q_FOREACH(const QString &key, _mock_app_info.keys()) { AppInfo appInfo = _mock_app_info.value(key); if (appInfo.domain == QLatin1String(domain)) { return appInfo.dontask; } } return false; } void unity_webapps_permissions_dontask_domain(const gchar *domain) { Q_UNUSED(domain); } void unity_webapps_application_repository_install_application(UnityWebappsApplicationRepository *repository, const gchar *name, UnityWebappsApplicationRepositoryInstallCallback callback, gpointer user_data) { Q_UNUSED(repository); Q_UNUSED(name); Q_UNUSED(callback); Q_UNUSED(user_data); } // }}} class WebappsHandlerTest : public QObject { Q_OBJECT public: WebappsHandlerTest(); private Q_SLOTS: void initTestCase(); void cleanupTestCase(); void testUrlLoadedMalformedRequest(); void testUrlLoaded_data(); void testUrlLoaded(); void testDontAskMalformedRequest(); void testDontAsk_data(); void testDontAsk(); void testInstallMalformedRequest(); void testInstall_data(); void testInstall(); void testCreateApplicationDesktopName_data(); void testCreateApplicationDesktopName(); }; WebappsHandlerTest::WebappsHandlerTest(): QObject(0) { } void WebappsHandlerTest::initTestCase() { _mock_app_info.insert("https://mail.google.com/", { true, false, false, UNITY_WEBAPPS_APPLICATION_STATUS_AVAILABLE, "Gmail", "mail.google.com" }); _mock_app_info.insert("http://www.tumblr.com/", { false, true, true, UNITY_WEBAPPS_APPLICATION_STATUS_AVAILABLE, "Tumblr", "www.tumblr.com" }); } void WebappsHandlerTest::cleanupTestCase() { } void WebappsHandlerTest::testUrlLoadedMalformedRequest() { UnityWebapps::WebappsHandler handler; QVariantMap message; message.insert("method", QString("url_loaded")); QVariantMap reply = handler.url_loaded(message); QVERIFY(!reply.empty()); QCOMPARE(reply.value("error").toString(), QStringLiteral("malformed request")); } void WebappsHandlerTest::testUrlLoaded_data() { QTest::addColumn("url"); QTest::addColumn("available"); QTest::addColumn("appName"); QTest::addColumn("appDomain"); QTest::newRow("available") << "https://mail.google.com/" << true << "Gmail" << "mail.google.com"; QTest::newRow("not_available") << "http://www.example.com/" << false << "None" << "None"; } void WebappsHandlerTest::testUrlLoaded() { QFETCH(QString, url); QFETCH(bool, available); QFETCH(QString, appName); QFETCH(QString, appDomain); QVariantMap message; message.insert("method", QString("url_loaded")); message.insert("url", url); UnityWebapps::WebappsHandler handler; QVariantMap reply = handler.url_loaded(message); QVERIFY(!reply.empty()); QCOMPARE(reply.value("available").toBool(), available); if (available) { QCOMPARE(appName, reply.value("appName").toString()); QCOMPARE(appDomain, reply.value("appDomain").toString()); } } void WebappsHandlerTest::testDontAskMalformedRequest() { UnityWebapps::WebappsHandler handler; QVariantMap message; message.insert("method", QString("dont_ask")); QVariantMap reply = handler.url_loaded(message); QVERIFY(!reply.empty()); QCOMPARE(reply.value("error").toString(), QStringLiteral("malformed request")); } void WebappsHandlerTest::testDontAsk_data() { QTest::addColumn("url"); QTest::addColumn("available"); QTest::newRow("ask") << "https://mail.google.com/" << true; QTest::newRow("dont_ask") << "http://www.tumblr.com/" << true; QTest::newRow("no app") << "http://www.example.com/" << false; } void WebappsHandlerTest::testDontAsk() { QFETCH(QString, url); QFETCH(bool, available); UnityWebapps::WebappsHandler handler; QVariantMap message; message.insert("method", QString("dont_ask")); message.insert("url", url); QVariantMap reply = handler.dont_ask(message); QVERIFY(!reply.empty()); if (available) { QCOMPARE(reply.value("dont_ask").toBool(), true); } else { QCOMPARE(reply.value("dont_ask").toBool(), false); QCOMPARE(reply.value("available").toBool(), false); } } void WebappsHandlerTest::testInstallMalformedRequest() { UnityWebapps::WebappsHandler handler; QVariantMap message; message.insert("method", QString("install")); QVariantMap reply = handler.url_loaded(message); QVERIFY(!reply.empty()); QCOMPARE(reply.value("error").toString(), QStringLiteral("malformed request")); } void WebappsHandlerTest::testInstall_data() { QTest::addColumn("url"); QTest::addColumn("available"); QTest::addColumn("installed"); QTest::newRow("installs") << "https://mail.google.com/" << true << true; QTest::newRow("wont install") << "http://www.tumblr.com/" << true << false; QTest::newRow("no app") << "http://www.example.com/" << false << false; } void WebappsHandlerTest::testInstall() { QFETCH(QString, url); QFETCH(bool, available); QFETCH(bool, installed); QVariantMap message; message.insert("method", QString("install")); message.insert("url", url); UnityWebapps::WebappsHandler handler; QVariantMap reply = handler.install(message); QVERIFY(!reply.empty()); QCOMPARE(reply.value("installed").toBool(), installed); if (!available) { QCOMPARE(reply.value("available").toBool(), false); } } void WebappsHandlerTest::testCreateApplicationDesktopName_data() { QTest::addColumn("appName"); QTest::addColumn("appDomain"); QTest::addColumn("expected_uri"); // Behaviour QTest::newRow("strip whitespace") << "White Space Name" << "example.com" << "application://WhiteSpaceNameexamplecom.desktop"; QTest::newRow("strip special chars") << "%$special%^" << "example.com" << "application://specialexamplecom.desktop"; QTest::newRow("numbers allowed") << "13monkeys" << "example.com" << "application://13monkeysexamplecom.desktop"; QTest::newRow("combined") << "##12combined test$%67" << "example.com" << "application://12combinedtest67examplecom.desktop"; // Examples QTest::newRow("live example 1") << "FacebookMessanger" << "facebook.com" << "application://FacebookMessangerfacebookcom.desktop"; QTest::newRow("live example 2") << "Gmail" << "mail.google.com" << "application://Gmailmailgooglecom.desktop"; QTest::newRow("live example 3") << "GooglePlus" << "plus.google.com" << "application://GooglePlusplusgooglecom.desktop"; } void WebappsHandlerTest::testCreateApplicationDesktopName() { QFETCH(QString, appName); QFETCH(QString, appDomain); QFETCH(QString, expected_uri); UnityWebapps::WebappsHandler handler; QCOMPARE(handler.createApplicationDesktopName(appName, appDomain), expected_uri); } QTEST_MAIN(WebappsHandlerTest); #include "tst_webapps-handler.moc" unity-chromium-extension-3.2.0+15.04.20150119/tests/unit/messaging-host/tst_connection.cpp0000644000015301777760000000547512457232627031753 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical Ltd. * * This file is part of unity-chromium-extension * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ #include #include #include #include #include #include #include class ConnectionTest: public QObject { Q_OBJECT public: ConnectionTest(); void postMessage(const QByteArray &message); QByteArray readReply(); QVariantMap jsonToMap(const QByteArray &json); private Q_SLOTS: void init(); void cleanup(); void testMessaging(); private: QProcess m_process; }; ConnectionTest::ConnectionTest(): QObject(0) { m_process.setProgram("./connection-host"); m_process.setProcessChannelMode(QProcess::ForwardedErrorChannel); m_process.setReadChannel(QProcess::StandardOutput); } void ConnectionTest::postMessage(const QByteArray &message) { quint32 length = message.length(); m_process.write((char *)&length, sizeof(length)); m_process.write(message); } QByteArray ConnectionTest::readReply() { quint32 length; m_process.waitForReadyRead(); m_process.read((char *)&length, sizeof(length)); return m_process.read(length); } QVariantMap ConnectionTest::jsonToMap(const QByteArray &json) { QJsonDocument doc = QJsonDocument::fromJson(json); return doc.toVariant().toMap(); } void ConnectionTest::init() { m_process.start(); m_process.waitForStarted(); } void ConnectionTest::cleanup() { m_process.kill(); m_process.waitForFinished(); } void ConnectionTest::testMessaging() { postMessage("{\"msg\":\"hi\"}"); QVariantMap reply = jsonToMap(readReply()); QCOMPARE(reply.count(), 2); QCOMPARE(reply.value("count").toInt(), 1); QCOMPARE(reply.value("keys").toStringList(), QStringList() << "msg"); postMessage("{\"list\": [\"one\", \"two\"]," "\"name\": \"Tom\"," "\"number\": 23}"); reply = jsonToMap(readReply()); QCOMPARE(reply.count(), 2); QCOMPARE(reply.value("count").toInt(), 3); QSet expectedKeys; expectedKeys << "list" << "name" << "number"; QCOMPARE(reply.value("keys").toStringList().toSet(), expectedKeys); m_process.terminate(); } QTEST_MAIN(ConnectionTest); #include "tst_connection.moc" unity-chromium-extension-3.2.0+15.04.20150119/tests/unit/messaging-host/messaging-host.pro0000644000015301777760000000045412457232627031660 0ustar pbusernogroup00000000000000TEMPLATE = subdirs SUBDIRS = \ tst_connection \ tst_connection_host \ tst_inactivity_timer.pro \ tst_service.pro \ tst_webapps-handler.pro \ tst_connection.file = tst_connection.pro tst_connection_host.file = tst_connection_host.pro tst_connection.depends = tst_connection_host unity-chromium-extension-3.2.0+15.04.20150119/tests/unit/messaging-host/tst_service.pro0000644000015301777760000000047112457232627031261 0ustar pbusernogroup00000000000000include(messaging-host.pri) TARGET = tst_service QT += \ core \ testlib SOURCES += \ $${SRC_DIR}/service.cpp \ tst_service.cpp HEADERS += \ $${SRC_DIR}/service.h check.commands = "xvfb-run -s '-screen 0 640x480x24' -a ./$${TARGET}" check.depends = $${TARGET} QMAKE_EXTRA_TARGETS += check unity-chromium-extension-3.2.0+15.04.20150119/tests/unit/messaging-host/tst_inactivity_timer.pro0000644000015301777760000000053512457232627033205 0ustar pbusernogroup00000000000000include(messaging-host.pri) TARGET = tst_inactivity_timer QT += \ core \ testlib SOURCES += \ $${SRC_DIR}/inactivity-timer.cpp \ tst_inactivity_timer.cpp HEADERS += \ $${SRC_DIR}/inactivity-timer.h check.commands = "xvfb-run -s '-screen 0 640x480x24' -a ./$${TARGET}" check.depends = $${TARGET} QMAKE_EXTRA_TARGETS += check unity-chromium-extension-3.2.0+15.04.20150119/tests/unit/messaging-host/connection-host.cpp0000644000015301777760000000346312457232627032027 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical Ltd. * * This file is part of unity-chromium-extension * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ #include #include #include "connection.h" class Handler: public QObject { Q_OBJECT public: Handler(): QObject() {} bool openConnection(); public Q_SLOTS: void onMessageReceived(const QVariantMap &message); private: UnityWebapps::Connection m_connection; }; bool Handler::openConnection() { QObject::connect(&m_connection, SIGNAL(messageReceived(const QVariantMap &)), this, SLOT(onMessageReceived(const QVariantMap &))); return m_connection.open(); } void Handler::onMessageReceived(const QVariantMap &message) { // Generate a predictable reply QVariantMap reply; reply.insert("count", message.count()); QStringList keys = message.uniqueKeys(); reply.insert("keys", keys); m_connection.postMessage(reply); } int main(int argc, char **argv) { QCoreApplication app(argc, argv); Handler handler; if (!handler.openConnection()) { qCritical() << "Connection::open() failed!"; return EXIT_FAILURE; } return app.exec(); } #include "connection-host.moc" unity-chromium-extension-3.2.0+15.04.20150119/tests/unit/messaging-host/tst_connection.pro0000644000015301777760000000037112457232627031757 0ustar pbusernogroup00000000000000include(messaging-host.pri) TARGET = tst_connection QT += \ core \ testlib SOURCES += \ tst_connection.cpp check.commands = "xvfb-run -s '-screen 0 640x480x24' -a ./$${TARGET}" check.depends = $${TARGET} QMAKE_EXTRA_TARGETS += check unity-chromium-extension-3.2.0+15.04.20150119/tests/unit/messaging-host/tst_inactivity_timer.cpp0000644000015301777760000000542312457232627033170 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical Ltd. * * This file is part of unity-chromium-extension * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ #include "inactivity-timer.h" #include #include #include using namespace UnityWebapps; class Service: public QObject { Q_OBJECT Q_PROPERTY(bool isIdle READ isIdle NOTIFY isIdleChanged) public: Service(): QObject(), m_isIdle(true) {} bool isIdle() const { return m_isIdle; } void setIdle(bool idle) { if (idle == m_isIdle) return; m_isIdle = idle; Q_EMIT isIdleChanged(); } Q_SIGNALS: void isIdleChanged(); private: bool m_isIdle; }; class InactivityTimerTest: public QObject { Q_OBJECT public: InactivityTimerTest(); private Q_SLOTS: void testAlwaysIdle(); void testBecomeIdle(); void testManyServices(); }; InactivityTimerTest::InactivityTimerTest(): QObject(0) { } void InactivityTimerTest::testAlwaysIdle() { InactivityTimer timer(10); QSignalSpy timeout(&timer, SIGNAL(timeout())); Service service; timer.watchObject(&service); QVERIFY(timeout.wait(100)); } void InactivityTimerTest::testBecomeIdle() { InactivityTimer timer(10); QSignalSpy timeout(&timer, SIGNAL(timeout())); Service service; service.setIdle(false); timer.watchObject(&service); /* No signal should be emitted, as the service is not idle */ QVERIFY(!timeout.wait(100)); service.setIdle(true); QVERIFY(timeout.wait(100)); } void InactivityTimerTest::testManyServices() { InactivityTimer timer(50); QSignalSpy timeout(&timer, SIGNAL(timeout())); Service service1; timer.watchObject(&service1); Service service2; timer.watchObject(&service2); Service service3; service3.setIdle(false); timer.watchObject(&service3); /* No signal should be emitted, as service3 is not idle */ QVERIFY(!timeout.wait(100)); /* Now set it is as idle, but soon afterwards set service1 as busy */ service3.setIdle(true); QTest::qWait(10); service1.setIdle(false); QVERIFY(!timeout.wait(100)); service1.setIdle(true); QVERIFY(timeout.wait(100)); } QTEST_MAIN(InactivityTimerTest); #include "tst_inactivity_timer.moc" unity-chromium-extension-3.2.0+15.04.20150119/tests/extension/0000755000015301777760000000000012457233063024303 5ustar pbusernogroup00000000000000unity-chromium-extension-3.2.0+15.04.20150119/tests/extension/context-as-uid-in-js/0000755000015301777760000000000012457233063030165 5ustar pbusernogroup00000000000000unity-chromium-extension-3.2.0+15.04.20150119/tests/extension/context-as-uid-in-js/manifest.json0000644000015301777760000000115712457232616032675 0ustar pbusernogroup00000000000000{ "name": "Test - displays a given valid context as a proper UID", "version": "0.1.3", "description": "Test - displays a given valid context as a proper UID", "background_page": "background-page.html", "permissions": ["tabs", "http://*/*"], "plugins": [ /** The "path" property specifies the path to your plugin, relative to the manifest file. * The "public" property specifies whether your plugin can be accessed by regular web pages; * the default is false, meaning only your extension can load the plugin. */ { "path": "libunity_npapi_plugin.so", "public": true } ] } ././@LongLink0000000000000000000000000000015000000000000011211 Lustar 00000000000000unity-chromium-extension-3.2.0+15.04.20150119/tests/extension/context-as-uid-in-js/background-page.htmlunity-chromium-extension-3.2.0+15.04.20150119/tests/extension/context-as-uid-in-js/background-page.h0000644000015301777760000000116412457232616033374 0ustar pbusernogroup00000000000000 Unity Webapps Extension Test Background Page unity-chromium-extension-3.2.0+15.04.20150119/tests/extension/bulked-actions/0000755000015301777760000000000012457233063027207 5ustar pbusernogroup00000000000000unity-chromium-extension-3.2.0+15.04.20150119/tests/extension/bulked-actions/manifest.json0000644000015301777760000000107112457232616031712 0ustar pbusernogroup00000000000000{ "name": "Test - bulked actions test", "version": "0.1.3", "description": "Test - bulked actions test", "background_page": "background-page.html", "permissions": ["tabs", "http://*/*"], "plugins": [ /** The "path" property specifies the path to your plugin, relative to the manifest file. * The "public" property specifies whether your plugin can be accessed by regular web pages; * the default is false, meaning only your extension can load the plugin. */ { "path": "libunity_npapi_plugin.so", "public": true } ] } unity-chromium-extension-3.2.0+15.04.20150119/tests/extension/bulked-actions/background-page.html0000644000015301777760000000360112457232616033131 0ustar pbusernogroup00000000000000 Unity Webapps Extension Test Background Page unity-chromium-extension-3.2.0+15.04.20150119/po/0000755000015301777760000000000012457233063021543 5ustar pbusernogroup00000000000000unity-chromium-extension-3.2.0+15.04.20150119/po/Makefile.am0000644000015301777760000000016612457232616023605 0ustar pbusernogroup00000000000000po_files = $(shell ls *.py) $(shell ls *.po) $(shell ls *.pot) EXTRA_DIST = $(po_files) noinst_DATA = $(po_files) unity-chromium-extension-3.2.0+15.04.20150119/po/generate_reference_pot_file.py0000755000015301777760000000446212457232616027622 0ustar pbusernogroup00000000000000#!/usr/bin/python ## Generates the reference pot file based on the chromium's extension locale content ## Expects to be called w/ locale folder, e.g.: ## ## ./generate_reference_pot_file.py ./chromium-extension/_locales import sys def exit_with_error(msg): sys.stderr.write("*** Error: " + msg + "\n") sys.exit(1) if len(sys.argv) != 2: exit_with_error("Invalid usage") locales_folder = sys.argv[1] import os thispath = os.path.dirname(os.path.realpath(__file__)) # validation if not os.path.exists(locales_folder): exit_with_error("Invalid locale folder, does not exist") if not os.path.isabs(locales_folder): locales_folder = os.path.join (thispath, locales_folder) messages_json_reference_filename = os.path.join(locales_folder, "en/messages.json") if not os.path.exists(messages_json_reference_filename): exit_with_error("Invalid locale folder structure: no messages.json found for 'en' reference") # go def save_pot_file_for(filename, messages): import polib po = polib.POFile() po.metadata = { 'Project-Id-Version': 'PACKAGE VERSION', 'Report-Msgid-Bugs-To': 'you@example.com', 'POT-Creation-Date': '2007-10-18 14:00+0100', 'PO-Revision-Date': 'YEAR-MO-DA HO:MI+ZONE', 'Last-Translator': 'FULL NAME ', 'Language-Team': 'LANGUAGE ', 'Language': '', 'MIME-Version': '1.0', 'Content-Type': 'text/plain; charset=utf-8', 'Content-Transfer-Encoding': '8bit', } for i, message in enumerate(messages): entry = polib.POEntry(msgid=message, msgstr=u'', occurrences=[('messages.json', str(i))] ) po.append(entry) po.save(filename) def generate_pot(json_filename): import json pot_messages = [] try: content = json.loads(open(json_filename).read()) for k, v in content.iteritems(): if v.__class__ is type({}) and v.has_key('message'): pot_messages.append(v['message']) save_pot_file_for('unity_chromium_extension.pot', pot_messages) except Exception, e: exit_with_error("Cannot read & import messages.json file, " + str(e)) if __name__ == "__main__": generate_pot(messages_json_reference_filename) unity-chromium-extension-3.2.0+15.04.20150119/po/export_translations_to_chromium.py0000755000015301777760000000747412457232616030666 0ustar pbusernogroup00000000000000#!/usr/bin/python ## Export the current translations to chromium's extension ## Expects to be called w/ .po folder and chromium locale folder, e.g.: import sys import argparse def exit_with_error(msg): sys.stderr.write("*** Error: " + msg + "\n") sys.exit(1) parser = argparse.ArgumentParser() parser.add_argument("po-folder", help="location of the .po files") parser.add_argument("chrome-locals-folder", help="location of the chromium locale folder") args = vars (parser.parse_args(sys.argv[1:])) po_folder = args['po-folder'] chrome_locale_folder = args['chrome-locals-folder'] # validation import os if not os.path.exists(po_folder) or not os.path.exists(chrome_locale_folder): exit_with_error("Invalid paths") import os thispath = os.path.dirname(os.path.realpath(__file__)) def complete_path(p): if not os.path.isabs(p): p = os.path.join (thispath, p) return p po_folder = complete_path(po_folder) chrome_locale_folder = complete_path(chrome_locale_folder) messages_json_reference_filename = os.path.join(chrome_locale_folder, "en/messages.json") if not os.path.exists(messages_json_reference_filename): exit_with_error("Invalid chromium locale folder structure: no messages.json found for 'en' reference") def collect_po_files(po_folder): po_folder = complete_path(po_folder) return [entry for entry in os.listdir(po_folder) if os.path.isfile(os.path.join(po_folder, entry)) and entry.endswith('.po')] def save_message_json_file(): pass def parse_chromium_reference_locale(chromium_locale_folder): import json messages = {} try: content = json.loads(open(messages_json_reference_filename).read()) for k, v in content.iteritems(): if v.__class__ is type({}) and v.has_key('message'): # assume that messages are identical if messages.has_key(v['message']): print "Something is wrong, duplicated message strings found '", v['message'], "'" else: messages[v['message']] = (k, v) except Exception, e: exit_with_error("Cannot read & import messages.json file, " + str(e)) return messages def parse_po_files(po_folder): import polib po_files = collect_po_files(po_folder) if len(po_files) == 0: return {} r = [] for po_file in po_files: cur = {} filepath = os.path.join(po_folder, po_file) lang = os.path.splitext(os.path.basename(po_file))[0] cur['lang'] = lang po = polib.pofile(filepath) for entry in po: if entry.obsolete or entry.msgstr == '': continue cur.setdefault('translations', {})[entry.msgid] = entry.msgstr r.append(cur) return r def generate_chromium_json_files(po_folder, chromium_locale_folder): po_data = parse_po_files(po_folder) if len(po_data) == 0: print "No .po files found, or data not parsable" return en_reference_data = parse_chromium_reference_locale(chromium_locale_folder) import copy for po_datum in po_data: lang = po_datum['lang'] chromium_cur_lang_folder = os.path.join(chromium_locale_folder, lang) if not os.path.exists(chromium_cur_lang_folder): os.mkdir(chromium_cur_lang_folder) message_filename = os.path.join(chromium_cur_lang_folder, "messages.json") lang_translations = po_datum['translations'] messages = {} for k, v in en_reference_data.iteritems(): message = copy.deepcopy(v[1]) message['message'] = lang_translations[k] messages[v[0]] = message import json import codecs out = codecs.open(message_filename, "w+", "utf-8") out.write(json.dumps(messages)) if __name__ == "__main__": generate_chromium_json_files(po_folder, chrome_locale_folder) unity-chromium-extension-3.2.0+15.04.20150119/po/pt.po0000644000015301777760000000173012457232616022532 0ustar pbusernogroup00000000000000# Portuguese translation for unity-chromium-extension # Copyright (c) 2012 Rosetta Contributors and Canonical Ltd 2012 # This file is distributed under the same license as the unity-firefox-extension package. # FIRST AUTHOR , 2012. # msgid "" msgstr "" "Project-Id-Version: unity-chromium-extension\n" "Report-Msgid-Bugs-To: FULL NAME \n" "POT-Creation-Date: 2007-10-18 14:00+0100\n" "PO-Revision-Date: 2012-09-25 08:41+0000\n" "Last-Translator: Alexandre Abreu \n" "Language-Team: Portuguese \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Launchpad-Export-Date: 2012-09-21 08:40+0000\n" "X-Generator: Launchpad (build 15985)\n" #: messages.json:0 msgid "" "Would you like to install $NAME$ (from $DOMAIN$), for extra features and " "quicker access?" msgstr "" "Gostaria de instalar $NAME$ (a partir de $DOMAIN$), para funções estendidas e um " "acceso máis rápido?" unity-chromium-extension-3.2.0+15.04.20150119/po/fr.po0000644000015301777760000000172512457232616022522 0ustar pbusernogroup00000000000000# French translation for unity-chromium-extension # Copyright (c) 2012 Rosetta Contributors and Canonical Ltd 2012 # This file is distributed under the same license as the unity-firefox-extension package. # FIRST AUTHOR , 2012. # msgid "" msgstr "" "Project-Id-Version: unity-chromium-extension\n" "Report-Msgid-Bugs-To: FULL NAME \n" "POT-Creation-Date: 2007-10-18 14:00+0100\n" "PO-Revision-Date: 2012-09-25 08:41+0000\n" "Last-Translator: Alexandre Abreu \n" "Language-Team: French \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Launchpad-Export-Date: 2012-09-21 08:40+0000\n" "X-Generator: Launchpad (build 15985)\n" #: messages.json:0 msgid "" "Would you like to install $NAME$ (from $DOMAIN$), for extra features and " "quicker access?" msgstr "" "Voulez vous installer $NAME$ (depuis $DOMAIN$), pour des fonctionnalités étendues " "et un accès plus rapide?" unity-chromium-extension-3.2.0+15.04.20150119/po/unity_chromium_extension.pot0000644000015301777760000000102212457232616027434 0ustar pbusernogroup00000000000000# msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: you@example.com\n" "POT-Creation-Date: 2007-10-18 14:00+0100\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: \n" #: messages.json:0 msgid "" "Would you like to install $NAME$ (from $DOMAIN$), for extra features and " "quicker access?" msgstr "" unity-chromium-extension-3.2.0+15.04.20150119/unity-chromium-extension.pro0000644000015301777760000000046312457232627026662 0ustar pbusernogroup00000000000000include(common-project-config.pri) include(common-vars.pri) TEMPLATE = subdirs SUBDIRS = \ chromium-extension \ messaging-host \ tests tests.depends = messaging-host DISTNAME = $${PROJECT_NAME}-$${PROJECT_VERSION} dist.commands = "bzr export $${DISTNAME}.tar.bz2" QMAKE_EXTRA_TARGETS += dist unity-chromium-extension-3.2.0+15.04.20150119/common-vars.pri0000644000015301777760000000040012457232627024101 0ustar pbusernogroup00000000000000#----------------------------------------------------------------------------- # Common variables for all projects. #----------------------------------------------------------------------------- PROJECT_NAME = unity_webapps_chromium PROJECT_VERSION = 3.2 unity-chromium-extension-3.2.0+15.04.20150119/COPYING0000644000015301777760000010451312457232616022167 0ustar pbusernogroup00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/0000755000015301777760000000000012457233063024762 5ustar pbusernogroup00000000000000unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/crxmake.sh0000755000015301777760000000241112457232616026754 0ustar pbusernogroup00000000000000#!/bin/bash -e # # Purpose: Pack a Chromium extension directory into crx format if test $# -ne 2; then echo "Usage: crxmake.sh " exit 1 fi dir=$1 key=$2 name=$(basename "$dir") crx="$name.crx" pub="$name.pub" sig="$name.sig" zip="$name.zip" trap 'rm -f "$pub" "$sig" "$zip"' EXIT # zip up the crx dir cwd=$(pwd -P) (cd "$dir" && zip -qr -9 -X "$cwd/$zip" .) # signature openssl sha1 -sha1 -binary -sign "$key" < "$zip" > "$sig" # public key openssl rsa -pubout -outform DER < "$key" > "$pub" 2>/dev/null byte_swap () { # Take "abcdefgh" and return it as "ghefcdab" echo "${1:6:2}${1:4:2}${1:2:2}${1:0:2}" } crmagic_hex="4372 3234" # Cr24 version_hex="0200 0000" # 2 pub_len_hex=$(byte_swap $(printf '%08x\n' $(ls -l "$pub" | awk '{print $5}'))) sig_len_hex=$(byte_swap $(printf '%08x\n' $(ls -l "$sig" | awk '{print $5}'))) ( echo "$crmagic_hex $version_hex $pub_len_hex $sig_len_hex" | xxd -r -p cat "$pub" "$sig" "$zip" ) > "$crx" echo "Wrote $crx" # Output files to package in subdir "res" res="$cwd/res" mkdir -p $res echo "Result: $res" cp -f $crx $res/ eid=`cat $key | openssl rsa -pubout -outform DER | openssl dgst -sha256 | awk '{print $2}' | cut -c 1-32 | tr '0-9a-f' 'a-p'` echo "ID: $eid" cp -f unity-webapps.json $res/$eid.json unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/infobar.css0000644000015301777760000000053212457232616027117 0ustar pbusernogroup00000000000000body { background: -webkit-linear-gradient(#E9E9E9, #DADADA); font-family: Tahoma, Geneva, sans-serif; font-size: 13px; height: 36px; /* Infobars are limited to 36-72px */ margin: 0; overflow: hidden; padding-left: 6px; padding-right: 6px; padding-top: 5px; } img { padding-right: 6px; } button { padding-right: 10px; } unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/options.js0000644000015301777760000000115512457232616027020 0ustar pbusernogroup00000000000000function save_options() { var logging = document.getElementById("logging"); localStorage["logging"] = logging.checked; } function restore_options() { if ( ! window.localStorage) { alert ("Please enable local storage in order to access options"); document.getElementById('logging').disabled = true; return; } var logging = localStorage["logging"]; var loggingElt = document.getElementById("logging"); if (loggingElt) { loggingElt.checked = (logging == "true"); } } window.onload = function () { restore_options(); document.getElementById('logging').onclick = save_options; }; unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/browser.js0000644000015301777760000001266312457232627027020 0ustar pbusernogroup00000000000000/** * Handles all the related work to injecting the 'external' extension into the * content script (well, more precisely the current environment), and the proxy * responsbile for handling the API requests in a webapplication. * */ (function (currentWindow) { var aWindow = currentWindow; var plugin = null; var service = null; var api = { init: function (options) { options.url = window.location.href; options.hostname = window.location.hostname; options.host = window.location.host; options.protocol = window.location.protocol; chrome.runtime.sendMessage ( {method: "init_requested", options: options} , function (response) {}); } }; /** * Inserts a given script in the webpage. * Needs chrome.extension functionality. * * @param path of file to be injected (part of the extension) */ var insertScriptIntoWebpage = function (path) { var script = document.createElement ('script'); script.type = 'text/javascript'; script.src = chrome.runtime.getURL (path); document.getElementsByTagName("head")[0].appendChild (script); }; var injectApiProxy = function () { // 1. inject a piece of javascript proxying all the requests // to the unity webapps api insertScriptIntoWebpage('unity-api-page-proxy-builder-gen.js'); insertScriptIntoWebpage('unity-api-page-proxy.js'); function makeWebpageCallback (id) { // TODO/FIXME: add support for callback params (needed for DnD) return function () { var d = document.createElement ("textarea"); var e = document.createEvent ("Events"); d.style.cssText = "display:none;"; d.value = id; d.addEventListener ("unity-webapps-chromium-api-com-link-callback-called-ack" , function() { d.parentNode.removeChild (d); } , true); document.body.appendChild (d); e.initEvent ("unity-webapps-chromium-api-com-link-callback-called", false, true); d.dispatchEvent (e); }; }; // TODO: should be shared / generated w/ web page code var isIterableObject = function(obj) { if (obj === undefined || obj === null) { return false; } var t = typeof(obj); var types = {'string': 0, 'function': 0, 'number': 0, 'undefined': 0, 'boolean': 0}; return types[t] === undefined; }; /** * Wraps callback ids in proper callback that dispatch to the * webpage thru a proper event * */ function wrapCallbackIds (obj) { if ( ! isIterableObject(obj)) { return obj; } if (obj && obj.hasOwnProperty('callbackid') && obj.callbackid != null) { return makeWebpageCallback (obj.callbackid); } var ret = (obj instanceof Array) ? [] : {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { if (isIterableObject (obj[key])) { if (obj[key].callbackid != null) { ret[key] = makeWebpageCallback (obj[key].callbackid); } else { ret[key] = wrapCallbackIds (obj[key]); } } else { ret[key] = obj[key]; } } } return ret; }; // 2. open the communication mean between the two // TODO has the implicit knowledge of who's behind ... var dispatchActualFunctionCall = function (funcname, args) { var funcnames = funcname.split('.'); var reducetarget = api; // a bit hacky try { // Assumes that we are calling a 'callable' from a succession of objects funcnames.reduce ( function (prev, cur) { return typeof prev[cur] == "function" ? prev[cur].bind(prev) : prev[cur]; }, reducetarget).apply (null, args); } catch (err) { console.log ('Error while dispatching call to ' + funcnames.join('.') + ': ' + err); } }; document.addEventListener("unity-webapps-chromium-api-com-link" , function(event) { var from = event.target; if (from) { var type = from.getAttribute("data-eventType"); var args = JSON.parse(from.value); args = args.map (function (arg) { return wrapCallbackIds (arg); }); // Actuall call, e.g. 'Notification.showNotification("a","b") // being reduces to successive calls to associated objects: // Notification, showNotification // // TODO add proper error handling dispatchActualFunctionCall(type, args); } // send ack event to allow cleanup var ret = document.createEvent('Events'); ret.initEvent('unity-webapps-chromium-api-com-link-ack', true, false); from.dispatchEvent(ret); } , true); }; // handle the proxy side of the api which is being injected on the // webpage injectApiProxy(); } )(window); unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/build.sh0000755000015301777760000000100212457232616026414 0ustar pbusernogroup00000000000000#!/bin/bash -e CRX_FILENAME=`pwd`/../chromium-extension.crx PEM_FILENAME=`pwd`/../chromium-extension.pem if [ -e "$CRX_FILENAME" ] then rm -f "$CRX_FILENAME" fi #if [ -e "$PEM_FILENAME" ] #then # rm -f "$PEM_FILENAME" #fi if test -n "`which google-chrome`"; then google-chrome --no-message-box --pack-extension=`pwd` --pack-extension-key=../chromium-extension.pem else chromium-browser --no-message-box --pack-extension=`pwd` fi # not necessary # mv `pwd`/../unity-chromium-extension.crx . unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/unity-webapps.json.in0000644000015301777760000000015612457232627031100 0ustar pbusernogroup00000000000000{ '"external_crx": "$${EXTENSION_DIR}/$${EXTENSION_FILE}"', '"external_version": "$${PROJECT_VERSION}"' } unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/background-page.js0000644000015301777760000002277112457232627030367 0ustar pbusernogroup00000000000000/* Chromium Unity integration extension * * Copyright 2012 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . **/ var background_page = (function () { // Native messaging support var HOST_ADDRESS = 'com.canonical.webapp.installer'; var port = null; var host_callbacks = []; var portListener = function (msg) { callback = host_callbacks.pop(); if (callback === undefined) { return; } callback(msg); }; var portDisconnecter = function () { console.log('UCX: port disconnected'); port = null }; var sendNativeMessage = function (msg, callback) { console.log("UCX: sendnativemessage: port=" + port); if (port === null) { port = chrome.runtime.connectNative(HOST_ADDRESS); port.onMessage.addListener(portListener); port.onDisconnect.addListener(portDisconnecter); } host_callbacks.push(callback || function(m) {}); port.postMessage(msg); }; // Wake server to catalogue webapps sendNativeMessage({"method":"ping"}); ///////////////////////////////////////////////////////// // // Scafolding to keep track of data associated w/ infobar requests // (Chromium's structure imposes some kind of state being maintained // in order to communicate data) // //////////////////////////////////////////////////////// // // list of callback that are to be called asynchronously // per tab. Used in the user integration/installation resquests context. // // One thing to keep in mind is that one constraint, that bring some amount of // 'soundness' is that there is a hard limit (provided by the browser) of one infobar per tab. var user_infobar_request_callbacks = {}; var addInfobarRequestCallbackFor = function (infobarRequestId, callback, message, details) { user_infobar_request_callbacks[infobarRequestId] = { callback: callback, message: message, details: details }; }; var getDataIfAnyFor = function (infobarRequestId) { if (user_infobar_request_callbacks[infobarRequestId] === undefined) { return ""; } return { message: user_infobar_request_callbacks[infobarRequestId].message, details: user_infobar_request_callbacks[infobarRequestId].details }; }; var invokeAndRemoveCallbackIfAnyFor = function (infobarRequestId, arguments) { if (user_infobar_request_callbacks[infobarRequestId] === undefined) { return; } var callback = user_infobar_request_callbacks[infobarRequestId].callback; user_infobar_request_callbacks[infobarRequestId] = undefined; if (typeof(callback) === 'function') { callback(arguments); } }; /** * Performs a match on the list of loaded integration scripts * given a url. * */ var matchesIntegrationScripts = function (plugin, url, repo, windowInfos, callback) { sendNativeMessage({ "method" : "url_loaded", "url" : url }, function (response) { if (response.available) { addInfobarRequestCallbackFor( windowInfos.tabId, function (result) { if (result && result.integrate) { sendNativeMessage({ "method" : "install", "url" : url }) } else { sendNativeMessage({ "method" : "dont_ask", "url" : url }) } }, chrome.i18n.getMessage("integration_copy", [ response.appName, response.appDomain ]), null); chrome.infobars.show({ tabId: windowInfos.tabId, path: "infobar.html" }); } }); }; // {{{ main request handler /** * Handles & responds to content script requests. * */ var init_requested_stamps = {}; var contentScriptsRequestHandler = function (request, sender, callback) { var handlers = { get_extension_settings: function (request, sender, callback) { var settings = { logging: false, incognito: sender.tab.incognito }; try { if (window.localStorage) { settings.logging = localStorage['logging']; } } catch (e) { console.log("Error while trying to retrieve logging information: " + str(e)); } callback (settings); }, on_user_infobar_request_result: function (request, sender, callback) { invokeAndRemoveCallbackIfAnyFor (request.tabId, request); }, init_requested: function (request, sender, callback) { sendNativeMessage({ "method" : "url_loaded", "url" : request.options.url }, function (response) { if (response.available) { addInfobarRequestCallbackFor( sender.tab.id, function (result) { if (result && result.integrate) { sendNativeMessage({ "method" : "install", "url" : request.options.url }) } else { sendNativeMessage({ "method" : "dont_ask", "url" : request.options.url }) } }, chrome.i18n.getMessage("integration_copy", [ response.appName, response.appDomain ]), null); chrome.infobars.show({ tabId: windowInfos.tabId, path: "infobar.html" }); } }); } }; // validate request if (!request || !request.method) { callback({ error: "Invalid request structure" }); return true; } if (!sender) { callback({ error: "Invalid sender" }); return true; } if (typeof(request.method) != 'string' || request.method.length == 0) { callback({ error: "Invalid request method" }); return true; } console.log('Got request: ' + request.method); var handler = handlers [request.method]; if (handler !== undefined && typeof(handler) == 'function') { handler(request, sender, callback); return true; } return false; } // Main event handler and communication link // w/ content scripts chrome.runtime.onMessage.addListener (contentScriptsRequestHandler); // }}} /////////////////////////////////////////////////////////////////////// // // Window management related functions. In chromeless mode, we have specific // rules for tab management to make webapps feel more "native" than plain // web applications. // /////////////////////////////////////////////////////////////////////// var onTabChanged = function (tabId, windowId, url) { var onInstalled = function (installed, packageName, appName, appDomain) { }; console.log("onTabChanged: " + url); matchesIntegrationScripts( null, //plugin, url, null, // repo_, { windowId: windowId, tabId: tabId }, onInstalled ); }; chrome.tabs.onCreated.addListener( function(tab) { if (tab && tab.url) { onTabChanged(tab.id, tab.windowId, tab.url); } } ); chrome.tabs.onUpdated.addListener( function(tabId, changeInfo, tab) { console.log("onUpdated " + changeInfo.url); if (changeInfo && changeInfo.url) { onTabChanged(tabId, tab.windowId, changeInfo.url); } } ); /* * Returns a potential message associated with a tab id (infobar) */ return { getMessageForTabId: function (tabId) { return getDataIfAnyFor(tabId).message; } }; })(); unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/manifest.json.in0000644000015301777760000000174012457232627030077 0ustar pbusernogroup00000000000000{ '"name": "Unity WebApps Chromium extension"', '"manifest_version"': 2, '"minimum_chrome_version": "34.0"', '"content_security_policy"': '"script-src \'self\' chrome-extension://infobar.js \'unsafe-eval\'; object-src \'self\'"', '"version": "$${PROJECT_VERSION}"', '"description": "Unity Webapps Chromium integration"', '"web_accessible_resources"': [ '"browser.js"', '"unity-api-page-proxy-builder-gen.js"', '"unity-api-page-proxy.js"', '"infobar.js"', '"options.js"' ], '"icons"': { '"16": "skin/cof-16.png"', '"48": "skin/cof-48.png"' }, '"default_locale": "en"', '"background"': { '"page"': '"background-page.html"' }, '"permissions": ["tabs", "http://*/*", "infobars", "nativeMessaging"]', '"options_page": "options.html"', '"content_scripts"': [ { '"all_frames"': true, '"matches": [ "" ]', '"js": ["base-content-script.js"]', '"run_at": "document_end"' } ] } unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/options.html0000644000015301777760000000152212457232616027346 0ustar pbusernogroup00000000000000 Unity Webapps Options
Unity Webapps Integration Extension
Enable extension logging:
unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/skin/0000755000015301777760000000000012457233063025726 5ustar pbusernogroup00000000000000unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/skin/cof-48.png0000644000015301777760000000545112457232616027444 0ustar pbusernogroup00000000000000PNG  IHDR00WsRGBbKGD pHYs  tIME ntEXtCommentCreated with GIMPW IDATh޽yp?ow%ٖزqrpSP(L v @nsJi(w)W8`ZBIpt t` HXrHeIHZ_Rb;3{iW*Uu/Vd$ HT]/A)PЖ-cdUBDfj #RUAU""_KkW 2:T\R*CUTQYZ h ,YbYeVTPT%-6WZ+ c pwYU 6Y@XUDe|'OTu jiZU^J2F qb=UQ!~lh<a*"/rL7=Iu!-'n\B$PT2~$oZR_8}T]e_8*_8'w[BQqymsV` 6P;`G8=qb=h2= 󊈁 bUWZCmb,A5#Qj0- ?⟞oXU"LcJtՋ#;itw)#B>p&‹iK>8E0#>gySvƕL8MY3qz9+e WnZUw⛾?vWVEt:,?`qhј',Sg moʷF #wy("tw"?˥|EOPRl{a^x ,.. NEfWZ?B|a(yY/ ~u'MlAbَαdhe-$ "~`jr9PvE'"DZFOxx:@tuDO!jN/.X]lxs|2izg@ fU9u"G": }NjchtK2ғ.F9 Efj'U|gֲǫI|FߟLi+}Qec.o-#Nd#<3 I_㝶g@ ˍO)K6隱MDpw3׹g)Haq>$*8v˔!aiXa3alB+&ĉ@GN("ӹ:+@ilq x|5j'0,_^$]F0J2!SDo[L fE5bZSeʓ7@y)%6d1Tݕm]tw B_~_„3"T |{}xmؑm9@1۝($fsfbW>GQՆTuKK"U跔 M;h'Dw/)k)qU*UW?@1g95 >Iwx.۽Q|с^Zٴ4M?T+QTαIRzSoo fϥ稹yCcò pWVKYt߬ܽ,޵og|o~:z[>&޶x'gR;SټG'B9Eg`s'5RZD [ÜPŷF X9G=FxbmS 3b _YY"TRU>-|p.]Eh zTѷwR|oeҏE$ CBȣ|!IvlbbWQ.2b& :ғ.ELFͽ"9*@8mWVdJO#NªRDV7qOo;yhbo۶ gq6u"PC*W#Ř`8nȶTlaNJͲHWQչ;6T>y00|HQ `GR}DJ0|9dj3`y5UUEU 69^O jTIv%K:/\|vР*y*qWL-ub0*:UE<>UYC5;ݎ?DR˃a{|usU:68J̪V{MEf LC]}?쌏;%@ Td8c %F۶mFL;rIj3"{ hjߠ_3e 5[S݀Q롁N R%FDq 6w~S]XUR#L@gT ZP]"Eu7r&蠟YIENDB`unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/skin/cof-16.png0000644000015301777760000000151312457232616027432 0ustar pbusernogroup00000000000000PNG  IHDRasBIT|dIDAT8e_hu?}߳xΖwb6; 4tc (Pf&)d ʠd BԙM9j4u2v}n8s>U2vUl;mN@s剴?ق\%~7V`*|ɟ`%oX1!Qb2x1V;쪖ũıAe ݿݭ0M7ly{ebj- ]$O*+ɰj=l`ZÊWq~  )MFʼnQ|mtbyۧ@Pu3g;図5.}lٞmp3/Ƹ&ƈuQ 5D|jC:wC'kN!D("/HSb%nH ,qBA -t!4ss-Kg'rCS/bw*Mf5nj1, #͐^۩ 'V_LWVs)d N{-T4FdӠ55JSdOب1ώ.vX̻ {'0': 1, '1': 2, '2': 3} d.value = JSON.stringify ( data.map ( function (datum) { return transformCallbacksToIds (datum); } ) ); d.addEventListener ("unity-webapps-chromium-api-com-link-ack" , function() { if (callback) callback (d.value); d.parentNode.removeChild (d); } , true); d.setAttribute ("data-eventType", type); document.body.appendChild (d); e.initEvent ("unity-webapps-chromium-api-com-link", false, true); d.dispatchEvent (e); }; document.addEventListener ("unity-webapps-chromium-api-com-link-callback-called" , function(event) { var from = event.target; if (from) { if (from.value) { var callback = callbackmanager.get(from.value); if (callback) { callback (); } } var ret = document.createEvent('Events'); ret.initEvent('unity-webapps-chromium-api-com-link-callback-called-ack', true, false); from.dispatchEvent(ret); } } , true); var api = UnityWebappsApiPageProxyBuilder(sendToApi); function unity() { } unity.prototype = { __proto__: window.external, getUnityObject: function (version) { console.log ('Proxy: getUnityObject called with version ' + version); if (version === 1) return api; throw new Error("incorrect version"); } }; window.external = new unity(); sendApiCreatedAcknowledge(); } , 0); unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/base-content-script.js0000644000015301777760000000561512457232627031220 0ustar pbusernogroup00000000000000/* Chromium Unity integration extension * * Copyright 2013 Canonical Ltd. * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . **/ (function () { var performContentScriptInitialization = function (loggerf) { UnityContentScriptApi = { getExtensionSettings: function (callback) { chrome.runtime.sendMessage ({method: "get_extension_settings"} , function (response) { if (response && response.error) { // TODO log return; } callback (response); }); }, }; // // Initialize if needed // var initializeIntegrationScriptIfNeededForUrl = function (loggerf) { var logger = loggerf || function (m) {}; // does the unity script injection + user script if necessary logger ('Base content script, started on url: ' + document.URL); var getUserScriptContent = function (url) { var content = null; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { content = xhr.responseText; } }; // mmh blocking xhr.open("GET", url, false); try { xhr.send(); } catch(e) { logger ('Could not load user script content from: ' + url); } return content; }; /** * Injects a given javascript file in the current content script * * @param path path *in the current extension* of the required file */ var require = function (path) { try { eval.call (window, getUserScriptContent (chrome.runtime.getURL (path))); } catch (e) { logger ('Failed to add required dependancy: ' + path + ', ' + e); } }; UnityContentScriptApi.getExtensionSettings ( function (settings) { // Bail out if in incognito mode. if (settings && settings.incognito) { return; } require ("browser.js"); }); }; // initializeIntegrationScriptIfNeededForUrl initializeIntegrationScriptIfNeededForUrl (loggerf); }; // performContentScriptInitialization // only do it for the top window, not the iframes performContentScriptInitialization ( function (msg) { if (top === self) { console.log ("Content script: " + msg); } } ); } ) (); unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/background-page.html0000644000015301777760000000043012457232627030703 0ustar pbusernogroup00000000000000 Unity Webapps Extension Background Page unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/_locales/0000755000015301777760000000000012457233063026543 5ustar pbusernogroup00000000000000unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/_locales/en/0000755000015301777760000000000012457233063027145 5ustar pbusernogroup00000000000000unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/_locales/en/messages.json0000644000015301777760000000041112457232616031646 0ustar pbusernogroup00000000000000{ "integration_copy": { "message": "Would you like to install $NAME$ (from $DOMAIN$), for extra features and quicker access?", "placeholders": { "name": { "content": "$1" }, "domain": { "content": "$2" } } } }unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/unity-api-page-proxy-builder-gen.js0000644000015301777760000003570012457232627033535 0ustar pbusernogroup00000000000000var UnityWebappsApiPageProxyBuilder = function(backend) { var dummy = true; var unity = { context: dummy, contextReady: dummy }; var uwa = { ContextActionCallbackType: null }; var CallbackManager = { makeCallback: function (dumd, func) { return func; } }; function checkString(str, allowUndef) { if (allowUndef && str == undefined) { return; } if (!str || typeof(str) !== 'string') { throw new TypeError("incorrect argument"); } } var findName = function (func, prefix, obj) { if (!prefix) { return findName(func, 'Unity.', api); } var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { if (typeof(keys[i]) !== 'string') { continue; } var descr = Object.getOwnPropertyDescriptor(obj, keys[i]); if (descr.value === func) { return prefix + keys[i]; } if (descr.value instanceof Object) { var res = findName(func, prefix + keys[i] + '.', obj[keys[i]]); if (res) return res; } if (obj.__lookupGetter__(keys[i]) === func) { return prefix + keys[i]; } if (obj.__lookupSetter__(keys[i]) === func) { return prefix + keys[i]; } } return null; }; var stringify = function (obj) { if (obj === undefined) return obj; if (obj === null) return obj; if (typeof(obj) == 'string') return obj; if (typeof(obj) == 'number') return obj; if (typeof(obj) == 'function') return String(obj); var dump = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) dump[i] = stringify(obj[i]); } return dump; }; var stringifyArgs = function (obj) { var args = []; for (var i = 0; i < obj.length; i++) { args.push(stringify(obj[i])); } var res = JSON.stringify(args); return res.substr(1, res.length - 2); }; var createArgumentsSanitaizer = function (func, argsDesc, callback) { return function () { var realArgs = arguments; var name = findName(arguments.callee); var k = 0; function argumentSanitaizer(desc, arg) { if (!desc) { throw new InternalError("argument description is null"); } if (desc.dummy) { k--; return null; } if (desc.array) { if (!(desc.array instanceof Object) || !(desc.array.element instanceof Object)) { throw new InternalError("invalid argument description"); } try { for (var j = 0; j < arg.length; j++) { argumentSanitaizer(desc.array.element, arg[j]); } } catch (x) { throw new TypeError("incorrect argument"); } return arg; } if (desc.obj) { if (!(desc.obj instanceof Object)) { throw new InternalError("invalid argument description"); } var res = {}, i; for (i in desc.obj) { if (desc.obj.hasOwnProperty(i)) { res[i] = argumentSanitaizer(desc.obj[i], arg[i]); } } return res; } if (desc.str) { if (desc.allowNull && !arg) { return null; } checkString(arg, false); return arg; } if (desc.number) { if (typeof(arg) !== 'number' && typeof(arg) !== 'boolean') throw new TypeError("incorrect argument"); return arg; } if (!desc.type) { throw new InternalError("argument description miss required parameter"); } if ((arg instanceof desc.type) || (desc.type === Function && ((typeof arg) === 'function')) || (arg === null && desc.allowNull)) { if (desc.type === Function) { if (!arg) { return null; } var id; if (desc.argAsCallbackId !== undefined) { id = realArgs[desc.argAsCallbackId]; } return CallbackManager.makeCallback(uwa.ContextActionCallbackType, function (context, user_data) { arg(); }, name, id); } return arg; } else { throw new TypeError("incorrect argument"); } throw new InternalError("unreacheable"); } var args = [unity.context], i; for (i = 0; i < argsDesc.length; i++) { if (k >= realArgs.length && k > 0 && !argsDesc[i].dummy) { throw new Error("not enough arguments"); } var value = argumentSanitaizer(argsDesc[i], realArgs[k]); k++; if (argsDesc[i].obj) { args = args.concat(value); } else { args.push(value); } } if (k < realArgs.length) { throw new Error("too much arguments"); } if (callback) callback.apply(uwa, args); if (func) return Function.apply.apply(func, [uwa, args]); return null; }; }; var api = { init: function(props) { checkString(props.name, false); checkString(props.iconUrl, true); checkString(props.domain, true); checkString(props.login, true); checkString(props.mimeTypes, true); checkString(props.homepage, true); if (props.homepage && !/^(http|https|file):\/\//.test(props.homepage)) { throw new TypeError("incorrect argument"); } backend("init", [props]); } , acceptData: createArgumentsSanitaizer(null, [{ array: { element: { str: true } } }, { type: Function, js: true }], function (context, mimeTypes, callback) { backend('acceptData', [mimeTypes, callback]); }) , addAction: createArgumentsSanitaizer(null, [{ str: true }, { type: Function, argAsCallbackId: 0 }], function (context, name, callback) { backend('addAction', [name, callback]); }) , clearAction: createArgumentsSanitaizer(null, [{ str: true }] , function (context, name) { backend('clearAction', [name]); }) , clearActions: createArgumentsSanitaizer(null, [], function (context) { backend('clearActions', []); }) , MediaPlayer: { init: createArgumentsSanitaizer(null, [{ str: true }], function (context, name) { backend('MediaPlayer.init', [name]); }) , onPlayPause: createArgumentsSanitaizer(null, [{ type: Function, allowNull: true }, { dummy: true }], function (context, callback) { backend('MediaPlayer.onPlayPause', [callback]); } ) , onPrevious: createArgumentsSanitaizer(null, [{ type: Function, allowNull: true }, { dummy: true }], function (context, callback) { backend('MediaPlayer.onPrevious', [callback]); }) , onNext: createArgumentsSanitaizer(null, [{ type: Function, allowNull: true }, { dummy: true }], function (context, callback) { backend('MediaPlayer.onNext', [callback]); } ) , setTrack: createArgumentsSanitaizer(null, [{ obj: { artist: { str: true, place: 0, allowNull: true }, album: { str: true, place: 1, allowNull: true }, title: { str: true, place: 2 }, artLocation: { str: true, place: 3, allowNull: true } } }], function (context, trackinfos) { backend('MediaPlayer.setTrack', [trackinfos]); }) , setCanGoNext: createArgumentsSanitaizer(null, [{ number: true }], function (context, v) { backend('MediaPlayer.setCanGoNext', [v]); } ) , setCanGoPrevious: createArgumentsSanitaizer(null, [{ number: true }], function (context, v) { backend('MediaPlayer.setCanGoPrevious', [v]); } ) , setCanPlay: createArgumentsSanitaizer(null, [{ number: true }], function (context, v) { backend('MediaPlayer.setCanPlay', [v]); } ) , setCanPause: createArgumentsSanitaizer(null, [{ number: true }], function (context, v) { backend('MediaPlayer.setCanPause', [v]); } ) , setPlaybackState: createArgumentsSanitaizer(null, [{ number: true }], function (context, v) { backend('MediaPlayer.setPlaybackState', [v]); } ) , getPlaybackState: createArgumentsSanitaizer(null , [{ type: Function }] , function (context, callback) { backend('MediaPlayer.getPlaybackState', [callback]); } ) , PlaybackState: {PLAYING: 0, PAUSED:1} }, Notification: { showNotification: createArgumentsSanitaizer(null, [{ str: true }, { str: true }, { str: true, allowNull: true }], function (context, title, name, dummy) { backend('Notification.showNotification', [title, name, dummy]); } ) }, Launcher: { setCount: createArgumentsSanitaizer(null, [{ number: true }], function (context, count) { backend('Launcher.setCount', [count]); } ) , clearCount: createArgumentsSanitaizer(null, [], function (context) { backend('Launcher.clearCount', []); }), setProgress: createArgumentsSanitaizer(null, [{ number: true }], function (context, progress) { backend('Launcher.setProgress', [progress]); } ) , clearProgress: createArgumentsSanitaizer(null, [], function (context) { backend('Launcher.clearProgress', []); } ) , setUrgent: createArgumentsSanitaizer(null, [], function (context) { backend('Launcher.setUrgent', []); } ) , addAction: function(arg1, arg2) { backend('Launcher.addAction', [arg1, arg2]); } , removeAction: createArgumentsSanitaizer(null, [{ str: true }], function (context, name) { backend('Launcher.removeAction', [name]); } ) , removeActions: createArgumentsSanitaizer(null, [], function (context) { backend('Launcher.removeActions', []); } ) }, MessagingIndicator: { addAction: createArgumentsSanitaizer(null, [{ str: true }, { type: Function, argAsCallbackId: 0 }, { dummy: true }], function (context, name, callback, dummy) { backend('MessagingIndicator.addAction', [name, callback, dummy]); } ) , showIndicator: function(name, properties) { backend('MessagingIndicator.showIndicator', [name, properties]); } , clearIndicator: createArgumentsSanitaizer(null, [{ str: true }], function(context, name) { backend('MessagingIndicator.clearIndicator', [name]); }), clearIndicators: createArgumentsSanitaizer(null, [], function (context) { backend('MessagingIndicator.clearIndicators', []); }) } }; return api; }; unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/infobar.html0000644000015301777760000000057512457232616027302 0ustar pbusernogroup00000000000000 unity-chromium-extension-3.2.0+15.04.20150119/chromium-extension/infobar.js0000644000015301777760000000213112457232627026742 0ustar pbusernogroup00000000000000var doIntegrate = function (integrate) { chrome.tabs.query({currentWindow: true, active: true}, function (tabs) { chrome.runtime.sendMessage({tabId: tabs[0].id, method: "on_user_infobar_request_result", integrate: integrate} , function (response) {}); window.close(); }); }; window.onload = function () { chrome.runtime.getBackgroundPage(function (bg) { document.getElementById('notintegrate').onclick = function () { doIntegrate(false); }; document.getElementById('integrate').onclick = function () { doIntegrate(true); }; chrome.tabs.query({currentWindow: true, active: true}, function (tabs) { if (tabs.length === 0) { window.close(); return; } if (!bg || !bg.background_page) { window.close(); return; } var msg = bg.background_page.getMessageForTabId(tabs[0].id); if (msg == null) { window.close(); return; } document.getElementById ('content').style.display = "block"; document.getElementById ('message').innerHTML = msg || ""; }); }); }; unity-chromium-extension-3.2.0+15.04.20150119/messaging-host/0000755000015301777760000000000012457233063024055 5ustar pbusernogroup00000000000000unity-chromium-extension-3.2.0+15.04.20150119/messaging-host/webapps-process.cpp0000644000015301777760000000055312457232627027706 0ustar pbusernogroup00000000000000 extern "C" { #include } #include "webapps-process.h" namespace UnityWebapps { class ProcessPrivate { public: UnityWebappsService *service; }; Process::Process(): d_ptr(new ProcessPrivate) { d_ptr->service = unity_webapps_service_new(); } Process::~Process() { g_object_unref(d_ptr->service); delete d_ptr; } } unity-chromium-extension-3.2.0+15.04.20150119/messaging-host/com.canonical.webapp.installer.json.in0000644000015301777760000000042412457232627033337 0ustar pbusernogroup00000000000000{ '"name": "com.canonical.webapp.installer"', '"description": "Canonical WebApp Installation Host"', '"path": "$${target.path}/$${TARGET}"', '"type": "stdio"', '"allowed_origins"': [ '"chrome-extension://pmoflmbbcfgacopiikdcpmbiellfihdg/"' ] } unity-chromium-extension-3.2.0+15.04.20150119/messaging-host/Makefile.am0000644000015301777760000000006612457232627026120 0ustar pbusernogroup00000000000000EXTRA_DIST += \ installation-host unity-chromium-extension-3.2.0+15.04.20150119/messaging-host/inactivity-timer.h0000644000015301777760000000250612457232627027537 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical Ltd. * * This file is part of unity-chromium-extension * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ #ifndef UNITY_WEBAPPS_INACTIVITY_TIMER_H #define UNITY_WEBAPPS_INACTIVITY_TIMER_H #include #include #include namespace UnityWebapps { class InactivityTimer: public QObject { Q_OBJECT public: InactivityTimer(int interval, QObject *parent = 0); ~InactivityTimer() {} void watchObject(QObject *object); Q_SIGNALS: void timeout(); private Q_SLOTS: void onIdleChanged(); void onTimeout(); private: bool allObjectsAreIdle() const; private: QList m_watchedObjects; QTimer m_timer; int m_interval; }; } // namespace #endif // UNITY_WEBAPPS_INACTIVITY_TIMER_H unity-chromium-extension-3.2.0+15.04.20150119/messaging-host/webapps-handler.cpp0000644000015301777760000002232012457232627027641 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical Ltd. * * This file is part of unity-chromium-extension * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ extern "C" { #include #include } #include "webapps-handler.h" #include #include using namespace UnityWebapps; namespace UnityWebapps { class WebappsHandlerPrivate { Q_DECLARE_PUBLIC(WebappsHandler) public: inline WebappsHandlerPrivate(WebappsHandler *service); inline ~WebappsHandlerPrivate(); UnityWebappsApplicationRepository *getRepository(); private: static void installationCallback(UnityWebappsApplicationRepository *repository, const gchar *name, UnityWebappsApplicationStatus status, gpointer user_data); mutable WebappsHandler *q_ptr; UnityWebappsApplicationRepository *applicationRepository; }; } // namespace WebappsHandlerPrivate::WebappsHandlerPrivate(WebappsHandler *service): q_ptr(service), applicationRepository(0) { } WebappsHandlerPrivate::~WebappsHandlerPrivate() { if (applicationRepository != 0) { g_object_unref(G_OBJECT(applicationRepository)); } } UnityWebappsApplicationRepository *WebappsHandlerPrivate::getRepository() { if (applicationRepository == 0) { applicationRepository = unity_webapps_application_repository_new_default(); unity_webapps_application_repository_prepare(applicationRepository); } return applicationRepository; } void WebappsHandlerPrivate::installationCallback( UnityWebappsApplicationRepository *repository, const gchar *name, UnityWebappsApplicationStatus status, gpointer user_data ) { Q_UNUSED(repository); Q_UNUSED(name); Q_UNUSED(status); Q_UNUSED(user_data); } WebappsHandler::WebappsHandler(QObject *parent): QObject(parent), d_ptr(new WebappsHandlerPrivate(this)) { } WebappsHandler::~WebappsHandler() { delete d_ptr; } QVariantMap WebappsHandler::url_loaded(const QVariantMap &message) { Q_D(WebappsHandler); QVariantMap reply; if (!message.contains("url")) { reply.insert("error", QStringLiteral("malformed request")); return reply; } QString url = message.value("url").toString(); GList *apps = unity_webapps_application_repository_resolve_url( d->getRepository(), url.toLocal8Bit().constData() ); if (apps == 0) { reply.insert("available", false); return reply; } // As per original extension only look at the first entry const gchar *packageName = (const gchar*)apps->data; UnityWebappsApplicationStatus status = unity_webapps_application_repository_get_resolved_application_status( d->getRepository(), packageName); if (status == UNITY_WEBAPPS_APPLICATION_STATUS_UNRESOLVED) { reply.insert("available", false); g_list_free_full(apps, g_free); return reply; } const gchar *appName = unity_webapps_application_repository_get_resolved_application_name( d->getRepository(), packageName); const gchar *appDomain = unity_webapps_application_repository_get_resolved_application_domain( d->getRepository(), packageName); if (unity_webapps_permissions_get_domain_dontask(appDomain) || unity_webapps_permissions_get_domain_allowed(appDomain)) { reply.insert("available", false); g_list_free_full(apps, g_free); return reply; } reply.insert("available", true); reply.insert("appName", QString::fromUtf8(appName)); reply.insert("appDomain", QString::fromUtf8(appDomain)); g_list_free_full(apps, g_free); return reply; } QVariantMap WebappsHandler::dont_ask(const QVariantMap &message) { Q_D(WebappsHandler); QVariantMap reply; if (!message.contains("url")) { reply.insert("error", QLatin1String("malformed request")); return reply; } QString url = message.value("url").toString(); GList *apps = unity_webapps_application_repository_resolve_url( d->getRepository(), url.toLocal8Bit().constData() ); if (apps == 0) { reply.insert("available", false); reply.insert("dont_ask", false); return reply; } const gchar *packageName = (const gchar*)apps->data; const gchar *appDomain = unity_webapps_application_repository_get_resolved_application_domain( d->getRepository(), packageName); unity_webapps_permissions_dontask_domain(appDomain); reply.insert("dont_ask", true); g_list_free_full(apps, g_free); return reply; } QVariantMap WebappsHandler::install(const QVariantMap &message) { Q_D(WebappsHandler); QVariantMap reply; if (!message.contains("url")) { reply.insert("error", QLatin1String("malformed request")); return reply; } QString url = message.value("url").toString(); GList *apps = unity_webapps_application_repository_resolve_url( d->getRepository(), url.toLocal8Bit().constData() ); if (apps == 0) { reply.insert("available", false); reply.insert("installed", false); return reply; } const gchar *packageName = (const gchar*)apps->data; UnityWebappsApplicationStatus status = unity_webapps_application_repository_get_resolved_application_status( d->getRepository(), packageName); if (status == UNITY_WEBAPPS_APPLICATION_STATUS_UNRESOLVED) { reply.insert("available", false); reply.insert("installed", false); g_list_free_full(apps, g_free); return reply; } const gchar *appDomain = unity_webapps_application_repository_get_resolved_application_domain( d->getRepository(), packageName); const gchar *appName = unity_webapps_application_repository_get_resolved_application_name( d->getRepository(), packageName); switch (status) { case UNITY_WEBAPPS_APPLICATION_STATUS_AVAILABLE: if (unity_webapps_permissions_get_domain_dontask(appDomain)) { reply.insert("available", true); reply.insert("installed", false); g_list_free_full(apps, g_free); return reply; } unity_webapps_permissions_allow_domain(appDomain); unity_webapps_application_repository_install_application( d->getRepository(), packageName, WebappsHandlerPrivate::installationCallback, 0); break; case UNITY_WEBAPPS_APPLICATION_STATUS_INSTALLED: if (unity_webapps_permissions_get_domain_dontask(appDomain) || unity_webapps_permissions_get_domain_allowed(appDomain)) { reply.insert("available", true); reply.insert("installed", true); g_list_free_full(apps, g_free); return reply; } unity_webapps_application_repository_add_desktop_to_launcher( createApplicationDesktopName(appName, appDomain).toLocal8Bit() ); unity_webapps_permissions_allow_domain(appDomain); break; case UNITY_WEBAPPS_APPLICATION_STATUS_UNRESOLVED: // handled above break; } reply.insert("installed", true); g_list_free_full(apps, g_free); return reply; } QVariantMap WebappsHandler::ping(const QVariantMap &message) { Q_UNUSED(message); QVariantMap reply; reply.insert("pong", QLatin1String("alive")); return reply; } /* \fn createApplicationDesktopName(QString, QString) This function creates a application:// URI suitable for passing to unity_webapps_application_repository_add_desktop_to_launcher(). To add the webapp's icon to the launcher, a dbus message is sent to the launcher, referencing the webapps canonical .desktop file name. This function creates the canonical name and returns it in the URI form. */ QString WebappsHandler::createApplicationDesktopName( const QString &appName, const QString &appDomain ) const { QString basename; QRegularExpression re(QStringLiteral("[^[:alnum:]]"), QRegularExpression::UseUnicodePropertiesOption); basename.append(appName.trimmed().replace(re, QStringLiteral(""))); basename.append(appDomain.trimmed().replace(re, QStringLiteral(""))); return QStringLiteral("application://%1.desktop").arg(basename); } unity-chromium-extension-3.2.0+15.04.20150119/messaging-host/webapps-handler.h0000644000015301777760000000304312457232627027307 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical Ltd. * * This file is part of unity-chromium-extension * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ #ifndef UNITY_WEBAPPS_WEBAPPS_HANDLER #define UNITY_WEBAPPS_WEBAPPS_HANDLER #include #include namespace UnityWebapps { class WebappsHandlerPrivate; class WebappsHandler: public QObject { Q_OBJECT public: explicit WebappsHandler(QObject *parent = 0); ~WebappsHandler(); public Q_SLOTS: QVariantMap url_loaded(const QVariantMap &message); QVariantMap dont_ask(const QVariantMap &message); QVariantMap install(const QVariantMap &message); QVariantMap ping(const QVariantMap &message); #if defined(UCX_UNDER_TEST) public: #else private: #endif QString createApplicationDesktopName( const QString &appName, const QString &appDomain ) const; WebappsHandlerPrivate *d_ptr; Q_DECLARE_PRIVATE(WebappsHandler) }; } // namespace #endif // UNITY_WEBAPPS_WEBAPPS_HANDLER unity-chromium-extension-3.2.0+15.04.20150119/messaging-host/messaging-host.pro0000644000015301777760000000144212457232627027535 0ustar pbusernogroup00000000000000include(../common-project-config.pri) TEMPLATE = app TARGET = unity-webapps-messaging-host CONFIG += \ link_pkgconfig \ qt QT += \ core PKGCONFIG += \ glib-2.0 \ gobject-2.0 \ libunity_webapps-0.2 \ libunity-webapps-repository \ SOURCES = \ connection.cpp \ inactivity-timer.cpp \ main.cpp \ service.cpp \ webapps-handler.cpp \ webapps-process.cpp \ HEADERS = \ connection.h \ inactivity-timer.h \ service.h \ webapps-handler.h \ webapps-process.h \ target.path = $${INSTALL_PREFIX}/share/unity-webapps/bin INSTALLS += target QMAKE_SUBSTITUTES += \ com.canonical.webapp.installer.json.in manifest.path = "/etc/chromium/native-messaging-hosts" manifest.files = com.canonical.webapp.installer.json INSTALLS += manifest unity-chromium-extension-3.2.0+15.04.20150119/messaging-host/service.h0000644000015301777760000000254212457232627025676 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical Ltd. * * This file is part of unity-chromium-extension * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ #ifndef UNITY_WEBAPPS_SERVICE #define UNITY_WEBAPPS_SERVICE #include #include namespace UnityWebapps { class ServicePrivate; class Service: public QObject { Q_OBJECT Q_PROPERTY(bool isIdle READ isIdle NOTIFY isIdleChanged) public: explicit Service(QObject *parent = 0); ~Service(); bool isIdle() const; void addHandler(QObject *handler); public Q_SLOTS: void handleMessage(const QVariantMap &message); Q_SIGNALS: void messageHandled(const QVariantMap &reply); void isIdleChanged(); private: ServicePrivate *d_ptr; Q_DECLARE_PRIVATE(Service) }; } // namespace #endif // UNITY_WEBAPPS_SERVICE unity-chromium-extension-3.2.0+15.04.20150119/messaging-host/connection.cpp0000644000015301777760000000740212457232627026730 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical Ltd. * * This file is part of unity-chromium-extension * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ #include "connection.h" #include #include #include #include #include #include #include #include using namespace UnityWebapps; namespace UnityWebapps { class ConnectionPrivate: public QObject { Q_OBJECT Q_DECLARE_PUBLIC(Connection) public: inline ConnectionPrivate(Connection *connection); inline ~ConnectionPrivate(); bool open(); private Q_SLOTS: void onReadyRead(); private: QFile m_readChannel; QFile m_writeChannel; QByteArray m_readBuffer; int m_expectedLength; mutable Connection *q_ptr; }; } // namespace ConnectionPrivate::ConnectionPrivate(Connection *connection): QObject(connection), m_expectedLength(0), q_ptr(connection) { } ConnectionPrivate::~ConnectionPrivate() { } bool ConnectionPrivate::open() { bool ok; int flag = fcntl(STDIN_FILENO, F_GETFL); if (Q_UNLIKELY(flag == -1)) return false; fcntl(STDIN_FILENO, F_SETFL, flag | O_NONBLOCK); ok = m_readChannel.open(stdin, QIODevice::ReadOnly); if (Q_UNLIKELY(!ok)) return false; ok = m_writeChannel.open(stdout, QIODevice::WriteOnly); if (Q_UNLIKELY(!ok)) return false; QSocketNotifier *notifier = new QSocketNotifier(m_readChannel.handle(), QSocketNotifier::Read, this); QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(onReadyRead())); // There might be already something to read onReadyRead(); return true; } void ConnectionPrivate::onReadyRead() { Q_Q(Connection); while (true) { if (m_expectedLength == 0) { /* We are beginning a new read */ quint32 length; int bytesRead = m_readChannel.read((char *)&length, sizeof(length)); if (bytesRead < int(sizeof(length))) break; m_expectedLength = length; m_readBuffer.clear(); } int neededBytes = m_expectedLength - m_readBuffer.length(); QByteArray buffer = m_readChannel.read(neededBytes); m_readBuffer += buffer; if (buffer.length() < neededBytes) break; if (m_readBuffer.length() == m_expectedLength) { QJsonDocument doc = QJsonDocument::fromJson(m_readBuffer); Q_EMIT q->messageReceived(doc.toVariant().toMap()); m_expectedLength = 0; } } } Connection::Connection(QObject *parent): QObject(parent), d_ptr(new ConnectionPrivate(this)) { } Connection::~Connection() { } bool Connection::open() { Q_D(Connection); return d->open(); } void Connection::postMessage(const QVariantMap &message) { Q_D(Connection); QJsonDocument doc = QJsonDocument::fromVariant(message); QByteArray json = doc.toJson(); quint32 length = json.length(); d->m_writeChannel.write((char *)&length, sizeof(length)); d->m_writeChannel.write(json); d->m_writeChannel.flush(); } #include "connection.moc" unity-chromium-extension-3.2.0+15.04.20150119/messaging-host/main.cpp0000644000015301777760000000502412457232627025513 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical Ltd. * * This file is part of unity-chromium-extension * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ #include #include "connection.h" #include "inactivity-timer.h" #include "service.h" #include "webapps-handler.h" #include "webapps-process.h" #include #include void syslogOutputHandler(QtMsgType type, const QMessageLogContext &, const QString &msg) { QByteArray localMsg = msg.toLocal8Bit(); int syslog_type = LOG_USER; switch (type) { case QtDebugMsg: syslog_type |= LOG_DEBUG; break; case QtWarningMsg: syslog_type |= LOG_WARNING; break; case QtCriticalMsg: syslog_type |= LOG_CRIT; break; case QtFatalMsg: syslog_type |= LOG_ERR; break; } syslog(syslog_type, "%s", localMsg.constData()); } int main(int argc, char **argv) { if (qgetenv("UNITY_WEBAPPS_LOGGING") == QByteArrayLiteral("1")) { qInstallMessageHandler(syslogOutputHandler); } qDebug() << "Starting"; QCoreApplication app(argc, argv); UnityWebapps::Process process; UnityWebapps::Service service; UnityWebapps::WebappsHandler handler; service.addHandler(&handler); UnityWebapps::InactivityTimer inactivityTimer(2 * 60 * 1000); QObject::connect(&inactivityTimer, SIGNAL(timeout()), &app, SLOT(quit())); inactivityTimer.watchObject(&service); UnityWebapps::Connection connection; QObject::connect(&connection, SIGNAL(messageReceived(const QVariantMap &)), &service, SLOT(handleMessage(const QVariantMap &))); QObject::connect(&service, SIGNAL(messageHandled(const QVariantMap &)), &connection, SLOT(postMessage(const QVariantMap &))); bool ok = connection.open(); if (Q_UNLIKELY(!ok)) { qCritical() << "Couldn't open connection"; return EXIT_FAILURE; } int r = app.exec(); qDebug() << "Finishing"; return r; } unity-chromium-extension-3.2.0+15.04.20150119/messaging-host/inactivity-timer.cpp0000644000015301777760000000323112457232627030066 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical Ltd. * * This file is part of unity-chromium-extension * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ #include "inactivity-timer.h" #include using namespace UnityWebapps; InactivityTimer::InactivityTimer(int interval, QObject *parent): QObject(parent), m_interval(interval) { m_timer.setSingleShot(true); QObject::connect(&m_timer, SIGNAL(timeout()), this, SLOT(onTimeout())); } void InactivityTimer::watchObject(QObject *object) { connect(object, SIGNAL(isIdleChanged()), SLOT(onIdleChanged())); m_watchedObjects.append(object); /* Force an initial check */ onIdleChanged(); } void InactivityTimer::onIdleChanged() { if (allObjectsAreIdle()) { m_timer.start(m_interval); } } void InactivityTimer::onTimeout() { if (allObjectsAreIdle()) { Q_EMIT timeout(); } } bool InactivityTimer::allObjectsAreIdle() const { foreach (const QObject *object, m_watchedObjects) { if (!object->property("isIdle").toBool()) { return false; } } return true; } unity-chromium-extension-3.2.0+15.04.20150119/messaging-host/webapps-process.h0000644000015301777760000000170012457232627027346 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical Ltd. * * This file is part of unity-chromium-extension * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ #ifndef UNITY_WEBAPPS_PROCESS #define UNITY_WEBAPPS_PROCESS namespace UnityWebapps { class ProcessPrivate; class Process { public: Process(); ~Process(); private: ProcessPrivate *d_ptr; }; } // namespace #endif // UNITY_WEBAPPS_SERVICE unity-chromium-extension-3.2.0+15.04.20150119/messaging-host/connection.h0000644000015301777760000000236712457232627026402 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical Ltd. * * This file is part of unity-chromium-extension * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ #ifndef UNITY_WEBAPPS_CONNECTION #define UNITY_WEBAPPS_CONNECTION #include #include namespace UnityWebapps { class ConnectionPrivate; class Connection: public QObject { Q_OBJECT public: explicit Connection(QObject *parent = 0); ~Connection(); bool open(); public Q_SLOTS: void postMessage(const QVariantMap &message); Q_SIGNALS: void messageReceived(const QVariantMap &message); private: ConnectionPrivate *d_ptr; Q_DECLARE_PRIVATE(Connection) }; } // namespace #endif // UNITY_WEBAPPS_CONNECTION unity-chromium-extension-3.2.0+15.04.20150119/messaging-host/service.cpp0000644000015301777760000000513212457232627026227 0ustar pbusernogroup00000000000000/* * Copyright (C) 2014 Canonical Ltd. * * This file is part of unity-chromium-extension * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ #include "service.h" #include #include #include #include using namespace UnityWebapps; namespace UnityWebapps { class ServicePrivate { Q_DECLARE_PUBLIC(Service) public: inline ServicePrivate(Service *service); inline ~ServicePrivate(); void setIdle(bool isIdle); private: QList m_handlers; bool m_isIdle; mutable Service *q_ptr; }; } // namespace ServicePrivate::ServicePrivate(Service *service): m_isIdle(true), q_ptr(service) { } ServicePrivate::~ServicePrivate() { } void ServicePrivate::setIdle(bool isIdle) { Q_Q(Service); if (m_isIdle == isIdle) return; m_isIdle = isIdle; Q_EMIT q->isIdleChanged(); } Service::Service(QObject *parent): QObject(parent), d_ptr(new ServicePrivate(this)) { } Service::~Service() { delete d_ptr; } bool Service::isIdle() const { Q_D(const Service); return d->m_isIdle; } void Service::addHandler(QObject *handler) { Q_D(Service); d->m_handlers.append(handler); } void Service::handleMessage(const QVariantMap &message) { Q_D(Service); QByteArray method = message.value(QStringLiteral("method")).toString().toLatin1(); if (Q_UNLIKELY(method.isEmpty())) return; QByteArray methodSignature = method + "(QVariantMap)"; d->setIdle(false); QVariantMap reply; bool ok = false; Q_FOREACH(QObject *handler, d->m_handlers) { const QMetaObject *metaObject = handler->metaObject(); int index = metaObject->indexOfMethod(methodSignature); if (index == -1) continue; QMetaMethod metaMethod = metaObject->method(index); ok = metaMethod.invoke(handler, Q_RETURN_ARG(QVariantMap, reply), Q_ARG(QVariantMap, message)); if (ok) break; } if (ok) { Q_EMIT messageHandled(reply); } d->setIdle(true); }