UBW3CWidget.cpp 15.5 KB
Newer Older
Claudio Valerio's avatar
Claudio Valerio committed
1
/*
Claudio Valerio's avatar
Claudio Valerio committed
2 3 4 5 6 7 8 9 10
 * 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.
Claudio Valerio's avatar
Claudio Valerio committed
11
 *
Claudio Valerio's avatar
Claudio Valerio committed
12 13
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
Claudio Valerio's avatar
Claudio Valerio committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
 */

#include "UBW3CWidget.h"

#include <QtNetwork>
#include <QtXml>

#include "frameworks/UBPlatformUtils.h"
#include "frameworks/UBFileSystemUtils.h"

#include "core/UBApplication.h"
#include "core/UBSettings.h"
#include "api/UBWidgetUniboardAPI.h"

#include "board/UBBoardController.h"

30 31
#include "core/memcheck.h"

Ivan Ilin's avatar
Ivan Ilin committed
32 33
const QString freezedWidgetDefaultContentFilePath = "./etc/freezedWidgetWrapper.html";

Claudio Valerio's avatar
Claudio Valerio committed
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
bool UBW3CWidget::sTemplateLoaded = false;
QMap<QString, QString> UBW3CWidget::sNPAPIWrapperTemplates;
QString UBW3CWidget::sNPAPIWrappperConfigTemplate;


UBW3CWidget::UBW3CWidget(const QUrl& pWidgetUrl, QWidget *parent)
    : UBAbstractWidget(pWidgetUrl, parent)

{
    QString path = pWidgetUrl.toLocalFile();
    QDir potentialDir(path);

    if (!path.endsWith(".wgt") && !path.endsWith(".wgt/") && !potentialDir.exists())
    {
        int lastSlashIndex = path.lastIndexOf("/");
        if (lastSlashIndex > 0)
        {
            path = path.mid(0, lastSlashIndex + 1);
        }
    }

    if(!path.endsWith("/"))
        path += "/";

    int width = 300;
    int height = 150;

61
    QFile configFile(path + "config.xml");
Claudio Valerio's avatar
Claudio Valerio committed
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
    configFile.open(QFile::ReadOnly);

    QDomDocument doc;
    doc.setContent(configFile.readAll());
    QDomNodeList widgetDomList = doc.elementsByTagName("widget");

    if (widgetDomList.count() > 0)
    {
        QDomElement widgetElement = widgetDomList.item(0).toElement();

        width = widgetElement.attribute("width", "300").toInt();
        height = widgetElement.attribute("height", "150").toInt();

        mMetadatas.id = widgetElement.attribute("id", "");

        //some early widget (<= 4.3.4) where using identifier instead of id
        if (mMetadatas.id.length() == 0)
             mMetadatas.id = widgetElement.attribute("identifier", "");

        mMetadatas.version = widgetElement.attribute("version", "");

        // TODO UB 4.x map properly ub namespace
        mIsResizable = widgetElement.attribute("ub:resizable", "false") == "true";
        mIsFreezable = widgetElement.attribute("ub:freezable", "true") == "true";

        QString roles = widgetElement.attribute("ub:roles", "content tool").trimmed().toLower();

89 90 91 92
        //------------------------------//

        if( roles == "" || roles.contains("tool") )
        {
93
            mCanBeTool = UBAbstractWidget::type_ALL;
94 95 96 97
        }

        if( roles.contains("twin") )
        {
98
            mCanBeTool |= UBAbstractWidget::type_WIN;
99 100 101 102
        }

        if( roles.contains("tmac") )
        {
103
            mCanBeTool |= UBAbstractWidget::type_MAC;
104 105 106 107
        }
        
        if( roles.contains("tunix") )
        {
108
            mCanBeTool |= UBAbstractWidget::type_UNIX;
109 110 111 112 113 114
        }

        //---------//

        if( roles == "" || roles.contains("content") )
        {
115
            mCanBeContent = UBAbstractWidget::type_ALL;
116 117 118 119
        }

        if( roles.contains("cwin") )
        {
120
            mCanBeContent |= UBAbstractWidget::type_WIN;
121 122 123 124
        }

        if( roles.contains("cmac") )
        {
125
            mCanBeContent |= UBAbstractWidget::type_MAC;
126 127 128 129
        }

        if( roles.contains("cunix") )
        {
130
            mCanBeContent |= UBAbstractWidget::type_UNIX;
131 132 133
        }

        //------------------------------//
Claudio Valerio's avatar
Claudio Valerio committed
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204

        QDomNodeList contentDomList = widgetElement.elementsByTagName("content");

        if (contentDomList.count() > 0)
        {
            QDomElement contentElement = contentDomList.item(0).toElement();

            mMainHtmlFileName = contentElement.attribute("src", "");
        }

        mMetadatas.name = textForSubElementByLocale(widgetElement, "name", locale());
        mMetadatas.description = textForSubElementByLocale(widgetElement, "description ", locale());

        QDomNodeList authorDomList = widgetElement.elementsByTagName("author");

        if (authorDomList.count() > 0)
        {
            QDomElement authorElement = authorDomList.item(0).toElement();

            mMetadatas.author = authorElement.text();
            mMetadatas.authorHref = authorElement.attribute("href", "");
            mMetadatas.authorEmail = authorElement.attribute("email ", "");
        }

        QDomNodeList propertiesDomList = widgetElement.elementsByTagName("preference");

        for (uint i = 0; i < propertiesDomList.length(); i++)
        {
            QDomElement preferenceElement = propertiesDomList.at(i).toElement();
            QString prefName = preferenceElement.attribute("name", "");

            if (prefName.length() > 0)
            {
                QString prefValue = preferenceElement.attribute("value", "");
                bool readOnly = (preferenceElement.attribute("readonly", "false") == "true");

                mPreferences.insert(prefName, PreferenceValue(prefValue, readOnly));
            }
        }
    }

    if (mMainHtmlFileName.length() == 0)
    {
        QFile defaultStartFile(path + "index.htm");

        if (defaultStartFile.exists())
        {
            mMainHtmlFileName = "index.htm";
        }
        else
        {
            QFile secondDefaultStartFile(path + "index.html");

            if (secondDefaultStartFile.exists())
            {
                mMainHtmlFileName = "index.html";
            }
        }
    }

    mMainHtmlUrl = pWidgetUrl;
    mMainHtmlUrl.setPath(pWidgetUrl.path() + "/" + mMainHtmlFileName);
    // is it a valid local file ?
    QFile f(mMainHtmlUrl.toLocalFile());

    if(!f.exists())
        mMainHtmlUrl = QUrl(mMainHtmlFileName);

    connect(page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(javaScriptWindowObjectCleared()));
    connect(UBApplication::boardController, SIGNAL(activeSceneChanged()), this, SLOT(javaScriptWindowObjectCleared()));

205 206
    QWebView::load(mMainHtmlUrl);

Claudio Valerio's avatar
Claudio Valerio committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220
    setFixedSize(QSize(width, height));

    mNominalSize = QSize(width, height);
}

UBW3CWidget::~UBW3CWidget()
{
    // NOOP
}

void UBW3CWidget::javaScriptWindowObjectCleared()
{
    UBWidgetUniboardAPI *uniboardAPI = new UBWidgetUniboardAPI(UBApplication::boardController->activeScene(), 0);

221
    page()->mainFrame()->addToJavaScriptWindowObject("sankore", uniboardAPI);
Claudio Valerio's avatar
Claudio Valerio committed
222 223 224 225 226 227 228 229 230 231 232 233 234 235

}

bool UBW3CWidget::hasNPAPIWrapper(const QString& pMimeType)
{
    loadNPAPIWrappersTemplates();

    return sNPAPIWrapperTemplates.contains(pMimeType);
}


QString UBW3CWidget::createNPAPIWrapper(const QString& url,
        const QString& pMimeType, const QSize& sizeHint, const QString& pName)
{
236
    const QString userWidgetPath = UBSettings::settings()->userInteractiveDirectory() + "/" + tr("Web");
Claudio Valerio's avatar
Claudio Valerio committed
237 238 239 240 241 242 243 244 245 246 247 248
    QDir userWidgetDir(userWidgetPath);

    return createNPAPIWrapperInDir(url, userWidgetDir, pMimeType, sizeHint, pName);
}



QString UBW3CWidget::createNPAPIWrapperInDir(const QString& pUrl, const QDir& pDir,
    const QString& pMimeType, const QSize& sizeHint,
    const QString& pName)
{
    QString url = pUrl;
249 250
    // if the file name start with file:// it has be removed because QFileInfo doesn't support this form
    url = url.replace("file://","");
Claudio Valerio's avatar
Claudio Valerio committed
251 252 253 254 255 256 257
    QString name = pName;

    QFileInfo fi(url);

    if (name.length() == 0)
        name = fi.baseName();

258 259
    if (fi.exists()){
        url = fi.fileName();
Claudio Valerio's avatar
Claudio Valerio committed
260 261 262 263 264 265
    }

    loadNPAPIWrappersTemplates();

    QString htmlTemplate;

266
    if (pMimeType.length() > 0 && sNPAPIWrapperTemplates.contains(pMimeType)){
Claudio Valerio's avatar
Claudio Valerio committed
267 268
        htmlTemplate = sNPAPIWrapperTemplates.value(pMimeType);
    }
269
    else {
Claudio Valerio's avatar
Claudio Valerio committed
270 271 272 273 274 275
        QString extension = UBFileSystemUtils::extension(url);

        if (sNPAPIWrapperTemplates.contains(extension))
            htmlTemplate = sNPAPIWrapperTemplates.value(extension);
    }

276
    if (htmlTemplate.length() > 0){
Claudio Valerio's avatar
Claudio Valerio committed
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
        htmlTemplate = htmlTemplate.replace(QString("{in.url}"), url)
            .replace(QString("{in.width}"), QString("%1").arg(sizeHint.width()))
            .replace(QString("{in.height}"), QString("%1").arg(sizeHint.height()));

        QString configTemplate = sNPAPIWrappperConfigTemplate
            .replace(QString("{in.id}"), url)
            .replace(QString("{in.width}"), QString("%1").arg(sizeHint.width()))
            .replace(QString("{in.height}"), QString("%1").arg(sizeHint.height()))
            .replace(QString("{in.name}"), name)
            .replace(QString("{in.startFile}"), QString("index.htm"));

        QString dirPath = pDir.path();
        if (!pDir.exists())
            pDir.mkpath(dirPath);

        QString widgetLibraryPath = dirPath + "/" + name + ".wgt";
        QDir widgetLibraryDir(widgetLibraryPath);

        if (widgetLibraryDir.exists())
        {
            if (!UBFileSystemUtils::deleteDir(widgetLibraryDir.path()))
            {
                qWarning() << "Cannot delete old widget " << widgetLibraryDir.path();
            }
        }

        widgetLibraryDir.mkpath(widgetLibraryPath);
304
        if (fi.exists()){
305
            QString target = widgetLibraryPath + "/" + fi.fileName();
306 307 308
            QString source = pUrl;
            source.replace("file://","");
            QFile::copy(source, target);
309
        }
Claudio Valerio's avatar
Claudio Valerio committed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424

        QFile configFile(widgetLibraryPath + "/config.xml");

        if (!configFile.open(QIODevice::WriteOnly))
        {
            qWarning() << "Cannot open file " << configFile.fileName();
            return "";
        }

        QTextStream outConfig(&configFile);
        outConfig.setCodec("UTF-8");

        outConfig << configTemplate;
        configFile.close();

        QFile indexFile(widgetLibraryPath + "/index.htm");

        if (!indexFile.open(QIODevice::WriteOnly))
        {
            qWarning() << "Cannot open file " << indexFile.fileName();
            return "";
        }

        QTextStream outIndex(&indexFile);
        outIndex.setCodec("UTF-8");

        outIndex << htmlTemplate;
        indexFile.close();

        return widgetLibraryPath;
    }
    else
    {
        return "";
    }
}


QString UBW3CWidget::createHtmlWrapperInDir(const QString& html, const QDir& pDir,
    const QSize& sizeHint, const QString& pName)
{

    QString widgetPath = pDir.path() + "/" + pName + ".wgt";
    widgetPath = UBFileSystemUtils::nextAvailableFileName(widgetPath);
    QDir widgetDir(widgetPath);

    if (!widgetDir.exists())
    {
        widgetDir.mkpath(widgetDir.path());
    }

    QFile configFile(widgetPath + "/" + "config.xml");

    if (configFile.exists())
    {
        configFile.remove(configFile.fileName());
    }

    if (!configFile.open(QIODevice::WriteOnly))
    {
        qWarning() << "Cannot open file " << configFile.fileName();
        return "";
    }

    QTextStream outConfig(&configFile);
    outConfig.setCodec("UTF-8");
    outConfig << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl;
    outConfig << "<widget xmlns=\"http://www.w3.org/ns/widgets\"" << endl;
    outConfig << "    xmlns:ub=\"http://uniboard.mnemis.com/widgets\"" << endl;
    outConfig << "    id=\"http://uniboard.mnemis.com/" << pName << "\"" <<endl;

    outConfig << "    version=\"1.0\"" << endl;
    outConfig << "    width=\"" << sizeHint.width() << "\"" << endl;
    outConfig << "    height=\"" << sizeHint.height() << "\"" << endl;
    outConfig << "    ub:resizable=\"true\">" << endl;

    outConfig << "  <name>" << pName << "</name>" << endl;
    outConfig << "  <content src=\"" << pName << ".html\"/>" << endl;

    outConfig << "</widget>" << endl;

    configFile.close();

    const QString fullHtmlFileName = widgetPath + "/" + pName + ".html";

    QFile widgetHtmlFile(fullHtmlFileName);
    if (widgetHtmlFile.exists())
    {
        widgetHtmlFile.remove(widgetHtmlFile.fileName());
    }
    if (!widgetHtmlFile.open(QIODevice::WriteOnly))
    {
        qWarning() << "cannot open file " << widgetHtmlFile.fileName();
        return "";
    }

    QTextStream outStartFile(&widgetHtmlFile);
    outStartFile.setCodec("UTF-8");

    outStartFile << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">" << endl;
    outStartFile << "<html>" << endl;
    outStartFile << "<head>" << endl;
    outStartFile << "    <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">" << endl;
    outStartFile << "</head>" << endl;
    outStartFile << "  <body>" << endl;
    outStartFile << html << endl;
    outStartFile << "  </body>" << endl;
    outStartFile << "</html>" << endl;

    widgetHtmlFile.close();

    return widgetPath;

}

Ivan Ilin's avatar
Ivan Ilin committed
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
QString UBW3CWidget::freezedWidgetPage()
{
    static QString defaultcontent;

    if (defaultcontent.isNull()) {
        QFile wrapperFile(freezedWidgetDefaultContentFilePath);
        if (!wrapperFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
            qDebug() << "can't open wrapper file " + freezedWidgetDefaultContentFilePath;
            defaultcontent = "";
        } else {
            QByteArray arr = wrapperFile.readAll();
            if (!arr.isEmpty()) {
                defaultcontent = QString(arr);
            } else {
                qDebug() << "content of " + freezedWidgetDefaultContentFilePath + "is empty";
                defaultcontent = "";
            }
        }
    }

    return defaultcontent;
}

Claudio Valerio's avatar
Claudio Valerio committed
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
void UBW3CWidget::loadNPAPIWrappersTemplates()
{
    if (!sTemplateLoaded)
    {
        sNPAPIWrapperTemplates.clear();

        QString etcPath = UBPlatformUtils::applicationResourcesDirectory() + "/etc/";

        QDir etcDir(etcPath);

        foreach(QString fileName, etcDir.entryList())
        {
            if (fileName.startsWith("npapi-wrapper") && (fileName.endsWith(".htm") || fileName.endsWith(".html")))
            {

                QString htmlContent = UBFileSystemUtils::readTextFile(etcPath + fileName);

                if (htmlContent.length() > 0)
                {
                    QStringList tokens = fileName.split(".");

                    if (tokens.length() >= 4)
                    {
                        QString mime = tokens.at(tokens.length() - 4 );
                        mime += "/" + tokens.at(tokens.length() - 3);

                        QString fileExtension = tokens.at(tokens.length() - 2);

                        sNPAPIWrapperTemplates.insert(mime, htmlContent);
                        sNPAPIWrapperTemplates.insert(fileExtension, htmlContent);
                    }
                }
            }
        }

        sNPAPIWrappperConfigTemplate = UBFileSystemUtils::readTextFile(etcPath + "npapi-wrapper.config.xml");

        sTemplateLoaded = true;
    }
}


QString UBW3CWidget::textForSubElementByLocale(QDomElement rootElement, QString subTagName, QLocale locale)
{
    QDomNodeList subList = rootElement.elementsByTagName(subTagName);

    QString lang = locale.name();

    if (lang.length() > 2)
        lang[2] = QLatin1Char('-');

    if (subList.count() > 1)
    {
        for(int i = 0; i < subList.count(); i++)
        {
            QDomNode node = subList.at(i);
            QDomElement element = node.toElement();

            QString configLang = element.attribute("xml:lang", "");

            if(lang == configLang || (configLang.length() == 2 && configLang == lang.left(2)))
                 return element.text();
        }
    }

    if (subList.count() >= 1)
    {
        QDomElement element = subList.item(0).toElement();
        return element.text();
    }

    return "";
}