UBFeaturesController.cpp 40.5 KB
Newer Older
1
/*
2
 * Copyright (C) 2015-2018 Département de l'Instruction Publique (DIP-SEM)
Craig Watson's avatar
Craig Watson committed
3
 *
Claudio Valerio's avatar
Claudio Valerio committed
4
 * Copyright (C) 2013 Open Education Foundation
5
 *
Claudio Valerio's avatar
Claudio Valerio committed
6 7
 * Copyright (C) 2010-2013 Groupement d'Intérêt Public pour
 * l'Education Numérique en Afrique (GIP ENA)
8
 *
Claudio Valerio's avatar
Claudio Valerio committed
9 10 11
 * This file is part of OpenBoard.
 *
 * OpenBoard is free software: you can redistribute it and/or modify
Claudio Valerio's avatar
Claudio Valerio committed
12 13
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License,
14 15 16 17
 * with a specific linking exception for the OpenSSL project's
 * "OpenSSL" library (or with modified versions of it that use the
 * same license as the "OpenSSL" library).
 *
Claudio Valerio's avatar
Claudio Valerio committed
18
 * OpenBoard is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Claudio Valerio's avatar
Claudio Valerio committed
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Claudio Valerio's avatar
Claudio Valerio committed
21
 * GNU General Public License for more details.
22
 *
Claudio Valerio's avatar
Claudio Valerio committed
23
 * You should have received a copy of the GNU General Public License
Claudio Valerio's avatar
Claudio Valerio committed
24
 * along with OpenBoard. If not, see <http://www.gnu.org/licenses/>.
25 26 27
 */


Claudio Valerio's avatar
Claudio Valerio committed
28

Claudio Valerio's avatar
Claudio Valerio committed
29

Anna Udovichenko's avatar
Anna Udovichenko committed
30 31
#include <QGraphicsItem>
#include <QPointF>
32
#include <QtGui>
Anna Udovichenko's avatar
Anna Udovichenko committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

#include "core/UBApplication.h"
#include "board/UBBoardController.h"
#include "UBFeaturesController.h"
#include "core/UBSettings.h"
#include "tools/UBToolsManager.h"
#include "frameworks/UBFileSystemUtils.h"
#include "frameworks/UBPlatformUtils.h"

#include "core/UBDownloadManager.h"
#include "domain/UBGraphicsScene.h"
#include "domain/UBGraphicsSvgItem.h"
#include "domain/UBGraphicsPixmapItem.h"
#include "domain/UBGraphicsWidgetItem.h"

48 49 50
#include "gui/UBFeaturesWidget.h"

const QString UBFeaturesController::virtualRootName = "root";
Ilia Ryabokon's avatar
Ilia Ryabokon committed
51 52 53 54 55 56 57 58 59 60 61 62 63
const QString UBFeaturesController::rootPath  = "/" + virtualRootName;

const QString UBFeaturesController::appPath = rootPath + "/Applications";
const QString UBFeaturesController::audiosPath = rootPath + "/Audios";
const QString UBFeaturesController::moviesPath = rootPath + "/Movies";
const QString UBFeaturesController::picturesPath = rootPath + "/Pictures";
const QString UBFeaturesController::flashPath = rootPath + "/Animations";
const QString UBFeaturesController::interactPath = rootPath + "/Interactivities";
const QString UBFeaturesController::shapesPath = rootPath + "/Shapes";
const QString UBFeaturesController::trashPath = rootPath + "/Trash";
const QString UBFeaturesController::favoritePath = rootPath + "/Favorites";
const QString UBFeaturesController::webSearchPath = rootPath + "/Web search";

64

65
void UBFeaturesComputingThread::scanFS(const QUrl & currentPath, const QString & currVirtualPath, const QSet<QUrl> &pFavoriteSet)
Anna Udovichenko's avatar
Anna Udovichenko committed
66
{
67
//    Q_ASSERT(QFileInfo(currentPath.toLocalFile()).exists());
Ilia Ryabokon's avatar
Ilia Ryabokon committed
68 69
//    if(QFileInfo(currentPath.toLocalFile()).exists())
//        return;
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

    QFileInfoList fileInfoList = UBFileSystemUtils::allElementsInDirectory(currentPath.toLocalFile());

    QFileInfoList::iterator fileInfo;
    for ( fileInfo = fileInfoList.begin(); fileInfo != fileInfoList.end(); fileInfo +=  1) {
        if (abort) {
            return;
        }

        QString fullFileName = fileInfo->absoluteFilePath();
        UBFeatureElementType featureType = UBFeaturesController::fileTypeFromUrl(fullFileName);
        QString fileName = fileInfo->fileName();

        QImage icon = UBFeaturesController::getIcon(fullFileName, featureType);

        if ( fullFileName.contains(".thumbnail."))
            continue;

Ilia Ryabokon's avatar
Ilia Ryabokon committed
88
        UBFeature testFeature(currVirtualPath + "/" + fileName, icon, fileName, QUrl::fromLocalFile(fullFileName), featureType);
89 90 91

        emit sendFeature(testFeature);
        emit featureSent();
92
        emit scanPath(fullFileName);
93

94 95
        if ( pFavoriteSet.find(QUrl::fromLocalFile(fullFileName)) != pFavoriteSet.end()) {
            //TODO send favoritePath from the controller or make favoritePath public and static
Ilia Ryabokon's avatar
Ilia Ryabokon committed
96
            emit sendFeature(UBFeature( UBFeaturesController::favoritePath + "/" + fileName, icon, fileName, QUrl::fromLocalFile(fullFileName), featureType));
97
        }
98 99

        if (featureType == FEATURE_FOLDER) {
100
            scanFS(QUrl::fromLocalFile(fullFileName), currVirtualPath + "/" + fileName, pFavoriteSet);
101 102
        }
    }
Anna Udovichenko's avatar
Anna Udovichenko committed
103 104
}

105
void UBFeaturesComputingThread::scanAll(QList<QPair<QUrl, UBFeature> > pScanningData, const QSet<QUrl> &pFavoriteSet)
106 107 108 109 110
{
    for (int i = 0; i < pScanningData.count(); i++) {
        if (abort) {
            return;
        }
111
        QPair<QUrl, UBFeature> curPair = pScanningData.at(i);
112

113 114
        emit scanCategory(curPair.second.getDisplayName());
        scanFS(curPair.first, curPair.second.getFullVirtualPath(), pFavoriteSet);
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    }
}

int UBFeaturesComputingThread::featuresCount(const QUrl &pPath)
{
    int noItems = 0;

    QFileInfoList fileInfoList = UBFileSystemUtils::allElementsInDirectory(pPath.toLocalFile());

    QFileInfoList::iterator fileInfo;
    for ( fileInfo = fileInfoList.begin(); fileInfo != fileInfoList.end(); fileInfo +=  1) {
        QString fullFileName = fileInfo->absoluteFilePath();
        UBFeatureElementType featureType = UBFeaturesController::fileTypeFromUrl(fullFileName);

        if (featureType != FEATURE_INVALID && !fullFileName.contains(".thumbnail.")) {
            noItems++;
        }

        if (featureType == FEATURE_FOLDER) {
            noItems += featuresCount(QUrl::fromLocalFile(fullFileName));
        }
    }

    return noItems;
}

141
int UBFeaturesComputingThread::featuresCountAll(QList<QPair<QUrl, UBFeature> > pScanningData)
142
{
143 144
    int noItems = 0;
    for (int i = 0; i < pScanningData.count(); i++) {
145
        QPair<QUrl, UBFeature> curPair = pScanningData.at(i);
146
        noItems += featuresCount(curPair.first);
147 148
    }

149 150 151 152 153 154 155 156 157 158
    return noItems;
}

UBFeaturesComputingThread::UBFeaturesComputingThread(QObject *parent) :
QThread(parent)
{
    restart = false;
    abort = false;
}

159
void UBFeaturesComputingThread::compute(const QList<QPair<QUrl, UBFeature> > &pScanningData, QSet<QUrl> *pFavoritesSet)
160 161 162 163
{
    QMutexLocker curLocker(&mMutex);

    mScanningData = pScanningData;
164
    mFavoriteSet = *pFavoritesSet;
165 166 167 168 169 170 171 172 173 174 175 176

    if (!isRunning()) {
        start(LowPriority);
    } else {
        restart = true;
        mWaitCondition.wakeOne();
    }
}

void UBFeaturesComputingThread::run()
{
    forever {
Ilia Ryabokon's avatar
Ilia Ryabokon committed
177
//        qDebug() << "Custom thread started execution";
178 179

        mMutex.lock();
180
        QList<QPair<QUrl, UBFeature> > searchData = mScanningData;
181
        QSet<QUrl> favoriteSet = mFavoriteSet;
182 183 184 185 186 187 188 189 190
        mMutex.unlock();

        if (abort) {
            return;
        }
        if (restart) {
            break;
        }

Ilia Ryabokon's avatar
Ilia Ryabokon committed
191
//        QTime curTime = QTime::currentTime();
192
        int fsCnt = featuresCountAll(searchData);
Ilia Ryabokon's avatar
Ilia Ryabokon committed
193 194
//        int msecsto = curTime.msecsTo(QTime::currentTime());
//        qDebug() << "time on evaluation" << msecsto;
195 196 197 198

        emit maxFilesCountEvaluated(fsCnt);

        emit scanStarted();
Ilia Ryabokon's avatar
Ilia Ryabokon committed
199
//        curTime = QTime::currentTime();
200
        scanAll(searchData, favoriteSet);
Ilia Ryabokon's avatar
Ilia Ryabokon committed
201
//        qDebug() << "Time on finishing" << curTime.msecsTo(QTime::currentTime());
202 203 204
        emit scanFinished();

        mMutex.lock();
205
        if (!abort) {
206 207 208 209 210
            mWaitCondition.wait(&mMutex);
        }
        restart = false;
        mMutex.unlock();

211 212 213
    }
}

214 215
UBFeaturesComputingThread::~UBFeaturesComputingThread()
{
Ilia Ryabokon's avatar
Ilia Ryabokon committed
216
//    qDebug() <<  "thread destructor catched";
217 218 219 220 221 222

    mMutex.lock();
    abort = true;
    mWaitCondition.wakeOne();
    mMutex.unlock();

Ilia Ryabokon's avatar
Ilia Ryabokon committed
223
    wait();
224 225 226
}

UBFeature::UBFeature(const QString &url, const QImage &icon, const QString &name, const QUrl &realPath, UBFeatureElementType type)
Ilia Ryabokon's avatar
Ilia Ryabokon committed
227
    : mThumbnail(icon), mDisplayName(name), mPath(realPath), elementType(type)
228
{
Ilia Ryabokon's avatar
Ilia Ryabokon committed
229 230
    mName = getNameFromVirtualPath(url);
    virtualDir = getVirtualDirFromVirtualPath(url);
231 232 233 234 235 236
}

UBFeature::~UBFeature()
{
}

Ilia Ryabokon's avatar
Ilia Ryabokon committed
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
QString UBFeature::getNameFromVirtualPath(const QString &pVirtPath)
{
    QString result;
    int slashPos = pVirtPath.lastIndexOf("/");
    if (slashPos != -1) {
        result = pVirtPath.right(pVirtPath.count() - slashPos - 1);
    } else {
        qDebug() << "UBFeature: incorrect virtual path parameter specified";
    }

    return result;
}

QString UBFeature::getVirtualDirFromVirtualPath(const QString &pVirtPath)
{
    QString result;
    int slashPos = pVirtPath.lastIndexOf("/");
    if (slashPos != -1) {
        result = pVirtPath.left(slashPos);
    } else {
        qDebug() << "UBFeature: incorrect virtual path parameter specified";
    }

    return result;
}

263 264
QString UBFeature::getUrl() const
{
Claudio Valerio's avatar
Claudio Valerio committed
265
    if ( elementType == FEATURE_INTERNAL )
266
        return getFullPath().toString();
267

268 269 270
    return getFullPath().toLocalFile();
}

Anna Udovichenko's avatar
Anna Udovichenko committed
271 272
bool UBFeature::operator ==( const UBFeature &f )const
{
273
    return virtualDir == f.getVirtualPath() && mName == f.getName() && mPath == f.getFullPath() && elementType == f.getType();
Anna Udovichenko's avatar
Anna Udovichenko committed
274
}
275

Anna Udovichenko's avatar
Anna Udovichenko committed
276 277
bool UBFeature::operator !=( const UBFeature &f )const
{
Claudio Valerio's avatar
Claudio Valerio committed
278
    return !(*this == f);
Anna Udovichenko's avatar
Anna Udovichenko committed
279
}
280 281

bool UBFeature::isFolder() const
Anna Udovichenko's avatar
Anna Udovichenko committed
282
{
Claudio Valerio's avatar
Claudio Valerio committed
283
    return elementType == FEATURE_CATEGORY || elementType == FEATURE_TRASH || elementType == FEATURE_FAVORITE
284 285 286 287 288 289 290 291
        || elementType == FEATURE_FOLDER || elementType == FEATURE_SEARCH;
}

bool UBFeature::allowedCopy() const
{
    return isFolder()
            && elementType != FEATURE_CATEGORY
            && elementType != FEATURE_SEARCH;
Anna Udovichenko's avatar
Anna Udovichenko committed
292 293
}

294
bool UBFeature::isDeletable() const
295
{
296
    return elementType == FEATURE_ITEM
297 298 299
            || elementType == FEATURE_AUDIO
            || elementType == FEATURE_VIDEO
            || elementType == FEATURE_IMAGE
Claudio Valerio's avatar
Claudio Valerio committed
300
            || elementType == FEATURE_FLASH
Ilia Ryabokon's avatar
Ilia Ryabokon committed
301 302 303
            || elementType == FEATURE_FOLDER
    //Ilia. Just a hotfix. Permission mechanism for UBFeatures should be reworked
            || getVirtualPath().startsWith("/root/Applications/Web");
304 305 306 307 308
}

bool UBFeature::inTrash() const
{
    return getFullPath().toLocalFile().startsWith(QUrl::fromLocalFile(UBSettings::userTrashDirPath()).toLocalFile() );
309
}
Anna Udovichenko's avatar
Anna Udovichenko committed
310 311

UBFeaturesController::UBFeaturesController(QWidget *pParentWidget) :
312 313 314
    QObject(pParentWidget)
    ,featuresList(0)
    ,mLastItemOffsetIndex(0)
Anna Udovichenko's avatar
Anna Udovichenko committed
315
{
316 317 318 319 320 321 322 323
    //Initializing physical directories from UBSettings
    mUserAudioDirectoryPath = QUrl::fromLocalFile(UBSettings::settings()->userAudioDirectory());
    mUserVideoDirectoryPath = QUrl::fromLocalFile(UBSettings::settings()->userVideoDirectory());
    mUserPicturesDirectoryPath = QUrl::fromLocalFile(UBSettings::settings()->userImageDirectory());
    mUserInteractiveDirectoryPath = QUrl::fromLocalFile(UBSettings::settings()->userInteractiveDirectory());
    mUserAnimationDirectoryPath = QUrl::fromLocalFile(UBSettings::settings()->userAnimationDirectory());

    mLibPicturesDirectoryPath = QUrl::fromLocalFile(UBSettings::settings()->applicationImageLibraryDirectory());
324 325 326
    mLibAudiosDirectoryPath = QUrl::fromLocalFile(UBSettings::settings()->applicationAudiosLibraryDirectory());
    mLibVideosDirectoryPath = QUrl::fromLocalFile(UBSettings::settings()->applicationVideosLibraryDirectory());
    mLibAnimationsDirectoryPath = QUrl::fromLocalFile(UBSettings::settings()->applicationAnimationsLibraryDirectory());
327 328 329 330 331 332
    mLibInteractiveDirectoryPath = QUrl::fromLocalFile(UBSettings::settings()->applicationInteractivesDirectory());
    mLibApplicationsDirectoryPath = QUrl::fromLocalFile(UBSettings::settings()->applicationApplicationsLibraryDirectory());
    mLibShapesDirectoryPath = QUrl::fromLocalFile(UBSettings::settings()->applicationShapeLibraryDirectory());
    mLibSearchDirectoryPath =QUrl::fromLocalFile(UBSettings::settings()->userSearchDirectory());
    trashDirectoryPath = QUrl::fromLocalFile(UBSettings::userTrashDirPath());

Ilia Ryabokon's avatar
Ilia Ryabokon committed
333 334 335 336 337 338 339 340 341 342
    rootElement = UBFeature(rootPath, QImage( ":images/libpalette/home.png" ), "root", QUrl());
    audiosElement = UBFeature( audiosPath, QImage(":images/libpalette/AudiosCategory.svg"), tr("Audios") , mUserAudioDirectoryPath, FEATURE_CATEGORY);
    moviesElement = UBFeature( moviesPath, QImage(":images/libpalette/MoviesCategory.svg"), tr("Movies") , mUserVideoDirectoryPath, FEATURE_CATEGORY);
    picturesElement = UBFeature( picturesPath, QImage(":images/libpalette/PicturesCategory.svg"), tr("Pictures") , mUserPicturesDirectoryPath, FEATURE_CATEGORY);
    flashElement = UBFeature( flashPath, QImage(":images/libpalette/FlashCategory.svg"), tr("Animations") , mUserAnimationDirectoryPath, FEATURE_CATEGORY);
    interactElement = UBFeature( interactPath, QImage(":images/libpalette/InteractivesCategory.svg"), tr("Interactivities") ,  mLibInteractiveDirectoryPath, FEATURE_CATEGORY);
    applicationsElement = UBFeature( appPath, QImage(":images/libpalette/ApplicationsCategory.svg"), tr("Applications") , mUserInteractiveDirectoryPath, FEATURE_CATEGORY);
    shapesElement = UBFeature( shapesPath, QImage(":images/libpalette/ShapesCategory.svg"), tr("Shapes") , mLibShapesDirectoryPath, FEATURE_CATEGORY );
    favoriteElement = UBFeature( favoritePath, QImage(":images/libpalette/FavoritesCategory.svg"), tr("Favorites"), QUrl("favorites"), FEATURE_FAVORITE );
    webSearchElement = UBFeature( webSearchPath, QImage(":images/libpalette/WebSearchCategory.svg"), tr("Web search"), mLibSearchDirectoryPath, FEATURE_CATEGORY);
Claudio Valerio's avatar
Claudio Valerio committed
343

Ilia Ryabokon's avatar
Ilia Ryabokon committed
344
    trashElement = UBFeature( trashPath, QImage(":images/libpalette/TrashCategory.svg"), tr("Trash"), trashDirectoryPath, FEATURE_TRASH);
345 346 347 348 349 350

    featuresList = new QList <UBFeature>();

    scanFS();

    featuresModel = new UBFeaturesModel(featuresList, this);
351
    //featuresModel->setSupportedDragActions(Qt::CopyAction | Qt::MoveAction);
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366

    featuresProxyModel = new UBFeaturesProxyModel(this);
    featuresProxyModel->setFilterFixedString(rootPath);
    featuresProxyModel->setSourceModel(featuresModel);
    featuresProxyModel->setFilterCaseSensitivity( Qt::CaseInsensitive );

    featuresSearchModel = new UBFeaturesSearchProxyModel(this);
    featuresSearchModel->setSourceModel(featuresModel);
    featuresSearchModel->setFilterCaseSensitivity( Qt::CaseInsensitive );

    featuresPathModel = new UBFeaturesPathProxyModel(this);
    featuresPathModel->setPath(rootPath);
    featuresPathModel->setSourceModel(featuresModel);

    connect(featuresModel, SIGNAL(dataRestructured()), featuresProxyModel, SLOT(invalidate()));
367 368 369 370 371
    connect(&mCThread, SIGNAL(sendFeature(UBFeature)), featuresModel, SLOT(addItem(UBFeature)));
    connect(&mCThread, SIGNAL(featureSent()), this, SIGNAL(featureAddedFromThread()));
    connect(&mCThread, SIGNAL(scanStarted()), this, SIGNAL(scanStarted()));
    connect(&mCThread, SIGNAL(scanFinished()), this, SIGNAL(scanFinished()));
    connect(&mCThread, SIGNAL(maxFilesCountEvaluated(int)), this, SIGNAL(maxFilesCountEvaluated(int)));
372 373
    connect(&mCThread, SIGNAL(scanCategory(QString)), this, SIGNAL(scanCategory(QString)));
    connect(&mCThread, SIGNAL(scanPath(QString)), this, SIGNAL(scanPath(QString)));
374
    connect(UBApplication::boardController, SIGNAL(npapiWidgetCreated(QString)), this, SLOT(createNpApiFeature(QString)));
375 376 377 378 379 380

    QTimer::singleShot(0, this, SLOT(startThread()));
}

void UBFeaturesController::startThread()
{
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
    QList<QPair<QUrl, UBFeature> > computingData;

    computingData << QPair<QUrl, UBFeature>(mLibAudiosDirectoryPath, audiosElement)
            <<  QPair<QUrl, UBFeature>(mLibVideosDirectoryPath, moviesElement)
            <<  QPair<QUrl, UBFeature>(mLibAnimationsDirectoryPath, flashElement)
            <<  QPair<QUrl, UBFeature>(mLibPicturesDirectoryPath, picturesElement)

            <<  QPair<QUrl, UBFeature>(mUserInteractiveDirectoryPath, applicationsElement)
            <<  QPair<QUrl, UBFeature>(mUserAudioDirectoryPath, audiosElement)
            <<  QPair<QUrl, UBFeature>(mUserPicturesDirectoryPath, picturesElement)
            <<  QPair<QUrl, UBFeature>(mUserVideoDirectoryPath, moviesElement)
            <<  QPair<QUrl, UBFeature>(mUserAnimationDirectoryPath, flashElement)

            <<  QPair<QUrl, UBFeature>(mLibApplicationsDirectoryPath, applicationsElement)
            <<  QPair<QUrl, UBFeature>(mLibShapesDirectoryPath, shapesElement)
            <<  QPair<QUrl, UBFeature>(mLibInteractiveDirectoryPath, interactElement)
            <<  QPair<QUrl, UBFeature>(trashDirectoryPath, trashElement)
            <<  QPair<QUrl, UBFeature>(mLibSearchDirectoryPath, webSearchElement);
399

400
    mCThread.compute(computingData, favoriteSet);
Anna Udovichenko's avatar
Anna Udovichenko committed
401 402
}

403 404 405 406 407 408
void UBFeaturesController::createNpApiFeature(const QString &str)
{
    Q_ASSERT(QFileInfo(str).exists() && QFileInfo(str).isDir());

    QString widgetName = QFileInfo(str).fileName();

Ilia Ryabokon's avatar
Ilia Ryabokon committed
409
    featuresModel->addItem(UBFeature(QString(appPath + "/Web/" + widgetName), QImage(UBGraphicsWidgetItem::iconFilePath(QUrl::fromLocalFile(str))), widgetName, QUrl::fromLocalFile(str), FEATURE_INTERACTIVE));
410 411
}

412
void UBFeaturesController::scanFS()
Anna Udovichenko's avatar
Anna Udovichenko committed
413
{
414 415
    featuresList->clear();
    featuresList->append(rootElement);
416

417 418 419 420 421 422 423 424 425 426
    *featuresList << audiosElement
                    << moviesElement
                    << picturesElement
                    << flashElement
                    << interactElement
                    << applicationsElement
                    << shapesElement
                    << favoriteElement
                    << webSearchElement
                    << trashElement;
Anna Udovichenko's avatar
Anna Udovichenko committed
427

428
    //filling favoriteList
429
    loadFavoriteList();
Anna Udovichenko's avatar
Anna Udovichenko committed
430

431
    QList <UBToolsManager::UBToolDescriptor> tools = UBToolsManager::manager()->allTools();
Anna Udovichenko's avatar
Anna Udovichenko committed
432

433
    foreach (UBToolsManager::UBToolDescriptor tool, tools) {
Ilia Ryabokon's avatar
Ilia Ryabokon committed
434
        featuresList->append(UBFeature(appPath + "/" + tool.label, tool.icon.toImage(), tool.label, QUrl(tool.id), FEATURE_INTERNAL));
435
        if (favoriteSet->find(QUrl(tool.id)) != favoriteSet->end()) {
Ilia Ryabokon's avatar
Ilia Ryabokon committed
436
            featuresList->append(UBFeature(favoritePath + "/" + tool.label, tool.icon.toImage(), tool.label, QUrl(tool.id), FEATURE_INTERNAL));
437 438
        }
    }
Anna Udovichenko's avatar
Anna Udovichenko committed
439
}
440
void UBFeaturesController::fileSystemScan(const QUrl & currentPath, const QString & currVirtualPath)
Anna Udovichenko's avatar
Anna Udovichenko committed
441
{
442
    QFileInfoList fileInfoList = UBFileSystemUtils::allElementsInDirectory(currentPath.toLocalFile());
Anna Udovichenko's avatar
Anna Udovichenko committed
443 444

    QFileInfoList::iterator fileInfo;
445 446 447
    for ( fileInfo = fileInfoList.begin(); fileInfo != fileInfoList.end(); fileInfo +=  1) {
        QString fullFileName = fileInfo->absoluteFilePath();
        UBFeatureElementType featureType = fileTypeFromUrl(fullFileName);
Anna Udovichenko's avatar
Anna Udovichenko committed
448
        QString fileName = fileInfo->fileName();
449

450
        QImage icon = getIcon(fullFileName, featureType);
451

452 453
        if ( fullFileName.contains(".thumbnail."))
            continue;
454
 
Ilia Ryabokon's avatar
Ilia Ryabokon committed
455
        UBFeature testFeature(currVirtualPath + "/" + fileName, icon, fileName, QUrl::fromLocalFile(fullFileName), featureType);
456 457

        featuresList->append(testFeature);
Anna Udovichenko's avatar
Anna Udovichenko committed
458

459
        if ( favoriteSet->find( QUrl::fromLocalFile( fullFileName ) ) != favoriteSet->end() ) {
Ilia Ryabokon's avatar
Ilia Ryabokon committed
460
            featuresList->append( UBFeature( favoritePath + "/" + fileName, icon, fileName, QUrl::fromLocalFile( fullFileName ), featureType ) );
Claudio Valerio's avatar
Claudio Valerio committed
461
        }
Anna Udovichenko's avatar
Anna Udovichenko committed
462

463 464
        if (featureType == FEATURE_FOLDER) {
            fileSystemScan(QUrl::fromLocalFile(fullFileName), currVirtualPath + "/" + fileName);
Claudio Valerio's avatar
Claudio Valerio committed
465
        }
466
    }
Anna Udovichenko's avatar
Anna Udovichenko committed
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
int UBFeaturesController::featuresCount(const QUrl &currPath)
{
    int noItems = 0;

    QFileInfoList fileInfoList = UBFileSystemUtils::allElementsInDirectory(currPath.toLocalFile());

    QFileInfoList::iterator fileInfo;
    for ( fileInfo = fileInfoList.begin(); fileInfo != fileInfoList.end(); fileInfo +=  1) {
        QString fullFileName = fileInfo->absoluteFilePath();
        UBFeatureElementType featureType = fileTypeFromUrl(fullFileName);

        if (featureType != FEATURE_INVALID && !fullFileName.contains(".thumbnail.")) {
            noItems++;
        } else {
            continue;
        }

        if (featureType == FEATURE_FOLDER) {
            noItems += featuresCount(QUrl::fromLocalFile(fullFileName));
        }
    }

    return noItems;
}

494 495
void UBFeaturesController::loadFavoriteList()
{
Claudio Valerio's avatar
Claudio Valerio committed
496 497 498 499 500 501 502 503 504 505 506 507
    favoriteSet = new QSet<QUrl>();
    QFile file( UBSettings::userDataDirectory() + "/favorites.dat" );
    if ( file.exists() )
    {
        file.open(QIODevice::ReadOnly);
        QDataStream in(&file);
        int elementsNumber;
        in >> elementsNumber;
        for ( int i = 0; i < elementsNumber; ++i)
        {
            QUrl path;
            in >> path;
508
            favoriteSet->insert( path );
Claudio Valerio's avatar
Claudio Valerio committed
509 510
        }
    }
511 512 513 514
}

void UBFeaturesController::saveFavoriteList()
{
Claudio Valerio's avatar
Claudio Valerio committed
515 516 517 518 519 520 521 522 523 524
    QFile file( UBSettings::userDataDirectory() + "/favorites.dat" );
    file.resize(0);
    file.open(QIODevice::WriteOnly);
    QDataStream out(&file);
    out << favoriteSet->size();
    for ( QSet<QUrl>::iterator it = favoriteSet->begin(); it != favoriteSet->end(); ++it )
    {
        out << (*it);
    }
    file.close();
525 526
}

527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
QString UBFeaturesController::uniqNameForFeature(const UBFeature &feature, const QString &pName, const QString &pExtention) const
{
    Q_ASSERT(featuresList);

    QStringList resultList;
    QString parentVirtualPath = feature.getFullVirtualPath();
    QString resultName;

    qDebug() << "start";
    foreach (UBFeature curFeature, *featuresList) {

        if (curFeature.getFullVirtualPath().startsWith(feature.getFullVirtualPath())) {

            QString curResultName = curFeature.getFullVirtualPath();
            if (!parentVirtualPath.endsWith("/")) {
                parentVirtualPath.append("/");
            }
            //Cut virtual path prevfix
            int i = curResultName.indexOf(feature.getFullVirtualPath());
            if (i != -1) {
                curResultName = curResultName.right(curFeature.getFullVirtualPath().count() - i - parentVirtualPath.count());
            }
            //if directory has children, emptying the name;
            i = curResultName.indexOf("/");
            if (i != -1) {
                curResultName = "";
            }

            if (!curResultName.isEmpty()) {
                resultList.append(curResultName);
            }

            qDebug() << curResultName;
        }
    }

    if (!resultList.contains(pName + pExtention, Qt::CaseInsensitive)) {
        resultName = pName + pExtention;

    } else {
        for (int i = 0; i < 16777215; i++) {
            QString probeName = pName + "_" + QString::number(i) + pExtention;
            if (!resultList.contains(probeName, Qt::CaseInsensitive)) {
                resultName = probeName;
                break;
            }
        }
    }
    qDebug() << "result name is " << resultName;

    return resultName;
}

QString UBFeaturesController::adjustName(const QString &str)
{
    if (str.isNull()) {
        return QString();
    }

    QString resultStr = str;
    QRegExp invalidSymbols("[\\/\\s\\:\\?\\*\\|\\<\\>\\\"]+");

    return resultStr.replace(invalidSymbols, "_");
}

592
void UBFeaturesController::addToFavorite( const QUrl &path )
593
{
Claudio Valerio's avatar
Claudio Valerio committed
594 595 596 597 598
    QString filePath = fileNameFromUrl( path );
    if ( favoriteSet->find( path ) == favoriteSet->end() )
    {
        QFileInfo fileInfo( filePath );
        QString fileName = fileInfo.fileName();
599
        UBFeatureElementType type = fileTypeFromUrl(filePath);
Ilia Ryabokon's avatar
Ilia Ryabokon committed
600
        UBFeature elem(favoritePath + "/" + fileName, getIcon(filePath, type), fileName, path, fileTypeFromUrl(filePath) );
Claudio Valerio's avatar
Claudio Valerio committed
601 602
        favoriteSet->insert( path );
        saveFavoriteList();
603 604 605

        if ( !elem.getVirtualPath().isEmpty() && !elem.getVirtualPath().isNull())
        featuresModel->addItem( elem );
Claudio Valerio's avatar
Claudio Valerio committed
606
    }
607 608
}

609
void UBFeaturesController::removeFromFavorite( const QUrl &path, bool deleteManualy)
610
{
Claudio Valerio's avatar
Claudio Valerio committed
611 612 613 614 615
    if ( favoriteSet->find( path ) != favoriteSet->end() )
    {
        favoriteSet->erase( favoriteSet->find( path ) );
        saveFavoriteList();
    }
616 617 618 619

    if (deleteManualy) {
        featuresModel->deleteFavoriteItem(path.toString());
    }
620 621
}

622 623
QString UBFeaturesController::fileNameFromUrl( const QUrl &url )
{
Claudio Valerio's avatar
Claudio Valerio committed
624
    QString fileName = url.toString();
625
    if ( fileName.contains( "openboardtool://"))
Claudio Valerio's avatar
Claudio Valerio committed
626 627
        return fileName;
    return url.toLocalFile();
628 629
}

630

631
UBFeatureElementType UBFeaturesController::fileTypeFromUrl(const QString &path)
632
{
633
    QFileInfo fileInfo(path);
634

635
    if ( path.contains("openboardtool://"))
636 637
        return FEATURE_INTERNAL;

638 639 640 641
    if (!fileInfo.exists()) {
        return FEATURE_INVALID;
    }

642
    UBFeatureElementType fileType = FEATURE_INVALID;
643 644 645 646 647 648
    QString fileName = fileInfo.fileName();
    QString mimeString = UBFileSystemUtils::mimeTypeFromFileName(fileName);

    if ( mimeString.contains("application")) {
        if (mimeString.contains("application/search")) {
            fileType = FEATURE_SEARCH;
649 650
        } else if (mimeString.contains("application/x-shockwave-flash")) {
            fileType = FEATURE_FLASH;
651 652 653
        } else {
            fileType = FEATURE_INTERACTIVE;
        }
654 655 656 657 658 659 660 661 662 663 664
    } else if (mimeString.contains("audio")) {
        fileType = FEATURE_AUDIO;
    } else if (mimeString.contains("video")) {
        fileType = FEATURE_VIDEO;
    } else if (mimeString.contains("image")) {
        fileType = FEATURE_IMAGE;
    } else if (fileInfo.isDir()) {
        fileType = FEATURE_FOLDER;
    } else {
        fileType = FEATURE_INVALID;
    }
665

Claudio Valerio's avatar
Claudio Valerio committed
666
    return fileType;
667 668
}

669
QImage UBFeaturesController::getIcon(const QString &path, UBFeatureElementType pFType = FEATURE_INVALID)
Anna Udovichenko's avatar
Anna Udovichenko committed
670
{
671 672
    if (pFType == FEATURE_FOLDER) {
        return QImage(":images/libpalette/folder.svg");
673
    } else if (pFType == FEATURE_INTERACTIVE || pFType == FEATURE_SEARCH) {
Yimgo's avatar
Yimgo committed
674
        return QImage(UBGraphicsWidgetItem::iconFilePath(QUrl::fromLocalFile(path)));
675 676
    } else if (pFType == FEATURE_INTERNAL) {
        return QImage(UBToolsManager::manager()->iconFromToolId(path));
677 678
    } else if (pFType == FEATURE_FLASH) {
        return QImage(":images/libpalette/FlashIcon.svg");
679 680 681 682 683 684 685 686 687 688 689 690
    } else if (pFType == FEATURE_AUDIO) {
        return QImage(":images/libpalette/soundIcon.svg");
    } else if (pFType == FEATURE_VIDEO) {
        return QImage(":images/libpalette/movieIcon.svg");
    } else if (pFType == FEATURE_IMAGE) {
        QImage pix(path);
        if (pix.isNull()) {
            pix = QImage(":images/libpalette/notFound.png");
        } else {
            pix = pix.scaledToWidth(qMin(UBSettings::maxThumbnailWidth, pix.width()));
        }
        return pix;
691 692
    }

693
    return QImage(":images/libpalette/notFound.png");
Anna Udovichenko's avatar
Anna Udovichenko committed
694 695
}

696 697
bool UBFeaturesController::isDeletable( const QUrl &url )
{
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
    UBFeatureElementType type = fileTypeFromUrl(fileNameFromUrl(url));
    return type == FEATURE_AUDIO
            || type == FEATURE_VIDEO
            || type == FEATURE_IMAGE
            || type == FEATURE_ITEM;
}

QString UBFeaturesController::categoryNameForVirtualPath(const QString &str)
{
    QString result;
    int ind = str.lastIndexOf("/");
    if (ind != -1) {
        result = str.right(str.count() - ind - 1);
    }
    return result;
713 714
}

715
QImage UBFeaturesController::createThumbnail(const QString &path)
Anna Udovichenko's avatar
Anna Udovichenko committed
716
{
717
    QString thumbnailPath = path;
Anna Udovichenko's avatar
Anna Udovichenko committed
718 719
    QString mimetype = UBFileSystemUtils::mimeTypeFromFileName(path);

720
    if ( mimetype.contains("audio" )) {
Anna Udovichenko's avatar
Anna Udovichenko committed
721
        thumbnailPath = ":images/libpalette/soundIcon.svg";
722
    } else if ( mimetype.contains("video")) {
Anna Udovichenko's avatar
Anna Udovichenko committed
723
        thumbnailPath = ":images/libpalette/movieIcon.svg";
724 725 726 727 728 729 730 731
    } else {
        QImage pix(path);
        if (!pix.isNull()) {
            pix = pix.scaledToWidth(qMin(UBSettings::maxThumbnailWidth, pix.width()), Qt::SmoothTransformation);
            return pix;

        } else {
            thumbnailPath = ":images/libpalette/notFound.png";
Anna Udovichenko's avatar
Anna Udovichenko committed
732
        }
733

Anna Udovichenko's avatar
Anna Udovichenko committed
734 735
    }

736
    return QImage(thumbnailPath);
Anna Udovichenko's avatar
Anna Udovichenko committed
737 738
}

739
void UBFeaturesController::importImage(const QImage &image, const QString &fileName)
740
{
741 742 743
    importImage(image, currentElement, fileName);
}

744

745 746 747
void UBFeaturesController::importImage( const QImage &image, const UBFeature &destination, const QString &fileName )
{
    QString mFileName = fileName;
748 749
    QString filePath;
    UBFeature dest = destination;
750 751
    if (mFileName.isNull()) {
        QDateTime now = QDateTime::currentDateTime();
752 753
        static int imageCounter = 0;
        mFileName  = tr("ImportedImage") + "-" + now.toString("dd-MM-yyyy hh-mm-ss");
754
        
755 756 757 758 759 760
        filePath = dest.getFullPath().toLocalFile() + "/" + mFileName;

        if (QFile::exists(filePath+".png"))
            mFileName += QString("-[%1]").arg(++imageCounter);
        else
            imageCounter = 0;
761
        
762
        mFileName += ".png";
763
    }
764
    
765 766 767

    if ( !destination.getFullVirtualPath().startsWith( picturesElement.getFullVirtualPath(), Qt::CaseInsensitive ) )
    {
Claudio Valerio's avatar
Claudio Valerio committed
768
        dest = picturesElement;
769 770
    }

771
    filePath = dest.getFullPath().toLocalFile() + "/" + mFileName;
772 773
    image.save(filePath);

774
    QImage thumb = createThumbnail( filePath );
Ilia Ryabokon's avatar
Ilia Ryabokon committed
775
    UBFeature resultItem =  UBFeature( dest.getFullVirtualPath() + "/" + mFileName, thumb, mFileName,
776
        QUrl::fromLocalFile( filePath ), FEATURE_ITEM );
777 778 779

    featuresModel->addItem(resultItem);

780 781
}

782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
QStringList UBFeaturesController::getFileNamesInFolders()
{
    QStringList strList;

    Q_ASSERT(curListModel);

    for (int i = 0; i < curListModel->rowCount(QModelIndex()); i++) {
        QModelIndex ind = curListModel->index(i, 0);
        if (!ind.isValid()) {
            qDebug() << "incorrect model index catched";
            continue;
        }
        UBFeature curFeature = curListModel->data(ind, Qt::UserRole + 1).value<UBFeature>();
        if (curFeature.getType() == FEATURE_FOLDER) {
            strList << QFileInfo(curFeature.getFullPath().toLocalFile()).fileName();
        }
    }

    return strList;
}

803
void UBFeaturesController::addNewFolder(QString name)
804
{
805
    QString path = currentElement.getFullPath().toLocalFile() + "/" + name;
806

Aleksei Kanash's avatar
Aleksei Kanash committed
807 808 809 810 811
    if ("/root" == currentElement.getFullVirtualPath())
    {
        return;
    }

812
    if(!QFileInfo(path).exists()) {
813
        QDir().mkpath(path);
Claudio Valerio's avatar
Claudio Valerio committed
814
    }
Ilia Ryabokon's avatar
Ilia Ryabokon committed
815
    UBFeature newFeatureFolder = UBFeature( currentElement.getFullVirtualPath() + "/" + name, QImage(":images/libpalette/folder.svg"),
816 817
                                            name, QUrl::fromLocalFile( path ), FEATURE_FOLDER );

Ilia Ryabokon's avatar
Ilia Ryabokon committed
818
    featuresModel->addItem(newFeatureFolder);
819
    featuresProxyModel->invalidate();
820 821
}

Anna Udovichenko's avatar
Anna Udovichenko committed
822 823
void UBFeaturesController::addItemToPage(const UBFeature &item)
{
824
    UBApplication::boardController->downloadURL( item.getFullPath() );
Anna Udovichenko's avatar
Anna Udovichenko committed
825 826
}

827 828
void UBFeaturesController::addItemAsBackground(const UBFeature &item)
{
829
    UBApplication::boardController->downloadURL( item.getFullPath(), QString(), QPointF(), QSize(), true );
830 831
}

832
UBFeature UBFeaturesController::getDestinationFeatureForUrl( const QUrl &url )
Anna Udovichenko's avatar
Anna Udovichenko committed
833
{
834
    QString mimetype = UBFileSystemUtils::mimeTypeFromFileName( url.toString() );
835 836
    return getDestinationFeatureForMimeType(mimetype);
}
Anna Udovichenko's avatar
Anna Udovichenko committed
837

838 839 840
UBFeature UBFeaturesController::getDestinationFeatureForMimeType(const QString &pMmimeType)
{
    if ( pMmimeType.contains("audio") )
Anna Udovichenko's avatar
Anna Udovichenko committed
841
        return audiosElement;
842
    if ( pMmimeType.contains("video") )
Anna Udovichenko's avatar
Anna Udovichenko committed
843
        return moviesElement;
844
    else if ( pMmimeType.contains("image") || pMmimeType.isEmpty())
Anna Udovichenko's avatar
Anna Udovichenko committed
845
        return picturesElement;
846 847 848
    else if ( pMmimeType.contains("application") )
    {
        if ( pMmimeType.contains( "x-shockwave-flash") )
Anna Udovichenko's avatar
Anna Udovichenko committed
849 850 851 852 853 854 855
            return flashElement;
        else
            return interactElement;
    }
    return UBFeature();
}

856
void UBFeaturesController::addDownloadedFile(const QUrl &sourceUrl, const QByteArray &pData, const QString pContentSource, const QString pTitle)
857
{
858
    UBFeature dest = getDestinationFeatureForMimeType(pContentSource);
859

Ilia Ryabokon's avatar
Ilia Ryabokon committed
860
    if (dest == UBFeature())
861 862
        return;

863 864
    QString fileName;
    QString filePath;
865
    
866 867
    //Audio item
    if(dest == picturesElement) {
868

869 870 871 872
        QString UniqName = uniqNameForFeature(dest, adjustName(pTitle), ".jpg");
        fileName =  !UniqName.isNull()
                ? UniqName
                : tr("ImportedImage") + "-" + QDateTime::currentDateTime().toString("dd-MM-yyyy hh-mm-ss")+ ".jpg";
873

874 875 876
        filePath = dest.getFullPath().toLocalFile() + "/" + fileName;

        QImage::fromData(pData).save(filePath);
877

878
        UBFeature downloadedFeature = UBFeature(dest.getFullVirtualPath() + "/" + fileName, getIcon( filePath, fileTypeFromUrl(filePath)),
879 880 881 882
                                                 fileName, QUrl::fromLocalFile(filePath), FEATURE_ITEM);
        if (downloadedFeature != UBFeature()) {
            featuresModel->addItem(downloadedFeature);
        }
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899

    } else {
        fileName = QFileInfo( sourceUrl.toString() ).fileName();
        filePath = dest.getFullPath().toLocalFile() + "/" + fileName;

        QFile file( filePath );
        if ( file.open(QIODevice::WriteOnly ))
        {
            file.write(pData);
            file.close();

            UBFeature downloadedFeature = UBFeature(dest.getFullVirtualPath() + "/" + fileName, getIcon( filePath, fileTypeFromUrl(filePath)),
                                                    fileName, QUrl::fromLocalFile(filePath), FEATURE_ITEM);
            if (downloadedFeature != UBFeature()) {
                featuresModel->addItem(downloadedFeature);
            }
        }
900
    }
901

902 903
}

Anna Udovichenko's avatar
Anna Udovichenko committed
904 905
UBFeature UBFeaturesController::moveItemToFolder( const QUrl &url, const UBFeature &destination )
{
Claudio Valerio's avatar
Claudio Valerio committed
906 907 908
    /*UBFeature newElement = copyItemToFolder( url, destination );
    deleteItem( url );
    return newElement;*/
Anna Udovichenko's avatar
Anna Udovichenko committed
909 910
    QString sourcePath = url.toLocalFile();

Claudio Valerio's avatar
Claudio Valerio committed
911
    Q_ASSERT( QFileInfo( sourcePath ).exists() );
Anna Udovichenko's avatar
Anna Udovichenko committed
912

Ilia Ryabokon's avatar
Ilia Ryabokon committed
913
    UBFeature possibleDest = getDestinationFeatureForUrl(url);
Anna Udovichenko's avatar
Anna Udovichenko committed
914

Claudio Valerio's avatar
Claudio Valerio committed
915
    UBFeature dest = destination;
Anna Udovichenko's avatar
Anna Udovichenko committed
916

917
    if ( destination != trashElement && 
Claudio Valerio's avatar
Claudio Valerio committed
918 919 920 921
        !destination.getFullVirtualPath().startsWith( possibleDest.getFullVirtualPath(), Qt::CaseInsensitive ) )
    {
        dest = possibleDest;
    }
Anna Udovichenko's avatar
Anna Udovichenko committed
922

Claudio Valerio's avatar
Claudio Valerio committed
923
    QString name = QFileInfo( sourcePath ).fileName();
Anna Udovichenko's avatar
Anna Udovichenko committed
924
    QString destPath = dest.getFullPath().toLocalFile();
Claudio Valerio's avatar
Claudio Valerio committed
925 926
    QString destVirtualPath = dest.getFullVirtualPath();
    QString newFullPath = destPath + "/" + name;
Anna Udovichenko's avatar
Anna Udovichenko committed
927 928
    if ( sourcePath.compare( newFullPath, Qt::CaseInsensitive ) )
    {
Claudio Valerio's avatar
Claudio Valerio committed
929
        QFile( sourcePath ).copy( newFullPath );
Anna Udovichenko's avatar
Anna Udovichenko committed
930 931 932
        deleteItem( url );
    }

933
    QImage thumb = getIcon( newFullPath );
934
    
Anna Udovichenko's avatar
Anna Udovichenko committed
935
    UBFeatureElementType type = FEATURE_ITEM;
936
    if ( UBFileSystemUtils::mimeTypeFromFileName( newFullPath ).contains("application") ) 
Anna Udovichenko's avatar
Anna Udovichenko committed
937
        type = FEATURE_INTERACTIVE;
Ilia Ryabokon's avatar
Ilia Ryabokon committed
938
    UBFeature newElement( destVirtualPath + "/" + name, thumb, name, QUrl::fromLocalFile( newFullPath ), type );
939 940 941 942 943
    return newElement;
}

void UBFeaturesController::rescanModel()
{
944
    featuresModel->removeRows(0, featuresList->count());
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959

    //Could implement infolder scanning for better perfomance
    scanFS();
    refreshModels();
}

void UBFeaturesController::siftElements(const QString &pSiftValue)
{
    featuresProxyModel->setFilterFixedString(pSiftValue);
    featuresProxyModel->invalidate();

    featuresPathModel->setPath(pSiftValue);
    featuresPathModel->invalidate();
}

960
UBFeature UBFeaturesController::getFeature(const QModelIndex &index, const QString &listName)
961
{
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
//    QSortFilterProxyModel *model = qobject_cast<QSortFilterProxyModel *>(pOnView->model());
    QAbstractItemModel *model = 0;
    if (listName == UBFeaturesWidget::objNamePathList) {
        model = featuresPathModel;
    } else if (listName == UBFeaturesWidget::objNameFeatureList) {
        model = curListModel;
    }

    if (model) {
        return model->data(index, Qt::UserRole + 1).value<UBFeature>();
    }

    return UBFeature();


//    return pOnView->model()->data(index, Qt::UserRole + 1).value<UBFeature>();  /*featuresSearchModel->data(index, Qt::UserRole + 1).value<UBFeature>()*/;
978 979 980 981 982 983 984 985
}

void UBFeaturesController::searchStarted(const QString &pattern, QListView *pOnView)
{
    if (pattern.isEmpty()) {

        pOnView->setModel(featuresProxyModel);
        featuresProxyModel->invalidate();
986 987
        curListModel = featuresProxyModel;
    } else if ( pattern.size() > 1 ) {
988

989
        //        featuresSearchModel->setFilterPrefix(currentElement.getFullVirtualPath());
990 991 992
        featuresSearchModel->setFilterWildcard( "*" + pattern + "*" );
        pOnView->setModel(featuresSearchModel );
        featuresSearchModel->invalidate();
993
        curListModel = featuresSearchModel;
994 995 996 997 998 999 1000 1001
    }
}

void UBFeaturesController::refreshModels()
{
    featuresProxyModel->invalidate();
    featuresSearchModel->invalidate();
    featuresPathModel->invalidate();
1002 1003 1004 1005
}

UBFeature UBFeaturesController::copyItemToFolder( const QUrl &url, const UBFeature &destination )
{
1006
    QString sourcePath = url.toLocalFile();
1007

1008
    Q_ASSERT( QFileInfo( sourcePath ).exists() );
1009

1010
    UBFeature possibleDest = getDestinationFeatureForUrl( url );
Anna Udovichenko's avatar
Anna Udovichenko committed
1011

1012
    UBFeature dest = destination;
Anna Udovichenko's avatar
Anna Udovichenko committed
1013

1014 1015 1016 1017 1018
    if ( destination != trashElement &&
        !destination.getFullVirtualPath().startsWith( possibleDest.getFullVirtualPath(), Qt::CaseInsensitive ) )
    {
        dest = possibleDest;
    }
Anna Udovichenko's avatar
Anna Udovichenko committed
1019

1020
    QString name = QFileInfo(sourcePath).fileName();
1021
    QString destPath = dest.getFullPath().toLocalFile();
1022 1023
    QString destVirtualPath = dest.getFullVirtualPath();
    QString newFullPath = destPath + "/" + name;
1024 1025
    if (!sourcePath.compare(newFullPath, Qt::CaseInsensitive))
        QFile(sourcePath).copy(newFullPath);
1026

1027
    QImage thumb = getIcon(newFullPath);
1028

Ivan Ilin's avatar
Ivan Ilin committed
1029
    UBFeatureElementType type = FEATURE_ITEM;
1030
    if (UBFileSystemUtils::mimeTypeFromFileName(newFullPath).contains("application"))
Ivan Ilin's avatar
Ivan Ilin committed
1031
        type = FEATURE_INTERACTIVE;
Ilia Ryabokon's avatar
Ilia Ryabokon committed
1032
    UBFeature newElement( destVirtualPath + "/" + name, thumb, name, QUrl::fromLocalFile( newFullPath ), type );
1033
    return newElement;
Anna Udovichenko's avatar
Anna Udovichenko committed
1034
}
1035

1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
void UBFeaturesController::moveExternalData(const QUrl &url, const UBFeature &destination)
{
    QString sourcePath = url.toLocalFile();

    Q_ASSERT( QFileInfo( sourcePath ).exists() );

    UBFeature possibleDest = getDestinationFeatureForUrl(url);

    UBFeature dest = destination;

1046 1047 1048
    if ( destination != trashElement && destination != UBFeature()
       /*&& !destination.getFullVirtualPath().startsWith( possibleDest.getFullVirtualPath(), Qt::CaseInsensitive )*/ )
    {
1049
        dest = possibleDest;
1050
    }
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068

    UBFeatureElementType type = fileTypeFromUrl(sourcePath);

    if (type == FEATURE_FOLDER) {
        return;
    }

    QString name = QFileInfo(sourcePath).fileName();
    QString destPath = dest.getFullPath().toLocalFile();
    QString destVirtualPath = dest.getFullVirtualPath();
    QString newFullPath = destPath + "/" + name;

    if (!sourcePath.compare(newFullPath, Qt::CaseInsensitive) || !UBFileSystemUtils::copy(sourcePath, newFullPath)) {
        return;
    }

    Q_ASSERT(QFileInfo(newFullPath).exists());

1069
    QImage thumb = getIcon(newFullPath, type);
Ilia Ryabokon's avatar
Ilia Ryabokon committed
1070
    UBFeature newElement(destVirtualPath + "/" + name, thumb, name, QUrl::fromLocalFile(newFullPath), type);
1071 1072 1073 1074

    featuresModel->addItem(newElement);
}

1075
void UBFeaturesController::deleteItem(const QUrl &url)
Anna Udovichenko's avatar
Anna Udovichenko committed
1076
{
1077 1078
    QString path = url.toLocalFile();
    Q_ASSERT( QFileInfo( path ).exists() );
Anna Udovichenko's avatar
Anna Udovichenko committed
1079

Claudio Valerio's avatar
Claudio Valerio committed
1080
    QString thumbnailPath = UBFileSystemUtils::thumbnailPath( path );
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
    if ( thumbnailPath.length() && QFileInfo( thumbnailPath ).exists()) {
        if (QFileInfo(thumbnailPath).isFile()) {
            QFile::remove(thumbnailPath);
        } else if (QFileInfo(thumbnailPath).isDir()){
            if (!UBFileSystemUtils::deleteDir(thumbnailPath)) {
                qDebug() << "Not able to delete directory";
             }
        }
    }
    if (QFileInfo(path).isFile()) {
        QFile::remove( path );

    } else if (QFileInfo(path).isDir()) {
        UBFileSystemUtils::deleteDir(path);
Anna Udovichenko's avatar
Anna Udovichenko committed
1095
    }
1096 1097 1098 1099 1100 1101 1102
}

void UBFeaturesController::deleteItem(const UBFeature &pFeature)
{
    QUrl sourceUrl = pFeature.getFullPath();
    featuresModel->deleteItem(pFeature);
    deleteItem(sourceUrl);
1103
}
Anna Udovichenko's avatar
Anna Udovichenko committed
1104

1105 1106
bool UBFeaturesController::isTrash( const QUrl &url )
{
1107
    return url.toLocalFile().startsWith( trashDirectoryPath.toLocalFile() );
Anna Udovichenko's avatar
Anna Udovichenko committed
1108
}
1109 1110 1111 1112 1113 1114
void UBFeaturesController::moveToTrash(UBFeature feature, bool deleteManualy)
{
    featuresModel->moveData(feature, trashElement, Qt::MoveAction, deleteManualy);
    removeFromFavorite(feature.getFullPath());
    featuresModel->deleteFavoriteItem(UBFeaturesController::fileNameFromUrl(feature.getFullPath()));
}
Anna Udovichenko's avatar
Anna Udovichenko committed
1115 1116 1117

UBFeaturesController::~UBFeaturesController()
{
1118 1119 1120 1121 1122
    if (featuresList) {
        delete featuresList;
    }
}

Claudio Valerio's avatar
Claudio Valerio committed
1123
void UBFeaturesController::assignFeaturesListView(UBFeaturesListView *pList)
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
{
    pList->setDragDropMode( QAbstractItemView::DragDrop );
    pList->setSelectionMode( QAbstractItemView::ContiguousSelection );

    pList->setResizeMode( QListView::Adjust );
    pList->setViewMode( QListView::IconMode );

    pList->setIconSize(QSize(UBFeaturesWidget::defaultThumbnailSize, UBFeaturesWidget::defaultThumbnailSize));
    pList->setGridSize(QSize(UBFeaturesWidget::defaultThumbnailSize + 20, UBFeaturesWidget::defaultThumbnailSize + 20));

    itemDelegate = new UBFeaturesItemDelegate(this, pList);
    pList->setItemDelegate(itemDelegate);

    pList->setModel(featuresProxyModel);
1138
    curListModel = featuresProxyModel;
Anna Udovichenko's avatar
Anna Udovichenko committed
1139
}
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160

void UBFeaturesController::assignPathListView(UBFeaturesListView *pList)
{
    pList->setViewMode(QListView::IconMode );
    pList->setIconSize(QSize(UBFeaturesWidget::defaultThumbnailSize - 10, UBFeaturesWidget::defaultThumbnailSize - 10));
    pList->setGridSize(QSize(UBFeaturesWidget::defaultThumbnailSize + 10, UBFeaturesWidget::defaultThumbnailSize - 10));
    pList->setFixedHeight(60);
    pList->setSelectionMode(QAbstractItemView::NoSelection);
    pList->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    pList->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
    pList->setFlow(QListView::LeftToRight);
    pList->setWrapping(false);
    pList->setDragDropMode(QAbstractItemView::DropOnly);

    pList->setModel( featuresPathModel);

    pathItemDelegate = new UBFeaturesPathItemDelegate(this);
    pList->setItemDelegate(pathItemDelegate);
}