bool StreamMail::LoadFile(const QString file) { ////qFatal(" unable to read ... "); bool filled = false; if (clear()) { QFile *f = new QFile(file); if (f->exists()) { ///// if (f->open(QIODevice::ReadOnly)) { //// read line by line if (f->isReadable()) { linenr = -1; while (!f->atEnd()) { linenr++; QByteArray crk = f->read(76); d->write(crk); } f->close(); d->write(QByteArray("\n--\n--\n--\n--")); } } else { qDebug() << "######## file errors:" << f->errorString() << "\n"; } } } if (d->bytesAvailable() > 23) { filled = true; } d->seek(0); return filled; }
void ExtractImages::acceptImage(DomImage *image) { QString format = image->elementData()->attributeFormat(); QString extension = format.left(format.indexOf(QLatin1Char('.'))).toLower(); QString fname = m_imagesDir.absoluteFilePath(image->attributeName() + QLatin1Char('.') + extension); *m_output << " <file>images/" << image->attributeName() << QLatin1Char('.') + extension << "</file>\n"; QFile f; f.setFileName(fname); const bool isXPM_GZ = format == QLatin1String("XPM.GZ"); QIODevice::OpenMode openMode = QIODevice::WriteOnly; if (isXPM_GZ) openMode |= QIODevice::Text; if (!f.open(openMode)) { fprintf(stderr, "%s: Error: Could not create image file %s: %s", qPrintable(m_option.messagePrefix()), qPrintable(fname), qPrintable(f.errorString())); return; } if (isXPM_GZ) { QTextStream *imageOut = new QTextStream(&f); imageOut->setCodec(QTextCodec::codecForName("UTF-8")); CPP::WriteIconData::writeImage(*imageOut, QString(), m_option.limitXPM_LineLength, image); delete imageOut; } else { CPP::WriteIconData::writeImage(f, image); } f.close(); }
void SaveBurstsDual(const QVector<BurstDual> &burstVectorDual, const QString filename) { QFile file; if(filename.isEmpty()) qFatal("SaveBursts: enter a valid filename"); else file.setFileName(filename); if(burstVectorDual.size()==0) AlexEvalLog::warning("No dual bursts to save!"); if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) AlexEvalLog::warning(file.errorString()); QTextStream out(&file); out.setRealNumberPrecision(11); out <<"# ALEX dual bursts\n# "<<burstVectorDual.size()<<" bursts were analyzed.\n"; out<<burstVectorDual.first().toStringHeader().c_str(); for(int i=0;i<burstVectorDual.size();++i) { out<<burstVectorDual.at(i).toString("",", ").c_str()<<"\n"; } AlexEvalLog::text(burstVectorDual.size()+"bursts written to file "+file.fileName()); file.close(); // out <<"# start time in s\tburst duration in ms\tproximity ratio\tstoichiometry ratio\tnumber of photons\tn_Dem_Dex\tn_Aem_Dex\tn_Dem_Aex\tn_Aem_Aex\tduration Dem in ms\tduration Aem in ms\tPR_RAW\tS_RAW\ttype\n"; // for(int i=0;i<burstVectorDual.size();++i) { // out <<burstVectorDual.at(i).startTime<<"\t"<<burstVectorDual.at(i).duration*1e3<<"\t" // <<burstVectorDual.at(i).proximityRatio<<"\t"<<burstVectorDual.at(i).stoichiometryRatio<<"\t"<<burstVectorDual.at(i).numberOfPhotons<<"\t" // <<burstVectorDual.at(i).n_Dem_Dex<<"\t"<<burstVectorDual.at(i).n_Aem_Dex<<"\t"<<burstVectorDual.at(i).n_Dem_Aex<<"\t"<<burstVectorDual.at(i).n_Aem_Aex<<"\t"<<burstVectorDual.at(i).durationDonor*1e3<<"\t"<<burstVectorDual.at(i).durationAcceptor*1e3<<"\t"<<burstVectorDual.at(i).proximityRatioRaw<<"\t"<<burstVectorDual.at(i).stoichiometryRatioRaw<<"\t"<<(int)burstVectorDual.at(i).type<<"\n"; // } }
/*------------------------------------------------------------------------------------------------- * on_buttonSaveFile_clicked -- *-----------------------------------------------------------------------------------------------*/ void SetupDialog::on_buttonSaveFile_clicked () { QByteArray ba = "Font="; ba += fontEdit->text (); ba += "\nConfig="; ba += configEdit->text (); ba += "\nBoot="; ba += bootEdit->text (); ba += '\n'; QString fileName = QFileDialog::getSaveFileName(this, "setup save file name", "", "setup (*.b4s)"); if (!fileName.endsWith (".b4s")) fileName.append (".b4s"); QFile file (fileName);; if (!file.open(QIODevice::WriteOnly)) { QMessageBox::warning(this, tr ("setup file"), tr ("Cannot create file %1:%2.") .arg(fileName) .arg(file.errorString())); return; } file.write (ba); file.close (); }
Document::Document (const QString& filename, QObject *plugin) : DocURL_ (QUrl::fromLocalFile (filename)) , Plugin_ (plugin) { QFile file (filename); if (!file.open (QIODevice::ReadOnly)) { qWarning () << Q_FUNC_INFO << "unable to open file" << file.fileName () << file.errorString (); return; } QDomDocument doc; if (!doc.setContent (file.readAll (), true)) { qWarning () << Q_FUNC_INFO << "malformed XML in" << filename; return; } FB2Converter conv (this, doc); auto textDoc = conv.GetResult (); SetDocument (textDoc); Info_ = conv.GetDocumentInfo (); TOC_ = conv.GetTOC (); }
void DomainContentBackupManager::setup() { for (auto& rule : _backupRules) { removeOldBackupVersions(rule); } auto backups = getAllBackups(); for (auto& backup : backups) { QFile backupFile { backup.absolutePath }; if (!backupFile.open(QIODevice::ReadOnly)) { qCritical() << "Could not open file:" << backup.absolutePath; qCritical() << " ERROR:" << backupFile.errorString(); continue; } QuaZip zip { &backupFile }; if (!zip.open(QuaZip::mdUnzip)) { qCritical() << "Could not open backup archive:" << backup.absolutePath; qCritical() << " ERROR:" << zip.getZipError(); continue; } for (auto& handler : _backupHandlers) { handler->loadBackup(backup.id, zip); } zip.close(); } for (auto& handler : _backupHandlers) { handler->loadingComplete(); } }
void AddressBook::chargerFichier() { QString nomFichier = QFileDialog::getOpenFileName(this, tr ("Charger depuis un fichier"), "", tr ("Carnet d'adresse (*.abk);;Tous les fichiers (*)")); if (nomFichier.isEmpty()) return; else { QFile fichier (nomFichier); if (!fichier.open(QIODevice::ReadOnly)) { QMessageBox::information(this, tr ("Erreur de chargement"), fichier.errorString()); return; } QDataStream in (&fichier); in.setVersion(QDataStream::Qt_4_7); listeContacts.empty(); in >> listeContacts; if (listeContacts.isEmpty()) { QMessageBox::information (this , tr ("Pas de contacts"), tr ("Aucun contact à importer dans le fichier")); } else { QMap<QString , QString>::iterator i = listeContacts.begin(); nomLineEdit->setText(i.key()); adresseTextEdit->setText(i.value()); } } updateInterface(NavigationMode); }
void MainWindow::checkAndGenerateNecessaryFile() { QDir dir; QString path = dir.absolutePath(); if(!dir.exists(path + "/data")) dir.mkdir(path + "/data"); if(!dir.exists(path + "/data/.temp")) dir.mkdir(path + "/data/.temp"); if(!dir.exists(path + "/data/.temp/VirtualFence")) dir.mkdir(path + "/data/.temp/VirtualFence"); QFile file; path = path + "/data/.temp/VirtualFence/"; if (!file.exists(path + "config.ini")) { QString fileName = path + "config.ini"; QFile file2(fileName); if (!file2.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("Create ini file"), tr("Cannot create ini file %1:\n%2.") .arg(fileName) .arg(file.errorString())); return; } //write the ini file content here QTextStream out(&file2); helper::writeDefautlVirtualFecingIni(out); file2.close(); } }
void AutomatedRssDownloader::on_importBtn_clicked() { QString selectedFilter {m_formatFilterJSON}; QString path = QFileDialog::getOpenFileName( this, tr("Import RSS rules"), QDir::homePath() , QString("%1;;%2").arg(m_formatFilterJSON, m_formatFilterLegacy), &selectedFilter); if (path.isEmpty() || !QFile::exists(path)) return; QFile file {path}; if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical( this, tr("I/O Error") , tr("Failed to open the file. Reason: %1").arg(file.errorString())); return; } const RSS::AutoDownloader::RulesFileFormat format { (selectedFilter == m_formatFilterJSON) ? RSS::AutoDownloader::RulesFileFormat::JSON : RSS::AutoDownloader::RulesFileFormat::Legacy }; try { RSS::AutoDownloader::instance()->importRules(file.readAll(),format); } catch (const RSS::ParsingError &error) { QMessageBox::critical( this, tr("Import Error") , tr("Failed to import the selected rules file. Reason: %1").arg(error.message())); } }
int QMacPasteboardMimeQt3Any::registerMimeType(const QString &mime) { if(!mime_registry.contains(mime)) { if(!loadMimeRegistry()) { qWarning("QMacPasteboardMimeAnyQt3Mime: Internal error"); return 0; } if(!mime_registry.contains(mime)) { if(!library_file.isOpen()) { if(!library_file.open(QIODevice::WriteOnly)) { qWarning("QMacPasteboardMimeAnyQt3Mime: Failure to open %s -- %s", library_file.fileName().toLatin1().constData(), library_file.errorString().toLatin1().constData()); return false; } } int ret = ++current_max; mime_registry_loaded = QFileInfo(library_file).lastModified(); QTextStream stream(&library_file); stream << mime << endl; stream << ret << endl; mime_registry.insert(mime, ret); library_file.flush(); //flush and set mtime return ret; } } return mime_registry[mime]; }
void StartupFirstPage::handleAccepted () { for (int i = 0; i < Ui_.Tree_->topLevelItemCount (); ++i) { QTreeWidgetItem *item = Ui_.Tree_->topLevelItem (i); if (item->checkState (0) != Qt::Checked) continue; QString set = item->data (0, RoleSet).toString (); QString filename = item->data (0, RoleFile).toString (); QString full = QString (":/resources/default/%1/%2") .arg (set) .arg (filename); QFile file (full); if (!file.open (QIODevice::ReadOnly)) { qWarning () << Q_FUNC_INFO << "could not open file for read only" << full << file.errorString (); continue; } QString contents = QTextCodec::codecForName ("UTF-8")-> toUnicode (file.readAll ()); Core::Instance ().HandleEntity (contents, static_cast<QLineEdit*> (Ui_.Tree_->itemWidget (item, 1))->text ()); } }
QStringList Read (const QString& path) { QFile file (path); if (!file.open (QIODevice::ReadOnly)) { qWarning () << Q_FUNC_INFO << "unable to open" << path << file.errorString (); return QStringList (); } QDomDocument doc; if (!doc.setContent (file.readAll ())) { qWarning () << Q_FUNC_INFO << "unable to parse" << path; return QStringList (); } QStringList result; auto track = doc.documentElement () .firstChildElement ("trackList") .firstChildElement ("track"); while (!track.isNull ()) { const auto& loc = track.firstChildElement ("location").text (); if (!loc.isEmpty ()) result << loc; track = track.nextSiblingElement ("track"); } return result; }
void TodoTab::handleImport () { const QString& filename = QFileDialog::getOpenFileName (this, tr ("Import tasks"), QDir::homePath (), tr ("iCalendar files (*.ics)")); QFile file (filename); if (!file.open (QIODevice::ReadOnly)) { QMessageBox::critical (this, tr ("Tasks import"), tr ("Unable to open %1: %2.") .arg ("<em>" + filename + "</em>") .arg (file.errorString ())); return; } const auto& items = ICalParser ().Parse (file.readAll ()); if (items.isEmpty ()) return; ItemsMergeDialog dia (items.size (), this); if (dia.exec () != QDialog::Accepted) return; auto storage = Core::Instance ().GetTodoManager ()->GetTodoStorage (); auto ourItems = storage->GetAllItems (); for (const auto& item : items) { const auto& itemId = item->GetID (); auto pos = std::find_if (ourItems.begin (), ourItems.end (), [&itemId] (const auto& ourItem) { return ourItem->GetID () == itemId; }); if (pos != ourItems.end ()) { if (dia.GetPriority () == ItemsMergeDialog::Priority::Imported) { (*pos)->CopyFrom (item); storage->HandleUpdated (*pos); } continue; } const auto& itemTitle = item->GetTitle (); pos = std::find_if (ourItems.begin (), ourItems.end (), [itemTitle] (const auto& ourItem) { return ourItem->GetTitle () == itemTitle; }); if (pos != ourItems.end ()) { if (dia.GetPriority () == ItemsMergeDialog::Priority::Imported && dia.GetSameTitle () == ItemsMergeDialog::SameTitle::Merge) { (*pos)->CopyFrom (item); storage->HandleUpdated (*pos); } continue; } storage->AddItem (item); } }
int createProject(const QString &outFileName) { QDir currentDir = QDir::current(); QString currentDirName = currentDir.dirName(); if (currentDirName.isEmpty()) currentDirName = QLatin1String("root"); QFile file; bool isOk = false; if (outFileName.isEmpty()) { isOk = file.open(stdout, QFile::WriteOnly | QFile::Text); } else { file.setFileName(outFileName); isOk = file.open(QFile::WriteOnly | QFile::Text); } if (!isOk) { fprintf(stderr, "Unable to open %s: %s\n", outFileName.isEmpty() ? qPrintable(outFileName) : "standard output", qPrintable(file.errorString())); return 1; } QTextStream out(&file); out << QLatin1String("<!DOCTYPE RCC><RCC version=\"1.0\">\n" "<qresource>\n"); // use "." as dir to get relative file pathes dumpRecursive(QDir(QLatin1String(".")), out); out << QLatin1String("</qresource>\n" "</RCC>\n"); return 0; }
QList<Filter> ParseToFilters (const QStringList& paths) { QList<Filter> result; for (const auto& filePath : paths) { QFile file (filePath); if (!file.open (QIODevice::ReadOnly)) { qWarning () << Q_FUNC_INFO << "could not open file" << filePath << file.errorString (); result << Filter (); continue; } const auto& data = QString::fromUtf8 (file.readAll ()); auto rawLines = data.split ('\n', QString::SkipEmptyParts); if (!rawLines.isEmpty ()) rawLines.removeAt (0); const auto& lines = Util::Map (rawLines, Util::QStringTrimmed {}); Filter f; std::for_each (lines.begin (), lines.end (), LineParser (&f)); f.SD_.Filename_ = QFileInfo (filePath).fileName (); result << f; } return result; }
QList<Filter> ParseToFilters (const QStringList& paths) { QList<Filter> result; for (const auto& filePath : paths) { QFile file (filePath); if (!file.open (QIODevice::ReadOnly)) { qWarning () << Q_FUNC_INFO << "could not open file" << filePath << file.errorString (); result << Filter (); continue; } const auto& data = QString::fromUtf8 (file.readAll ()); QStringList rawLines = data.split ('\n', QString::SkipEmptyParts); if (rawLines.size ()) rawLines.removeAt (0); QStringList lines; std::transform (rawLines.begin (), rawLines.end (), std::back_inserter (lines), [] (const QString& t) { return t.trimmed (); }); Filter f; std::for_each (lines.begin (), lines.end (), LineParser (&f)); f.SD_.Filename_ = QFileInfo (filePath).fileName (); result << f; } return result; }
/// Takes the error string from given file and emits an error indication. /// Closes the files and stops the copy. Always returns false bool error(QFile & f) { m_error = f.errorString(); m_error.append(QStringLiteral("(in %1 file").arg(f.objectName())); emit finished(false, m_error); close(); return false; }
int SaveBursts(const QVector<Burst> &burstVector, const BurstSearchParams_t BurstSearchParams, const QString filename) { QFile file; if(filename.isEmpty()) qFatal("SaveBursts: enter a valid filename"); else file.setFileName(filename); if(burstVector.size()==0) { AlexEvalLog::warning("vector is empty"); return EXIT_FAILURE; } if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) { AlexEvalLog::warning(file.errorString()); return EXIT_FAILURE; } QTextStream out(&file); out << BurstSearchParams.toString("# ","\t") //Burst Search with parameters\tM="<<BurstSearchParams.M<<"\tL="<<BurstSearchParams.L()<<" \tT="<<BurstSearchParams.T*1e6<<" us.\t" <<".\t" <<burstVector.size()<<" bursts were found.\n"; out <<"# start photon \tstart time in s \tnumber of photons \tburst duration in ms\n"; out.setRealNumberPrecision(11); for(int i=0;i<burstVector.size();++i) { out <<burstVector[i].startIdx<<"\t"<<burstVector[i].startTime<<"\t" <<burstVector[i].numberOfPhotons<<"\t"<<burstVector[i].duration*1e3<<"\n"; } AlexEvalLog::text(burstVector.size() + "bursts written to file " + file.fileName()); file.close(); return EXIT_SUCCESS; }
void Plugin::hookItemLoad (IHookProxy_ptr, Item *item) { if (!FetchedItems_.contains (item->ItemID_)) return; const quint64 id = item->ItemID_; if (!ContentsCache_.contains (id)) { QDir dir = StorageDir_; dir.cd (QString::number (id % 10)); QFile file (dir.filePath (QString ("%1.html").arg (id))); if (!file.open (QIODevice::ReadOnly)) { qWarning () << Q_FUNC_INFO << "unable to open file:" << file.fileName () << file.errorString (); return; } ContentsCache_ [id] = QString::fromUtf8 (file.readAll ()); } const QString& contents = ContentsCache_ [id]; if (!contents.isEmpty ()) item->Description_ = contents; }
/** * Throws FileOpenError * * @param filename * @param regexp * @return */ bool findInFile (const QString &filename, QRegExp ®exp) { QFile file (filename); if (!file.open (QIODevice::ReadOnly)) throw FileOpenError (filename, file.error (), file.errorString ()); return findInIoDevice (file, regexp); }
TorrentInfo TorrentInfo::loadFromFile(const QString &path, QString *error) noexcept { if (error) error->clear(); QFile file {path}; if (!file.open(QIODevice::ReadOnly)) { if (error) *error = file.errorString(); return TorrentInfo(); } const qint64 fileSizeLimit = 100 * 1024 * 1024; // 100 MB if (file.size() > fileSizeLimit) { if (error) *error = tr("File size exceeds max limit %1").arg(fileSizeLimit); return TorrentInfo(); } const QByteArray data = file.read(fileSizeLimit); if (data.size() != file.size()) { if (error) *error = tr("Torrent file read error"); return TorrentInfo(); } file.close(); // 2-step construction to overcome default limits of `depth_limit` & `token_limit` which are // used in `torrent_info()` constructor const int depthLimit = 100; const int tokenLimit = 10000000; libt::error_code ec; #if LIBTORRENT_VERSION_NUM < 10100 libt::lazy_entry node; libt::lazy_bdecode(data.constData(), (data.constData() + data.size()), node, ec , nullptr, depthLimit, tokenLimit); #else libt::bdecode_node node; bdecode(data.constData(), (data.constData() + data.size()), node, ec , nullptr, depthLimit, tokenLimit); #endif if (ec) { if (error) *error = QString::fromStdString(ec.message()); return TorrentInfo(); } TorrentInfo info {NativePtr(new libt::torrent_info(node, ec))}; if (ec) { if (error) *error = QString::fromStdString(ec.message()); return TorrentInfo(); } return info; }
Playlist Read2Sources (const QString& path) { QFile file (path); if (!file.open (QIODevice::ReadOnly)) { qWarning () << Q_FUNC_INFO << "unable to open" << path << file.errorString (); return {}; } const auto& m3uDir = QFileInfo (path).absoluteDir (); QVariantMap lastMetadata; Playlist result; while (!file.atEnd ()) { const auto& line = file.readLine ().trimmed (); if (line.startsWith ('#')) { const auto& pair = ParseMetadata (line); if (!pair.first.isEmpty ()) lastMetadata [pair.first] = pair.second; continue; } const auto& url = QUrl::fromEncoded (line); auto src = QString::fromUtf8 (line); const auto mdGuard = std::shared_ptr<void> (nullptr, [&lastMetadata] (void*) { lastMetadata.clear (); }); #ifdef Q_OS_WIN32 if (url.scheme ().size () > 1) #else if (!url.scheme ().isEmpty ()) #endif { result.Append ({ url, lastMetadata }); continue; } src.replace ('\\', '/'); const QFileInfo fi (src); if (fi.isRelative ()) src = m3uDir.absoluteFilePath (src); if (fi.suffix () == "m3u" || fi.suffix () == "m3u8") result += Read2Sources (src); else result.Append ({ src, lastMetadata }); } return result; }
void KinotifyWidget::LoadTheme (const QString& themePath) { if (ThemeCache_.contains (themePath)) { Theme_ = ThemeCache_ [themePath]; return; } Theme_.clear (); QFile content (themePath + "/tmp.html"); if (!content.open (QIODevice::ReadOnly)) { qWarning () << Q_FUNC_INFO << "could not open theme file at" << content.fileName () << content.errorString (); return; } Theme_ = content.readAll (); const QPalette& palette = QApplication::palette (); #define REPLACE1(a) { const QColor& c = palette.color (QPalette::a); \ Theme_.replace ("{Color"#a "}", QString ("%1, %2, %3").arg (c.red ()).arg (c.green ()).arg (c.blue ())); } REPLACE1 (Window); REPLACE1 (WindowText); REPLACE1 (Base); REPLACE1 (AlternateBase); REPLACE1 (ToolTipBase); REPLACE1 (ToolTipText); REPLACE1 (Text); REPLACE1 (Button); REPLACE1 (ButtonText); REPLACE1 (BrightText); REPLACE1 (Light); REPLACE1 (Midlight); REPLACE1 (Dark); REPLACE1 (Mid); REPLACE1 (Shadow); REPLACE1 (Link); REPLACE1 (LinkVisited); REPLACE1 (Highlight); REPLACE1 (HighlightedText); #undef REPLACE1 QDir imgDir (themePath + "/img"); Q_FOREACH (QString elem, imgDir.entryList (QStringList ("*.png"))) Theme_.replace (QString ("{%1}").arg (elem.left (elem.size () - 4)), MakeImage (themePath + "/img/" + elem)); if (ThemeCache_.size () > 3) ThemeCache_.clear (); ThemeCache_ [themePath] = Theme_; }
void DriveManager::handleUploadRequestFinished () { QNetworkReply *reply = qobject_cast<QNetworkReply*> (sender ()); if (!reply) return; reply->deleteLater (); QString path = Reply2FilePath_.take (reply); const int code = reply-> attribute (QNetworkRequest::HttpStatusCodeAttribute).toInt (); if (code != 200) { qWarning () << Q_FUNC_INFO << "upload initiating failed with code:" << code; return; } emit uploadStatusChanged (tr ("Uploading..."), path); QFile *file = new QFile (path); if (!file->open (QIODevice::ReadOnly)) { qWarning () << Q_FUNC_INFO << "unable to open file: " << file->errorString (); return; } QUrl url (reply->rawHeader ("Location")); QNetworkRequest request (url); #ifdef HAVE_MAGIC request.setHeader (QNetworkRequest::ContentTypeHeader, magic_file (Magic_, path.toUtf8 ())); #endif request.setHeader (QNetworkRequest::ContentLengthHeader, QString::number (QFileInfo (path).size ()).toUtf8 ()); QNetworkReply *uploadReply = Core::Instance ().GetProxy ()-> GetNetworkAccessManager ()->put (request, file); file->setParent (uploadReply); Reply2FilePath_ [uploadReply] = path; connect (uploadReply, SIGNAL (finished ()), this, SLOT (handleUploadFinished ())); connect (uploadReply, SIGNAL (error (QNetworkReply::NetworkError)), this, SLOT (handleUploadError (QNetworkReply::NetworkError))); connect (uploadReply, SIGNAL (uploadProgress (qint64, qint64)), this, SLOT (handleUploadProgress (qint64, qint64))); }
int EventItemModel::loadFile(QString &filename) { QFile input; input.setFileName(filename); if (!input.open(QIODevice::ReadOnly)) { qDebug() << "Couldn't open event stream file: " << input.errorString(); return -1; } return _events.load(input); }
bool LuaParser::OpenFile(QFile File) { if(!File.open(QIODevice::ReadOnly)) { QMessageBox::information(0, "error", File.errorString()); return false; }; return true; }
void Updater::writeUpdate() { if(m_netReply->bytesAvailable() != 0) { QFileInfo file(m_urlExe); QString executableName = file.fileName(); if(QFile::exists(executableName)) { if(QFile::exists("_old_" + executableName)) QFile::remove("_old_" + executableName); QFile::rename(executableName, "_old_" + executableName); } QFile fileToWrite (QFileInfo(m_urlExe).fileName(), this); if(fileToWrite.open(QFile::WriteOnly | QIODevice::Truncate)) { fileToWrite.write(m_netReply->readAll()); fileToWrite.close(); QMessageBox endBox (nullptr); endBox.setWindowTitle(tr("Mise à jour terminée ! ")); endBox.setText(tr("La mise à jour %1 a pu être appliquée avec succès\n" "Voulez-vous lancer à nouveau %2?").arg(m_newAppVersion).arg(m_appName)); endBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); endBox.setDefaultButton(QMessageBox::Yes); endBox.setButtonText(QMessageBox::Yes, tr("Relancer %1").arg(m_appName)); endBox.setButtonText(QMessageBox::No, tr("Pas maintenant")); int reply = endBox.exec(); //Awaiting user reply if(reply == QMessageBox::Yes) QDesktopServices::openUrl(QUrl::fromLocalFile(executableName)); exit(0); } else { qDebug() << fileToWrite.errorString(); QMessageBox::critical(nullptr, tr("Erreur"), tr("La mise à jour n'a pas pu être écrite : ") + fileToWrite.errorString()); exit(1); } } }
bool Shader::compileSourceFile (CGcontext context, const QString& file, const QString& entryPoint) { QFile dev (file); if (!dev.open(QIODevice::ReadOnly)) { qWarning("failed to open file: %s", qPrintable(dev.errorString())); return false; } return compileSourceCode(context, dev.readAll(), entryPoint); }
bool ExportHelper::exportHTML(const int qryheadid, ParameterList ¶ms, QString &filename, QString &errmsg) { if (DEBUG) qDebug("ExportHelper::exportHTML(%d, %d params, %s, errmsg) entered", qryheadid, params.size(), qPrintable(filename)); bool returnVal = false; XSqlQuery setq; setq.prepare("SELECT * FROM qryhead WHERE qryhead_id=:id;"); setq.bindValue(":id", qryheadid); setq.exec(); if (setq.first()) { if (filename.isEmpty()) { QFileInfo fileinfo(setq.value("qryhead_name").toString()); filename = fileinfo.absoluteFilePath(); } QFile *exportfile = new QFile(filename); if (! exportfile->open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text)) errmsg = tr("Could not open %1: %2.") .arg(filename, exportfile->errorString()); else { if (exportfile->write(generateHTML(qryheadid, params, errmsg).toUtf8()) < 0) errmsg = tr("Error writing to %1: %2") .arg(filename, exportfile->errorString()); exportfile->close(); } } else if (setq.lastError().type() != QSqlError::NoError) errmsg = setq.lastError().text(); else errmsg = tr("<p>Cannot export data because the query set with " "id %1 was not found.").arg(qryheadid); if (DEBUG) qDebug("ExportHelper::exportHTML returning %d, filename %s, and errmsg %s", returnVal, qPrintable(filename), qPrintable(errmsg)); return returnVal; }
bool Project::save() { saveOpenTexts(); serializeConfigurationXml(); // indebted to: http://stackoverflow.com/questions/2598117/zipping-a-folder-file-using-qt QuaZip zip(mProjectPath); QuaZipFile outFile(&zip); if (!zip.open(QuaZip::mdCreate)) { qWarning() << "zip.open()" << zip.getZipError(); return false; } char c; QFile inFile; QDir tempDir = getTempDir(); tempDir.setNameFilters(QStringList("*")); QStringList files = tempDir.entryList(QDir::Files,QDir::Name); for(int i=0; i<files.count(); i++) { inFile.setFileName( tempDir.absoluteFilePath(files.at(i)) ); if( !inFile.open(QIODevice::ReadOnly)) { qWarning() << inFile.errorString(); return false; } if( !outFile.open(QIODevice::WriteOnly, QuaZipNewInfo(files.at(i) , tempDir.absoluteFilePath(files.at(i)) ))) { qWarning() << outFile.errorString(); return false; } while (inFile.getChar(&c) && outFile.putChar(c)); if (outFile.getZipError() != UNZ_OK) { qWarning() << outFile.getZipError(); return false; } outFile.close(); if (outFile.getZipError() != UNZ_OK) { qWarning() << outFile.getZipError(); return false; } inFile.close(); } mChanged = false; return true; }