Exemple #1
0
void KWin::Script::slotScriptLoadedFromFile()
{
    QFutureWatcher<QByteArray> *watcher = dynamic_cast< QFutureWatcher< QByteArray>* >(sender());
    if (!watcher) {
        // not invoked from a QFutureWatcher
        return;
    }
    if (watcher->result().isNull()) {
        // do not load empty script
        deleteLater();
        watcher->deleteLater();
        return;
    }
    QScriptValue optionsValue = m_engine->newQObject(options, QScriptEngine::QtOwnership,
                            QScriptEngine::ExcludeSuperClassContents | QScriptEngine::ExcludeDeleteLater);
    m_engine->globalObject().setProperty(QStringLiteral("options"), optionsValue, QScriptValue::Undeletable);
    m_engine->globalObject().setProperty(QStringLiteral("QTimer"), constructTimerClass(m_engine));
    QObject::connect(m_engine, SIGNAL(signalHandlerException(QScriptValue)), this, SLOT(sigException(QScriptValue)));
    KWin::MetaScripting::supplyConfig(m_engine);
    installScriptFunctions(m_engine);

    QScriptValue ret = m_engine->evaluate(QString::fromUtf8(watcher->result()));

    if (ret.isError()) {
        sigException(ret);
        deleteLater();
    }

    watcher->deleteLater();
    setRunning(true);
    m_starting = false;
}
void EditTagDialog::SetSongsFinished() {
  QFutureWatcher<QList<Data> >* watcher =
      dynamic_cast<QFutureWatcher<QList<Data> >*>(sender());
  if (!watcher) return;
  watcher->deleteLater();

  if (!SetLoading(QString())) return;

  data_ = watcher->result();
  if (data_.count() == 0) {
    // If there were no valid songs, disable everything
    ui_->song_list->setEnabled(false);
    ui_->tab_widget->setEnabled(false);

    // Show a summary with empty information
    UpdateSummaryTab(Song());
    ui_->tab_widget->setCurrentWidget(ui_->summary_tab);

    SetSongListVisibility(false);
    return;
  }

  // Add the filenames to the list
  for (const Data& data : data_) {
    ui_->song_list->addItem(data.current_.basefilename());
  }

  // Select all
  ui_->song_list->setCurrentRow(0);
  ui_->song_list->selectAll();

  // Hide the list if there's only one song in it
  SetSongListVisibility(data_.count() != 1);
}
void SpellCheckerCore::futureFinished()
{
  /* Get the watcher from the sender() of the signal that invoked this slot.
   * reinterpret_cast is used since qobject_cast is not valid of template
   * classes since the template class does not have the Q_OBJECT macro. */
  QFutureWatcher<WordList>* watcher = reinterpret_cast<QFutureWatcher<WordList>*>( sender() );
  if( watcher == nullptr ) {
    return;
  }

  if( d->shuttingDown == true ) {
    /* Application shutting down, should not try something */
    return;
  }
  if( watcher->isCanceled() == true ) {
    /* Application is shutting down */
    return;
  }
  /* Get the list of words with spelling mistakes from the future. */
  WordList checkedWords = watcher->result();
  QMutexLocker locker( &d->futureMutex );
  /* Recheck again after getting the lock. */
  if( d->shuttingDown == true ) {
    return;
  }
  /* Get the file name associated with this future and the misspelled
   * words. */
  FutureWatcherMapIter iter = d->futureWatchers.find( watcher );
  if( iter == d->futureWatchers.end() ) {
    return;
  }
  QString fileName = iter.value();
  /* Remove the watcher from the list of running watchers and the file that
   * kept track of the file getting spell checked. */
  d->futureWatchers.erase( iter );
  d->filesInProcess.removeAll( fileName );
  /* Check if the file was scheduled for a re-check. As discussed previously,
   * if a spell check was requested for a file that had a future already in
   * progress, it was scheduled for a re-check as soon as the in progress one
   * completes. If it was scheduled, restart it using the normal slot. */
  QHash<QString, WordList>::iterator waitingIter = d->filesWaitingForProcess.find( fileName );
  if( waitingIter != d->filesWaitingForProcess.end() ) {
    WordList wordsToSpellCheck = waitingIter.value();
    /* remove the file and words from the scheduled list. */
    d->filesWaitingForProcess.erase( waitingIter );
    locker.unlock();
    /* Invoke the method to make sure that it gets called from the main thread.
     * This will most probably be already in the main thread, but to make sure
     * it is done like this. */
    this->metaObject()->invokeMethod( this
                                      , "spellcheckWordsFromParser"
                                      , Qt::QueuedConnection
                                      , Q_ARG( QString, fileName )
                                      , Q_ARG( SpellChecker::WordList, wordsToSpellCheck ) );
  }
  locker.unlock();
  watcher->deleteLater();
  /* Add the list of misspelled words to the mistakes model */
  addMisspelledWords( fileName, checkedWords );
}
void TrackSelectionDialog::AcceptFinished() {
  QFutureWatcher<void>* watcher = dynamic_cast<QFutureWatcher<void>*>(sender());
  if (!watcher) return;
  watcher->deleteLater();

  SetLoading(QString());
  QDialog::accept();
}
void SymbolsFindFilter::finish()
{
    QFutureWatcher<SearchResultItem> *watcher =
            static_cast<QFutureWatcher<SearchResultItem> *>(sender());
    SearchResult *search = m_watchers.value(watcher);
    if (search)
        search->finishSearch(watcher->isCanceled());
    m_watchers.remove(watcher);
    watcher->deleteLater();
}
void MapReduceProgress::operationFinished()
{
	QFutureWatcher<void>* watcher = (QFutureWatcher<void>*) sender();
	
	m_model->removeRow(itemForFuture(watcher->future())->row());
	watcher->deleteLater();
	
	if (m_model->rowCount() == 0)
		accept();
}
Exemple #7
0
void AttachDialog::updateProcessesFinished()
{
  QFutureWatcher<ProcDataList>* watcher = dynamic_cast<QFutureWatcher<ProcDataList>*>(sender());
  Q_ASSERT(watcher);
  ui.stackedWidget->setCurrentWidget(ui.listViewPage);
  const int oldPid = pid();
  m_model->mergeProcesses(watcher->result());
  if (oldPid != pid()) {
    ui.view->setCurrentIndex(QModelIndex());
  }
  watcher->deleteLater();
}
void QgsDemHeightMapGenerator::onFutureFinished()
{
  QFutureWatcher<QByteArray> *fw = static_cast<QFutureWatcher<QByteArray>*>( sender() );
  Q_ASSERT( fw );
  Q_ASSERT( mJobs.contains( fw ) );
  JobData jobData = mJobs.value( fw );

  mJobs.remove( fw );
  fw->deleteLater();

  QByteArray data = jobData.future.result();
  emit heightMapReady( jobData.jobId, data );
}
Exemple #9
0
void PrettyImage::ImageScaled() {
  QFutureWatcher<QImage>* watcher =
      reinterpret_cast<QFutureWatcher<QImage>*>(sender());
  if (!watcher) return;
  watcher->deleteLater();

  thumbnail_ = QPixmap::fromImage(watcher->result());
  state_ = State_Finished;

  updateGeometry();
  update();
  emit Loaded();
}
Exemple #10
0
bool OrganiseDialog::SetFilenames(const QStringList& filenames) {
  songs_future_ =
      QtConcurrent::run(this, &OrganiseDialog::LoadSongsBlocking, filenames);
  QFutureWatcher<SongList>* watcher = new QFutureWatcher<SongList>(this);
  watcher->setFuture(songs_future_);
  NewClosure(watcher, SIGNAL(finished()), [=]() {
    SetSongs(songs_future_.result());
    watcher->deleteLater();
  });

  SetLoadingSongs(true);
  return true;
}
void AccountsWorker::createAccount(const User *user)
{
    qDebug() << "create account " << user;
    Q_EMIT requestFrameAutoHide(false);

    QFutureWatcher<CreationResult*> *watcher = new QFutureWatcher<CreationResult*>(this);
    connect(watcher, &QFutureWatcher<CreationResult*>::finished, [this, watcher] {
        CreationResult *result = watcher->result();
        Q_EMIT accountCreationFinished(result);
        Q_EMIT requestFrameAutoHide(true);
        watcher->deleteLater();
    });

    QFuture<CreationResult*> future = QtConcurrent::run(this, &AccountsWorker::createAccountInternal, user);
    watcher->setFuture(future);
}
void DownloadSizeFinder::watcherFinished()
{
    QFutureWatcher<DownloadFile>* w = static_cast<
            QFutureWatcher<DownloadFile>*>(sender());
    DownloadFile r = w->result();

    this->mutex.lock();
    if (r.error.isEmpty())
        this->files.insert(r.url, QString::number(r.size));
    else
        this->files.insert(r.url, "*" + r.error);
    this->mutex.unlock();

    emit this->downloadCompleted(r.url, r.size, r.error);

    w->deleteLater();
}
Exemple #13
0
void TaskDispatcher::removeFinishedWatchers(void)
{
  QMutexLocker locker(&mutex_);

  std::vector<QObject*> temp;
  for (size_t i = 0, i_end = active_watchers_.size(); i < i_end; ++ i)
  {
    QFutureWatcher<void>* watcher = dynamic_cast<QFutureWatcher<void>*>(active_watchers_[i]);
    if (!watcher->isFinished())
      temp.push_back(active_watchers_[i]);
    else
      watcher->deleteLater();
  }

  active_watchers_ = temp;

  return;
}
Exemple #14
0
void PluginEffectLoader::queryAndLoadAll()
{
    if (m_queryConnection) {
        return;
    }
    // perform querying for the services in a thread
    QFutureWatcher<QVector<KPluginMetaData>> *watcher = new QFutureWatcher<QVector<KPluginMetaData>>(this);
    m_queryConnection = connect(watcher, &QFutureWatcher<QVector<KPluginMetaData>>::finished, this,
        [this, watcher]() {
            const auto effects = watcher->result();
            for (const auto &effect : effects) {
                const LoadEffectFlags flags = readConfig(effect.pluginId(), effect.isEnabledByDefault());
                if (flags.testFlag(LoadEffectFlag::Load)) {
                    m_queue->enqueue(qMakePair(effect, flags));
                }
            }
            watcher->deleteLater();
            m_queryConnection = QMetaObject::Connection();
        },
        Qt::QueuedConnection);
    watcher->setFuture(QtConcurrent::run(this, &PluginEffectLoader::findAllEffects));
}
void DeviceProperties::UpdateFormatsFinished() {
  QFutureWatcher<bool>* watcher = static_cast<QFutureWatcher<bool>*>(sender());
  watcher->deleteLater();
  updating_formats_ = false;

  if (!watcher->future().result()) {
    supported_formats_.clear();
  }

  // Hide widgets if there are no supported types
  ui_->supported_formats_container->setVisible(!supported_formats_.isEmpty());
  ui_->transcode_unsupported->setEnabled(!supported_formats_.isEmpty());

  if (ui_->transcode_unsupported->isChecked() && supported_formats_.isEmpty()) {
    ui_->transcode_off->setChecked(true);
  }

  // Populate supported types list
  ui_->supported_formats->clear();
  for (Song::FileType type : supported_formats_) {
    QListWidgetItem* item = new QListWidgetItem(Song::TextForFiletype(type));
    ui_->supported_formats->addItem(item);
  }
  ui_->supported_formats->sortItems();

  // Set the format combobox item
  TranscoderPreset preset = Transcoder::PresetForFileType(
      Song::FileType(index_.data(DeviceManager::Role_TranscodeFormat).toInt()));
  if (preset.type_ == Song::Type_Unknown) {
    // The user hasn't chosen a format for this device yet, so work our way down
    // a list of some preferred formats, picking the first one that is supported
    preset = Transcoder::PresetForFileType(
        Transcoder::PickBestFormat(supported_formats_));
  }
  ui_->transcode_format->setCurrentIndex(
      ui_->transcode_format->findText(preset.name_));

  ui_->formats_stack->setCurrentWidget(ui_->formats_page);
}
Exemple #16
0
bool FileManager::removeRecursively(const QString &path)
{
    qCDebug(log, "Removing '%s'...", qPrintable(path));

    if (!QFileInfo(path).isDir()) {
        qCWarning(log, "'%s' is not a directory.", qPrintable(path));
        return false;
    }

    const QString deletePath = QStringLiteral("%1.%2.deleteme")
            .arg(path, QString::number(QDateTime::currentMSecsSinceEpoch()));

    if (!QDir().rename(path, deletePath)) {
        qCWarning(log, "Failed to rename '%s' to '%s'.", qPrintable(path), qPrintable(deletePath));
        return false;
    } else {
        qCDebug(log, "Renamed '%s' to '%s'.", qPrintable(path), qPrintable(deletePath));
    }


    QFutureWatcher<bool> *watcher = new QFutureWatcher<bool>();
    connect(watcher, &QFutureWatcher<bool>::finished, [=] {
        if (!watcher->result()) {
            qCWarning(log, "Failed to remove '%s'.", qPrintable(deletePath));
        } else {
            qCDebug(log, "Removed '%s'.", qPrintable(deletePath));
        }

        watcher->deleteLater();
    });

    watcher->setFuture(QtConcurrent::run([deletePath] {
        return QDir(deletePath).removeRecursively();
    }));

    return true;
}
Exemple #17
0
void SettingsDialog::removeDocsets(const QStringList &names)
{
    for (const QString &name : names) {
        const QString title = m_docsetRegistry->docset(name)->title();
        m_docsetRegistry->remove(name);

        const QDir dataDir(m_application->settings()->docsetPath);
        if (dataDir.exists()) {
            ui->docsetsProgress->show();
            ui->removeDocsetsButton->setEnabled(false);
            displayProgress();

            QFuture<bool> future = QtConcurrent::run([=] {
                QDir docsetDir(dataDir);
                return docsetDir.cd(name + QLatin1String(".docset"))
                        && docsetDir.removeRecursively();
            });
            QFutureWatcher<bool> *watcher = new QFutureWatcher<bool>();
            watcher->setFuture(future);
            connect(watcher, &QFutureWatcher<void>::finished, [=] {
                if (!watcher->result()) {
                    QMessageBox::warning(this, tr("Error"),
                                         QString(tr("Cannot delete docset <b>%1</b>!")).arg(title));
                }

                resetProgress();

                QListWidgetItem *listItem = findDocsetListItem(title);
                if (listItem)
                    listItem->setHidden(false);

                watcher->deleteLater();
            });
        }
    }
}
Exemple #18
0
void ClipboardJob::start()
{
    const QString operation = operationName();
    // first check for operations not needing an item
    if (operation == QLatin1String("clearHistory")) {
        m_klipper->slotAskClearHistory();
        setResult(true);
        emitResult();
        return;
    } else if (operation == QLatin1String("configureKlipper")) {
        m_klipper->slotConfigure();
        setResult(true);
        emitResult();
        return;
    }

    // other operations need the item
    HistoryItemConstPtr item = m_klipper->history()->find(QByteArray::fromBase64(destination().toUtf8()));
    if (item.isNull()) {
        setResult(false);
        emitResult();
        return;
    }
    if (operation == QLatin1String("select")) {
        m_klipper->history()->slotMoveToTop(item->uuid());
        setResult(true);
    } else if (operation == QLatin1String("remove")) {
        m_klipper->history()->remove(item);
        setResult(true);
    } else if (operation == QLatin1String("edit")) {
        connect(m_klipper, &Klipper::editFinished, this,
            [this, item](HistoryItemConstPtr editedItem, int result) {
                if (item != editedItem) {
                    // not our item
                    return;
                }
                setResult(result);
                emitResult();
            }
        );
        m_klipper->editData(item);
        return;
    } else if (operation == QLatin1String("barcode")) {
#ifdef HAVE_PRISON
        int pixelWidth = parameters().value(QStringLiteral("width")).toInt();
        int pixelHeight = parameters().value(QStringLiteral("height")).toInt();
        Prison::AbstractBarcode *code = nullptr;
        switch (parameters().value(QStringLiteral("barcodeType")).toInt()) {
        case 1: {
            code = Prison::createBarcode(Prison::DataMatrix);
            const int size = qMin(pixelWidth, pixelHeight);
            pixelWidth = size;
            pixelHeight = size;
            break;
        }
        case 2: {
            code = Prison::createBarcode(Prison::Code39);
            break;
        }
        case 3: {
            code = Prison::createBarcode(Prison::Code93);
            break;
        }
        case 0:
        default: {
            code = Prison::createBarcode(Prison::QRCode);
            const int size = qMin(pixelWidth, pixelHeight);
            pixelWidth = size;
            pixelHeight = size;
            break;
        }
        }
        if (code) {
            code->setData(item->text());
            QFutureWatcher<QImage> *watcher = new QFutureWatcher<QImage>(this);
            connect(watcher, &QFutureWatcher<QImage>::finished, this,
                [this, watcher, code] {
                    setResult(watcher->result());
                    watcher->deleteLater();
                    delete code;
                    emitResult();
                }
            );
            auto future = QtConcurrent::run(code, &Prison::AbstractBarcode::toImage, QSizeF(pixelWidth, pixelHeight));
            watcher->setFuture(future);
            return;
        } else {
            setResult(false);
        }
#else
        setResult(false);
#endif
    } else if (operation == QLatin1String("action")) {
        m_klipper->urlGrabber()->invokeAction(item);
        setResult(true);

    } else if (operation == s_previewKey) {
        const int pixelWidth = parameters().value(s_previewWidthKey).toInt();
        const int pixelHeight = parameters().value(s_previewHeightKey).toInt();
        QUrl url = parameters().value(s_urlKey).toUrl();
        qCDebug(KLIPPER_LOG) << "URL: " << url;
        KFileItem item(url);

        if (pixelWidth <= 0 || pixelHeight <= 0) {
            qCWarning(KLIPPER_LOG) << "Preview size invalid: " << pixelWidth << "x" << pixelHeight;
            iconResult(item);
            return;
        }

        if (!url.isValid() || !url.isLocalFile()) { // no remote files
            qCWarning(KLIPPER_LOG) << "Invalid or non-local url for preview: " << url;
            iconResult(item);
            return;
        }

        KFileItemList urls;
        urls << item;

        KIO::PreviewJob* job = KIO::filePreview(urls, QSize(pixelWidth, pixelHeight));
        job->setIgnoreMaximumSize(true);
        connect(job, &KIO::PreviewJob::gotPreview, this,
            [this](const KFileItem &item, const QPixmap &preview) {
                QVariantMap res;
                res.insert(s_urlKey, item.url());
                res.insert(s_previewKey, preview);
                res.insert(s_iconKey, false);
                res.insert(s_previewWidthKey, preview.size().width());
                res.insert(s_previewHeightKey, preview.size().height());
                setResult(res);
                emitResult();
            }
        );
        connect(job, &KIO::PreviewJob::failed, this,
            [this](const KFileItem &item) {
                iconResult(item);
            }
        );

        job->start();

        return;
    } else {
        setResult(false);
    }
    emitResult();
}
Exemple #19
0
void MainWindow::applyPatch(const QString &fileName)
{
    ui->btnPatch->setEnabled(false);
    ui->btnStart->setEnabled(false);

    ui->animation->start();

    QFutureWatcher<void> *future = new QFutureWatcher<void>();
    connect(future, &QFutureWatcher<void>::finished, [this,future]() {
        ui->animation->stop();

        ui->btnStart->setEnabled(true);
        ui->btnPatch->setEnabled(true);

        refTask = NULL;

        future->deleteLater();
    });

    future->setFuture(QtConcurrent::run([=](const QString &fileName) {
        QStringList args;
        QProcess task; refTask = &task;

        args << "x" << fileName << "-y" << "-o..\\";
        task.start("bin\\7za.exe", args);
        task.waitForFinished(-1);

        args.clear(); args << "*.pck.b64.files";
        QDir elementDir("..\\element");
        QStringList packs = elementDir.entryList(args, QDir::Dirs);

        for (int i = 0; i < packs.size(); i++)
        {
            QString source = packs.at(i).toLocal8Bit().constData();
            QString dest = source.left(source.indexOf('.'));
            QString pck = dest + ".pck";
            QString pkx = dest + ".pkx";

            QString originalWorkingDir = QDir::current().dirName();
            QDir::setCurrent("..\\element");

            if (QFile::exists(pkx))
            {
                // TODO: merge *.pck and *.pkx
                args.clear(); args << "/c" << "copy" << "/b" << pck+"+"+pkx << pck;
                task.start("cmd.exe", args);
                task.waitForFinished(-1);
                QFile::remove(pkx);
            }

            // TODO: merge source folder into *.pck
            args.clear(); args << "-pw" << "-ap" << source;
            task.start("bin\\sPCK.exe", args);
            task.waitForFinished(-1);

            // TODO: split *.pck into *.pkx
            if (QFile(pck).size() > 2147483392)
            {
                args.clear(); args << pck << "2147483392";
                task.start("bin\\split.exe", args);
                task.waitForFinished(-1);

                QFile::remove(pck);
                QFile::rename(pck + ".1", pck);
                QFile::rename(pck + ".2", pkx);
            }

            // TODO: delete source folder recursive
            QDir(source).removeRecursively();


            QDir::setCurrent(originalWorkingDir);
        }

    }, fileName));
}