QList<br::FilesWithLabel> br::getFilesWithLabels(QDir dir) { dir = QDir(dir.canonicalPath()); QStringList files; foreach (const QString &file, dir.entryList(QDir::Files)) files.append(dir.absoluteFilePath(file)); QList<br::FilesWithLabel> filesWithLabels; filesWithLabels.append(br::FilesWithLabel(dir.dirName(),files)); foreach (const QString &folder, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) { QDir subdir(dir); bool success = subdir.cd(folder); if (!success) qFatal("cd failure."); filesWithLabels.append(getFilesWithLabels(subdir)); } return filesWithLabels; }
/* Create a new project. - a new directory for the project - an XML project file for the project, from template - a stubbed out source file, from template Make sure the path name doesn't have any spaces in it, so make can work happily. Return the new project's name, or an empty string on failure. */ QString ProjectManager::createNewProject(const QString & newProjectPath) { QString projectPath = confirmValidProjectName(newProjectPath); QDir newProjectDir; newProjectDir.mkpath(projectPath); newProjectDir.setPath(projectPath); QString newProjName = newProjectDir.dirName(); // grab the templates for a new project QString templatePath = "resources/templates"; #ifdef MCBUILDER_TEST_SUITE templatePath.prepend("../"); #endif QDir templatesDir(MainWindow::appDirectory().filePath(templatePath)); // create the project file from our template QFile templateFile(templatesDir.filePath("project_template.xml")); templateFile.copy(newProjectDir.filePath(newProjName + ".xml")); templateFile.close(); templateFile.setFileName(templatesDir.filePath("makefile_template.txt")); templateFile.copy(newProjectDir.filePath("Makefile")); templateFile.close(); templateFile.setFileName(templatesDir.filePath("config_template.txt")); templateFile.copy(newProjectDir.filePath("config.h")); templateFile.close(); templateFile.setFileName(templatesDir.filePath("source_template.txt")); if (templateFile.open(QIODevice::ReadOnly | QFile::Text)) { // and create the main file QFile mainFile(newProjectDir.filePath(newProjName + ".c")); if (mainFile.open(QIODevice::WriteOnly | QFile::Text)) { QTextStream out(&mainFile); out << QString("// %1.c").arg(newProjName) << endl; out << QString("// created %1").arg(QDate::currentDate().toString("MMM d, yyyy") ) << endl; out << templateFile.readAll(); mainFile.close(); } QFileInfo fi(mainFile); addToProjectFile(newProjectDir.path(), fi.filePath()); templateFile.close(); } return newProjectDir.path(); }
bool PSPApplication::isPercentMultiple(QDir dir) { //Get the dir name of the pbp container QString dirName = dir.dirName();//dir.absolutePath(); //Set the name of the other dir QString otherName = dirName; if (dirName.endsWith("%")) { otherName.resize(otherName.length() - 1); } else { otherName.append("%"); } //Now we have to check that both the otherName dir exists //and it has a valid PBP file dir.cdUp(); QDir otherDir(dir.absolutePath() +"/"+ otherName); if (!otherDir.exists()) { return false; } //Find the eboot.pbp file inside the dir QFileInfoList files; files = otherDir.entryInfoList(QDir::Files | QDir::NoSymLinks); for (int i = 0; i < files.size(); ++i) { if (files.at(i).fileName().toLower() == "eboot.pbp") { if (isPBPSignature(files.at(i).filePath())) { return true; //We have the correct directory and contains a correct pbp file } } } return false; }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- QUrl DREAM3DHelpUrlGenerator::generateHTMLUrl(QString htmlName) { QString appPath = qApp->applicationDirPath(); QDir helpDir = QDir(appPath); QString s("file://"); #if defined(Q_OS_WIN) s = s + "/"; // Need the third slash on windows because file paths start with a drive letter #elif defined(Q_OS_MAC) if (helpDir.dirName() == "MacOS") { helpDir.cdUp(); helpDir.cdUp(); helpDir.cdUp(); } #else // We are on Linux - I think QFileInfo fi( helpDir.absolutePath() + Detail::Dream3DHelpPath + htmlName + ".html"); if (fi.exists() == false) { // The help file does not exist at the default location because we are probably running from the build tree. // Try up one more directory helpDir.cdUp(); } #endif #if defined(Q_OS_WIN) QFileInfo fi( helpDir.absolutePath() + Detail::Dream3DHelpPath + htmlName + ".html"); if (fi.exists() == false) { // The help file does not exist at the default location because we are probably running from visual studio. // Try up one more directory helpDir.cdUp(); } #endif s = s + helpDir.absolutePath() + Detail::Dream3DHelpPath + htmlName + ".html"; return QUrl(s); }
/************************************************************ * WriteToFile * ----------------------------------------------------------- * - Overloaded * - see WriteToFile(Qstring) * Returns true only if it successfully writes * Returns false if it fails to open, write or if there are * no customers in the list. * ------------------------------------------------------------ * File path is set when first establishing the database *************************************************************/ bool MainProgramWindow::StoreTestimonials() { QDir dataPath = QDir::current(); bool writeStatus; // Failstate signal writeStatus = false; // Initialize QFile and write failed, Appended File to path, QFile Creates while(dataPath.dirName() != "Class-Project") { dataPath.cdUp(); } dataPath.cd("Database-Files"); QFile testimonialDataFile((dataPath.path() + "/Testimonials.txt")); if(testimonialDataFile.open((QIODevice::ReadWrite | QIODevice::Text)|QIODevice::Truncate)) { QTextStream out(&testimonialDataFile); out << bWindow->getTestimonials(); // Flushes output buffer out.flush(); writeStatus = true; } // END OPEN FILE IF // Flushes and coses the data file testimonialDataFile.flush(); testimonialDataFile.close(); // Returns True or False status return writeStatus; }// **** END METHOD **** //
void DumpRenderTree::processLine(const QString &input) { QString line = input; m_expectedHash = QString(); if (m_dumpPixels) { // single quote marks the pixel dump hash int i = line.indexOf('\''); if (i > -1) { m_expectedHash = line.mid(i + 1, line.length()); line.remove(i, line.length()); } } if (line.startsWith(QLatin1String("http:")) || line.startsWith(QLatin1String("https:")) || line.startsWith(QLatin1String("file:"))) { open(QUrl(line)); } else { QFileInfo fi(line); if (!fi.exists()) { QDir currentDir = QDir::currentPath(); // Try to be smart about where the test is located if (currentDir.dirName() == QLatin1String("LayoutTests")) fi = QFileInfo(currentDir, line.replace(QRegExp(".*?LayoutTests/(.*)"), "\\1")); else if (!line.contains(QLatin1String("LayoutTests"))) fi = QFileInfo(currentDir, line.prepend(QLatin1String("LayoutTests/"))); if (!fi.exists()) { emit ready(); return; } } open(QUrl::fromLocalFile(fi.absoluteFilePath())); } fflush(stdout); }
QDir Tools::pluginsPath(void) { QDir dir = QCoreApplication::applicationDirPath(); #if defined(Q_OS_MAC) if (dir.dirName() == "MacOS") { dir.cdUp(); } dir.cd("plugins"); dir.cd("lugdulov"); #elif defined(Q_OS_WIN32) dir.cd("plugins"); dir.cd("lugdulov"); #else dir.cdUp(); dir.cd("lib"); dir.cd("lugdulov"); dir.cd("plugins"); #endif return dir; }
Global::Global() { appDirPath = QCoreApplication::applicationDirPath(); QDir appDir = QDir(appDirPath); #if defined(Q_OS_MAC) if (appDir.dirName() == "MacOS") { //We're in the mac package and need to get back to the package to access relative directories appDir.cdUp(); appDir.cdUp(); appDir.cdUp(); //Root dir where app is located appDirPath = appDir.absolutePath(); } #endif pebbleDataPath = appDirPath + "/PebbleData/"; file = new QFile(pebbleDataPath+"pebblelog.txt"); bool res = file->open(QIODevice::Unbuffered | QIODevice::Truncate | QIODevice::WriteOnly | QIODevice::Text); pLogfile = NULL; if (res) { pLogfile = new QDebug(file); *pLogfile << "Pebble log file\n"; } revision = new char[80]; //See PebbleQt.pro for DEFINES statement that creates PEBBLE_VERSION sprintf(revision,"Build %s on %s using QT:%s",PEBBLE_VERSION, PEBBLE_DATE, PEBBLE_QT); //qDebug(revision); sdr = NULL; perform.InitPerformance(); beep.setSource(QUrl::fromLocalFile(pebbleDataPath + "beep-07.wav")); beep.setLoopCount(1); beep.setVolume(0.25f); primaryScreen = QGuiApplication::primaryScreen(); }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void HelpDialog::setContentFile(QUrl sourceLocation) { QDir aPluginDir = QDir(dream3dApp->applicationDirPath()); QString aPluginDirStr = aPluginDir.absolutePath(); QString thePath; #if defined(Q_OS_WIN) if (aPluginDir.cd("Help") ) { thePath = aPluginDir.absolutePath(); } else if (aPluginDir.cd("../Help") ) { thePath = aPluginDir.absolutePath(); } #elif defined(Q_OS_MAC) if (aPluginDir.dirName() == "MacOS") { aPluginDir.cdUp(); aPluginDir.cdUp(); aPluginDir.cdUp(); } // aPluginDir.cd("Plugins"); thePath = aPluginDir.absolutePath() + "/Help"; #else if (aPluginDir.cd("Help")) { thePath = aPluginDir.absolutePath(); } #endif thePath = QString("file:///").append(thePath).append("/").append(sourceLocation.toString()); // qDebug() << "Help File Path:" << thePath() << "\n"; helpBrowser->setSource(QUrl(thePath)); // Set the Home Page File m_HomeUrl = QUrl(thePath); this->show(); }
void Camera::requestDownloadFile(const CameraFileRef& file, const QDir& destinationFolderPath, const std::function<void(EdsError error, QString outputFilePath)>& callback) { // check if destination exists and create if not if ( !destinationFolderPath.exists() ) { bool status = destinationFolderPath.mkpath("."); if (!status) { std::cerr << "ERROR - failed to create destination folder path '" << destinationFolderPath.dirName().toStdString() << "'" << std::endl; return callback(EDS_ERR_INTERNAL_ERROR, NULL); } } QString filePath = destinationFolderPath.filePath(QString::fromStdString(file->getName())); EdsStreamRef stream = NULL; EdsError error = EdsCreateFileStream(filePath.toStdString().c_str(), kEdsFileCreateDisposition_CreateAlways, kEdsAccess_ReadWrite, &stream); if (error != EDS_ERR_OK) { std::cerr << "ERROR - failed to create file stream" << std::endl; goto download_cleanup; } error = EdsDownload(file->mDirectoryItem, file->getSize(), stream); if (error != EDS_ERR_OK) { std::cerr << "ERROR - failed to download" << std::endl; goto download_cleanup; } error = EdsDownloadComplete(file->mDirectoryItem); if (error != EDS_ERR_OK) { std::cerr << "ERROR - failed to mark download as complete" << std::endl; goto download_cleanup; } download_cleanup: if (stream) { EdsRelease(stream); } callback(error, filePath); }
/* Create a new project. - a new directory for the project - an XML project file for the project, from template - a stubbed out source file, from template Make sure the path name doesn't have any spaces in it, so make can work happily. Return the new project's name, or an empty string on failure. */ QString ProjectManager::createNewProject(QString newProjectPath) { confirmValidProjectName(&newProjectPath); if(newProjectPath.contains(" ")) // if there are still spaces in the path, we have problems return ""; QDir newProjectDir; newProjectDir.mkpath(newProjectPath); newProjectDir.setPath(newProjectPath); QString newProjName = newProjectDir.dirName(); // grab the templates for a new project QDir templatesDir = QDir::current().filePath("resources/templates"); // create the project file from our template QFile templateFile(templatesDir.filePath("project_template.xml")); templateFile.copy(newProjectDir.filePath(newProjName + ".xml")); templateFile.close(); templateFile.setFileName(templatesDir.filePath("source_template.txt")); if( templateFile.open(QIODevice::ReadOnly | QFile::Text) ) { // and create the main file QFile mainFile(newProjectDir.filePath(newProjName + ".c")); if( mainFile.open(QIODevice::WriteOnly | QFile::Text) ) { QTextStream out(&mainFile); out << QString("// %1.c").arg(newProjName) << endl; out << QString("// created %1").arg(QDate::currentDate().toString("MMM d, yyyy") ) << endl; out << templateFile.readAll(); mainFile.close(); } QFileInfo fi(mainFile); addToProjectFile(newProjectDir.path(), fi.filePath(), "thumb"); templateFile.close(); } return newProjectDir.path(); }
bool RemoveDirectory(QDir &aDir) { qDebug() << "Now Deleting " << aDir; QDirIterator iterator(aDir.absolutePath (), QDirIterator::NoIteratorFlags); while(iterator.hasNext ()) { iterator.next (); qDebug() << "Iterating over - " << iterator.filePath (); if(iterator.fileInfo ().isFile ()) { qDebug () << "Deleting File"; QFile::remove (iterator.filePath ()); } if (iterator.fileInfo ().isDir () && iterator.fileName () != "." && iterator.fileName () != "..") { QDir rDel(iterator.filePath ()); RemoveDirectory(rDel); } } // Delete the root director QString dirName = aDir.dirName (); aDir.cdUp (); aDir.rmdir (dirName); }
AddressBarButton::AddressBarButton(const QString &newPath, int index, QWidget *parent) : QPushButton(parent), _path(QDir::toNativeSeparators(newPath)), idx(index), _atLeastOneSubDir(true) { if (_path.right(1) != QDir::separator()) { _path += QDir::separator(); } this->setFlat(true); this->setMouseTracking(true); QDir d = QDir(_path); /*foreach (QFileInfo fileInfo, d.entryInfoList(QStringList(), QDir::NoDotAndDotDot)) { qDebug() << fileInfo.absoluteFilePath(); if (fileInfo.isDir()) { _atLeastOneSubDir = true; //break; } }*/ // padding + text + (space + arrow + space) if current dir has subdirectories int width = fontMetrics().width(d.dirName()); if (_atLeastOneSubDir) { width += 30; } this->setMinimumWidth(width); this->setMaximumWidth(width); }
QString Maildir::name() const { const QDir dir(d->path); return dir.dirName(); }
void UniformValue::updateUniformVariableValuesFromDialog(int rowIdx, int colIdx, QVariant newValue) { switch (type) { case INT: ivalue = newValue.toInt(); break; case FLOAT: fvalue = newValue.toDouble(); break; case BOOL: bvalue = newValue.toBool() != 0; break; case VEC2: case VEC3: case VEC4: vec4[colIdx] = newValue.toDouble(); break; case IVEC2: case IVEC3: case IVEC4: ivec4[colIdx] = newValue.toInt(); break; case BVEC2: case BVEC3: case BVEC4: bvec4[colIdx] = newValue.toBool() != 0; break; case MAT2: mat2[rowIdx][colIdx] = newValue.toDouble(); break; case MAT3: mat3[rowIdx][colIdx] = newValue.toDouble(); break; case MAT4: mat4[rowIdx][colIdx] = newValue.toDouble(); break; case SAMPLER1D: case SAMPLER2D: case SAMPLER3D: case SAMPLERCUBE: case SAMPLER1DSHADOW: case SAMPLER2DSHADOW: { QString newPath; // * choose the filename with a dialog (55 by convention) if (rowIdx == 5 && colIdx == 5) { QFileDialog fd(0, "Choose new texture"); QDir texturesDir = QDir(qApp->applicationDirPath()); #if defined(Q_OS_WIN) if (texturesDir.dirName() == "debug" || texturesDir.dirName() == "release") texturesDir.cdUp(); #elif defined(Q_OS_MAC) if (texturesDir.dirName() == "MacOS") { for (int i = 0; i < 4; ++i) { texturesDir.cdUp(); if (texturesDir.exists("textures")) break; } } #endif texturesDir.cd("textures"); fd.setDirectory(texturesDir); fd.move(500, 100); if (fd.exec()) { QStringList sels = fd.selectedFiles(); newPath = sels[0]; } } else newPath = newValue.toString(); // Load the new texture from given file if(textureLoaded) glDeleteTextures(1, &textureId); QImage img, imgScaled, imgGL; QFileInfo finfo(newPath); if(!finfo.exists()) { qDebug() << "Texture" << name << "in" << newPath << ": file do not exists"; } else if (!img.load(newPath)) { QMessageBox::critical(0, "Meshlab", newPath + ": Unsupported texture format"); } glEnable(GL_TEXTURE_2D); // image has to be scaled to a 2^n size. We choose the first 2^N <= picture size. int bestW = pow(2.0, floor(::log(double(img.width())) / ::log(2.0))); int bestH = pow(2.0, floor(::log(double(img.height())) / ::log(2.0))); if (!img.isNull()) imgScaled = img.scaled(bestW, bestH, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); imgGL = QGLWidget::convertToGLFormat(imgScaled); glGenTextures(1, &textureId); glBindTexture(GL_TEXTURE_2D, textureId); glTexImage2D(GL_TEXTURE_2D, 0, 3, imgGL.width(), imgGL.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, imgGL.bits()); textureLoaded = true; break; } case OTHER: assert(0); } }
void ChannelData::handleChannels(int id, QList<ChanInfo> *chanlist) { QString fileprefix = SetupIconCacheDirectory(); QDir::setCurrent(fileprefix); fileprefix += "/"; QList<ChanInfo>::iterator i = chanlist->begin(); for (; i != chanlist->end(); ++i) { QString localfile; if (!(*i).iconpath.isEmpty()) { QDir remotefile = QDir((*i).iconpath); QString filename = remotefile.dirName(); localfile = fileprefix + filename; QFile actualfile(localfile); if (!actualfile.exists() && !HttpComms::getHttpFile(localfile, (*i).iconpath)) { LOG(VB_GENERAL, LOG_ERR, QString("Failed to fetch icon from '%1'") .arg((*i).iconpath)); } } MSqlQuery query(MSqlQuery::InitCon()); if (!(*i).old_xmltvid.isEmpty()) { query.prepare( "SELECT xmltvid " "FROM channel " "WHERE xmltvid = :XMLTVID"); query.bindValue(":XMLTVID", (*i).old_xmltvid); if (!query.exec()) { MythDB::DBError("xmltvid conversion 1", query); } else if (query.next()) { LOG(VB_GENERAL, LOG_INFO, QString("Converting old xmltvid (%1) to new (%2)") .arg((*i).old_xmltvid).arg((*i).xmltvid)); query.prepare("UPDATE channel " "SET xmltvid = :NEWXMLTVID" "WHERE xmltvid = :OLDXMLTVID"); query.bindValue(":NEWXMLTVID", (*i).xmltvid); query.bindValue(":OLDXMLTVID", (*i).old_xmltvid); if (!query.exec()) { MythDB::DBError("xmltvid conversion 2", query); } } } query.prepare( "SELECT chanid, name, callsign, channum, " " finetune, icon, freqid, tvformat " "FROM channel " "WHERE xmltvid = :XMLTVID AND " " sourceid = :SOURCEID"); query.bindValue(":XMLTVID", (*i).xmltvid); query.bindValue(":SOURCEID", id); if (!query.exec()) { MythDB::DBError("handleChannels", query); } else if (query.next()) { QString chanid = query.value(0).toString(); if (interactive) { QString name = query.value(1).toString(); QString callsign = query.value(2).toString(); QString chanstr = query.value(3).toString(); QString finetune = query.value(4).toString(); QString icon = query.value(5).toString(); QString freqid = query.value(6).toString(); QString tvformat = query.value(7).toString(); cout << "### " << endl; cout << "### Existing channel found" << endl; cout << "### " << endl; cout << "### xmltvid = " << (*i).xmltvid.toLocal8Bit().constData() << endl; cout << "### chanid = " << chanid.toLocal8Bit().constData() << endl; cout << "### name = " << name.toLocal8Bit().constData() << endl; cout << "### callsign = " << callsign.toLocal8Bit().constData() << endl; cout << "### channum = " << chanstr.toLocal8Bit().constData() << endl; if (channel_preset) { cout << "### freqid = " << freqid.toLocal8Bit().constData() << endl; } cout << "### finetune = " << finetune.toLocal8Bit().constData() << endl; cout << "### tvformat = " << tvformat.toLocal8Bit().constData() << endl; cout << "### icon = " << icon.toLocal8Bit().constData() << endl; cout << "### " << endl; (*i).name = name; (*i).callsign = callsign; (*i).chanstr = chanstr; (*i).finetune = finetune; (*i).freqid = freqid; (*i).tvformat = tvformat; promptForChannelUpdates(i, chanid.toUInt()); if ((*i).callsign.isEmpty()) (*i).callsign = chanid; if (name != (*i).name || callsign != (*i).callsign || chanstr != (*i).chanstr || finetune != (*i).finetune || freqid != (*i).freqid || icon != localfile || tvformat != (*i).tvformat) { MSqlQuery subquery(MSqlQuery::InitCon()); subquery.prepare("UPDATE channel SET chanid = :CHANID, " "name = :NAME, callsign = :CALLSIGN, " "channum = :CHANNUM, finetune = :FINE, " "icon = :ICON, freqid = :FREQID, " "tvformat = :TVFORMAT " " WHERE xmltvid = :XMLTVID " "AND sourceid = :SOURCEID;"); subquery.bindValue(":CHANID", chanid); subquery.bindValue(":NAME", (*i).name); subquery.bindValue(":CALLSIGN", (*i).callsign); subquery.bindValue(":CHANNUM", (*i).chanstr); subquery.bindValue(":FINE", (*i).finetune.toInt()); subquery.bindValue(":ICON", localfile); subquery.bindValue(":FREQID", (*i).freqid); subquery.bindValue(":TVFORMAT", (*i).tvformat); subquery.bindValue(":XMLTVID", (*i).xmltvid); subquery.bindValue(":SOURCEID", id); if (!subquery.exec()) { MythDB::DBError("update failed", subquery); } else { cout << "### " << endl; cout << "### Change performed" << endl; cout << "### " << endl; } } else { cout << "### " << endl; cout << "### Nothing changed" << endl; cout << "### " << endl; } } else { if (!non_us_updating && !localfile.isEmpty()) { MSqlQuery subquery(MSqlQuery::InitCon()); subquery.prepare("UPDATE channel SET icon = :ICON WHERE " "chanid = :CHANID;"); subquery.bindValue(":ICON", localfile); subquery.bindValue(":CHANID", chanid); if (!subquery.exec()) MythDB::DBError("Channel icon change", subquery); } } } else if (insert_chan(id)) // Only insert channels for non-scannable sources { int major, minor = 0; long long freq = 0; get_atsc_stuff((*i).chanstr, id, (*i).freqid.toInt(), major, minor, freq); if (interactive && ((minor == 0) || (freq > 0))) { cout << "### " << endl; cout << "### New channel found" << endl; cout << "### " << endl; cout << "### name = " << (*i).name.toLocal8Bit().constData() << endl; cout << "### callsign = " << (*i).callsign.toLocal8Bit().constData() << endl; cout << "### channum = " << (*i).chanstr.toLocal8Bit().constData() << endl; if (channel_preset) { cout << "### freqid = " << (*i).freqid.toLocal8Bit().constData() << endl; } cout << "### finetune = " << (*i).finetune.toLocal8Bit().constData() << endl; cout << "### tvformat = " << (*i).tvformat.toLocal8Bit().constData() << endl; cout << "### icon = " << localfile.toLocal8Bit().constData() << endl; cout << "### " << endl; uint chanid = promptForChannelUpdates(i,0); if ((*i).callsign.isEmpty()) (*i).callsign = QString::number(chanid); int mplexid = 0; if ((chanid > 0) && (minor > 0)) mplexid = ChannelUtil::CreateMultiplex(id, "atsc", freq, "8vsb"); if (((mplexid > 0) || ((minor == 0) && (chanid > 0))) && ChannelUtil::CreateChannel( mplexid, id, chanid, (*i).callsign, (*i).name, (*i).chanstr, 0 /*service id*/, major, minor, false /*use on air guide*/, false /*hidden*/, false /*hidden in guide*/, (*i).freqid, localfile, (*i).tvformat, (*i).xmltvid)) { cout << "### " << endl; cout << "### Channel inserted" << endl; cout << "### " << endl; } else { cout << "### " << endl; cout << "### Channel skipped" << endl; cout << "### " << endl; } } else if (!non_us_updating && ((minor == 0) || (freq > 0))) { // We only do this if we are not asked to skip it with the // --updating flag. int mplexid = 0, chanid = 0; if (minor > 0) { mplexid = ChannelUtil::CreateMultiplex( id, "atsc", freq, "8vsb"); } if ((mplexid > 0) || (minor == 0)) chanid = ChannelUtil::CreateChanID(id, (*i).chanstr); if ((*i).callsign.isEmpty()) { QStringList words = (*i).name.simplified().toUpper() .split(" "); QString callsign = ""; QString w1 = words.size() > 0 ? words[0] : QString(); QString w2 = words.size() > 1 ? words[1] : QString(); if (w1.isEmpty()) callsign = QString::number(chanid); else if (w2.isEmpty()) callsign = words[0].left(5); else { callsign = w1.left(w2.length() == 1 ? 4:3); callsign += w2.left(5 - callsign.length()); } (*i).callsign = callsign; } if (chanid > 0) { QString cstr = QString((*i).chanstr); if(channel_preset && cstr.isEmpty()) cstr = QString::number(chanid % 1000); bool retval = ChannelUtil::CreateChannel( mplexid, id, chanid, (*i).callsign, (*i).name, cstr, 0 /*service id*/, major, minor, false /*use on air guide*/, false /*hidden*/, false /*hidden in guide*/, (*i).freqid, localfile, (*i).tvformat, (*i).xmltvid ); if (!retval) cout << "Channel " << chanid << " creation failed" << endl; } } } } }
bool XSAppBuilder::packProject() { if(projectPath.isEmpty()) { return false; } bool ret = false; QDir dir(projectPath); QFileInfoList infoList = dir.entryInfoList(); for(int i = 0; i < infoList.size(); i++) { if(infoList.at(i).isDir()) { QDir jsDir = QDir(infoList.at(i).absoluteFilePath()); QFileInfoList jsInforList = jsDir.entryInfoList(); if(jsDir.dirName() == "scripts") { for(int j = 0; j < jsInforList.size(); j++) { if(jsInforList.at(j).suffix() == "js") { QString prefix = jsDir.dirName() + "_"; ret = compileScript(jsInforList.at(j), prefix); break; } } } continue; } if(infoList.at(i).suffix() == "xpk") { continue; } else if(infoList.at(i).suffix() == "xml" || infoList.at(i).suffix() == "json") { ret = compileObject(infoList.at(i)); } else if(infoList.at(i).suffix() == "js") { ret = compileScript(infoList.at(i), ""); } else { ret = compileBinary(infoList.at(i)); } if(ret == false) { return ret; } } ret = writeObject(); return ret; }
int main(int argc, char ** argv) { QApplication * app = new QApplication(argc, argv); int uid = -1; // note : QFile fp(QDir::home().absFilePath(".boumlrc")) doesn't work // if the path contains non latin1 characters, for instance cyrillic ! QDir homeDir = QDir::home(); QString s = homeDir.absFilePath(".boumlrc"); FILE * fp = fopen((const char *) s, "r"); int cx = -1; int cy = -1; int w = QApplication::desktop()->width(); int h = QApplication::desktop()->height(); if (fp != 0) { char line[512]; while (fgets(line, sizeof(line) - 1, fp) != 0) { remove_crlf(line); if (!strncmp(line, "ID ", 3)) { sscanf(line+3, "%d", &uid); break; } else if (!strncmp(line, "DESKTOP ", 8)) { int l, t, r, b; if (sscanf(line+8, "%d %d %d %d", &l, &t, &r, &b) == 4) { if (!((r == 0) && (t == 0) && (r == 0) && (b == 0)) && !((r < 0) || (t < 0) || (r < 0) || (b < 0)) && !((r <= l) || (b <= t))) { cx = (r + l) / 2; cy = (t + b) / 2; w = r - l; h = b - t; } } } } fclose(fp); } if (uid == -1) QMessageBox::critical(0, "Control project", "Own identifier not defined"); else if ((uid < 2) || (uid > 127)) QMessageBox::critical(0, "Control project", "invalid Identifier"); else { set_user_id(uid, homeDir.dirName()); app->connect(app, SIGNAL(lastWindowClosed()), SLOT(quit()) ); init_pixmaps(); ControlWindow * ww = new ControlWindow(homeDir); ww->resize((w * 3)/5, (h * 3)/5); if (cx != -1) ww->move(ww->x() + cx - (ww->x() + ww->width() / 2), ww->y() + cy - (ww->y() + ww->height() / 2)); ww->show(); app->exec(); } return 0; }
int Package::file_number(QDir & d, bool rec) { if (! allowed(DirFilter, d.dirName())) return 0; int result = 0; // const QFileInfoList * list = d.entryInfoList(QDir::Files | QDir::Readable); /* if (list != 0) { QFileInfoListIterator it(*list); QFileInfo * fi; while ((fi = it.current()) != 0) { if (fi->extension(FALSE) == Ext) result += 1; ++it; } }*/ // Oh lord, Bruno is so used to cut-n-paste, I am getting sick. QFileInfoList list = d.entryInfoList(QDir::Files | QDir::Readable); if (!list.isEmpty()) { QFileInfoList::iterator it = list.begin(); while (it != list.end()) { if ((*it).extension(FALSE) == Ext) result += 1; it++; } } if (rec) { // // sub directories // list = d.entryInfoList(QDir::Dirs | QDir::NoSymLinks); // // if (list != 0) { // QFileInfoListIterator itd(*list); // QFileInfo * di; // // while ((di = itd.current()) != 0) { // if (((const char *) di->fileName())[0] != '.') { // QDir sd(di->filePath()); // // result += file_number(sd, rec); // } // ++itd; // } // } // } // list = d.entryInfoList(QDir::Dirs | QDir::NoSymLinks); if (!list.isEmpty()) { QFileInfoList::iterator it = list.begin(); while (it != list.end()) { if ((*it).fileName()[0] != '.') { QDir sd((*it).filePath()); result += file_number(sd, rec); } it++; } } } return result; }
Athlete::Athlete(Context *context, const QDir &home) { // athlete name this->home = home; this->context = context; context->athlete = this; cyclist = home.dirName(); isclean = false; // Recovering from a crash? if(!appsettings->cvalue(cyclist, GC_SAFEEXIT, true).toBool()) { GcCrashDialog *crashed = new GcCrashDialog(home); crashed->exec(); } appsettings->setCValue(cyclist, GC_SAFEEXIT, false); // will be set to true on exit // Before we initialise we need to run the upgrade wizard for this athlete GcUpgrade v3; v3.upgrade(context->athlete->home); // metric / non-metric QVariant unit = appsettings->cvalue(cyclist, GC_UNIT); if (unit == 0) { // Default to system locale unit = appsettings->value(this, GC_UNIT, QLocale::system().measurementSystem() == QLocale::MetricSystem ? GC_UNIT_METRIC : GC_UNIT_IMPERIAL); appsettings->setCValue(cyclist, GC_UNIT, unit); } useMetricUnits = (unit.toString() == GC_UNIT_METRIC); // Power Zones zones_ = new Zones; QFile zonesFile(home.absolutePath() + "/power.zones"); if (zonesFile.exists()) { if (!zones_->read(zonesFile)) { QMessageBox::critical(context->mainWindow, tr("Zones File Error"), zones_->errorString()); } else if (! zones_->warningString().isEmpty()) QMessageBox::warning(context->mainWindow, tr("Reading Zones File"), zones_->warningString()); } // Heartrate Zones hrzones_ = new HrZones; QFile hrzonesFile(home.absolutePath() + "/hr.zones"); if (hrzonesFile.exists()) { if (!hrzones_->read(hrzonesFile)) { QMessageBox::critical(context->mainWindow, tr("HR Zones File Error"), hrzones_->errorString()); } else if (! hrzones_->warningString().isEmpty()) QMessageBox::warning(context->mainWindow, tr("Reading HR Zones File"), hrzones_->warningString()); } // read athlete's charts.xml and translate etc LTMSettings reader; reader.readChartXML(context->athlete->home, context->athlete->useMetricUnits, presets); translateDefaultCharts(presets); // Metadata rideMetadata_ = new RideMetadata(context,true); rideMetadata_->hide(); // Date Ranges seasons = new Seasons(home); // Search / filter #ifdef GC_HAVE_LUCENE namedSearches = new NamedSearches(this); // must be before navigator lucene = new Lucene(context, context); // before metricDB attempts to refresh #endif // metrics DB metricDB = new MetricAggregator(context); // just to catch config updates! metricDB->refreshMetrics(); // the model atop the metric DB sqlModel = new QSqlTableModel(this, metricDB->db()->connection()); sqlModel->setTable("metrics"); sqlModel->setEditStrategy(QSqlTableModel::OnManualSubmit); // Downloaders withingsDownload = new WithingsDownload(context); zeoDownload = new ZeoDownload(context); calendarDownload = new CalendarDownload(context); // Calendar #ifdef GC_HAVE_ICAL rideCalendar = new ICalendar(context); // my local/remote calendar entries davCalendar = new CalDAV(context); // remote caldav davCalendar->download(); // refresh the diary window #endif // RIDE TREE -- transitionary treeWidget = new QTreeWidget; treeWidget->setColumnCount(3); treeWidget->setSelectionMode(QAbstractItemView::SingleSelection); treeWidget->header()->resizeSection(0,60); treeWidget->header()->resizeSection(1,100); treeWidget->header()->resizeSection(2,70); treeWidget->header()->hide(); treeWidget->setAlternatingRowColors (false); treeWidget->setIndentation(5); treeWidget->hide(); allRides = new QTreeWidgetItem(context->athlete->treeWidget, FOLDER_TYPE); allRides->setText(0, tr("All Activities")); treeWidget->expandItem(context->athlete->allRides); treeWidget->setFirstItemColumnSpanned (context->athlete->allRides, true); //.INTERVALS TREE -- transitionary intervalWidget = new IntervalTreeView(context); intervalWidget->setColumnCount(1); intervalWidget->setIndentation(5); intervalWidget->setSortingEnabled(false); intervalWidget->header()->hide(); intervalWidget->setAlternatingRowColors (false); intervalWidget->setSelectionBehavior(QAbstractItemView::SelectRows); intervalWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); intervalWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); intervalWidget->setContextMenuPolicy(Qt::CustomContextMenu); intervalWidget->setFrameStyle(QFrame::NoFrame); allIntervals = context->athlete->intervalWidget->invisibleRootItem(); allIntervals->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsDropEnabled); allIntervals->setText(0, tr("Intervals")); // populate ride list QTreeWidgetItem *last = NULL; QStringListIterator i(RideFileFactory::instance().listRideFiles(home)); while (i.hasNext()) { QString name = i.next(); QDateTime dt; if (RideFile::parseRideFileName(name, &dt)) { last = new RideItem(RIDE_TYPE, home.path(), name, dt, zones(), hrZones(), context); allRides->addChild(last); } } // trap signals connect(context, SIGNAL(configChanged()), this, SLOT(configChanged())); connect(treeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(rideTreeWidgetSelectionChanged())); connect(context,SIGNAL(rideAdded(RideItem*)),this,SLOT(checkCPX(RideItem*))); connect(context,SIGNAL(rideDeleted(RideItem*)),this,SLOT(checkCPX(RideItem*))); connect(intervalWidget,SIGNAL(itemSelectionChanged()), this, SLOT(intervalTreeWidgetSelectionChanged())); connect(intervalWidget,SIGNAL(itemChanged(QTreeWidgetItem *,int)), this, SLOT(updateRideFileIntervals())); }
bool doNeuronToolBoxPlugin(MainWindow* mainwindow, const vaa3d_neurontoolbox_paras & p) { v3d_msg(QString("Now try to run NeuronToolbox [%1]").arg(p.OPS), 0); try { QDir pluginsDir = QDir(qApp->applicationDirPath()); #if defined(Q_OS_WIN) if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release") pluginsDir.cdUp(); #elif defined(Q_OS_MAC) if (pluginsDir.dirName() == "MacOS") { pluginsDir.cdUp(); pluginsDir.cdUp(); pluginsDir.cdUp(); } #endif if (pluginsDir.cd("plugins/neuron_toolbox")==false) { v3d_msg("Cannot find ./plugins/neuron_toolbox directory!"); return false; } QStringList fileList = pluginsDir.entryList(QDir::Files); if (fileList.size()<1) { v3d_msg("Cannot find any file in the ./plugins/neuron_toolbox directory!"); return false; } QString fullpath = pluginsDir.absoluteFilePath(fileList.at(0)); //always just use the first file (assume it is the only one) found in the folder as the "correct" dll QPluginLoader* loader = new QPluginLoader(fullpath); if (!loader) { qDebug("unable to load neuron_toolbox plugin"); return false; } // v3d_msg(fullpath, 0); // V3d_PluginLoader mypluginloader(mainwindow); V3d_PluginLoader* mypluginloader = mainwindow->pluginLoader; //mypluginloader.runPlugin(loader, QString("about this plugin")); // curw->getImageData()->setCustomStructPointer((void *)(&p)); //to pass parameters to the imaging plugin // mypluginloader.runPlugin(loader, p.OPS); //mypluginloader.runPlugin(loader, "about"); V3DPluginArgList input; V3DPluginArgList output; V3DPluginArgItem arg; arg.p = (void *)(&p); input<<arg; mypluginloader->callPluginFunc(fullpath, "neuron_toolbox", input, output); // MainWindow * mainWin = qobject_cast<MainWindow*>(qApp->topLevelWidgets().at(0)); //mainwindow->pluginLoader->callPluginFunc(fullpath, "neuron_toolbox", input, output); } catch (...) { v3d_msg("NeuronToolbox has a problem", 1); return false; } return true; }
bool v3d_imaging(MainWindow* mainwindow, const v3d_imaging_paras & p) { v3d_msg(QString("Now try to do imaging or other plugin functions [%1]").arg(p.OPS), 0); try { const char* filename=p.imgp->getFileName(); //v3d_msg(QString("[")+filename+"]"); XFormWidget *curw = 0; if (filename) { curw = mainwindow->findMdiChild(QString(filename)); //search window using name. ZJL //unsigned char* rawdata=p.imgp->getRawData(); //QList <V3dR_MainWindow *> winlist=mainwindow->list_3Dview_win; //V3dR_MainWindow *curwin; //for(int i=0;i<winlist.size();i++) //{ // unsigned char* winrawdata=winlist.at(i)->getGLWidget()->getiDrawExternalParameter()->image4d->getRawData(); // if(rawdata==winrawdata) // { // curwin=winlist.at(i); // continue; // } //} if (!curw) { v3d_msg(QString("No window open yet (error detected in v3d_imaging() main entry point [filename={%1}]).").arg(filename)); return false; } } else { if (p.OPS != "Load file using Vaa3D data IO manager") //only allow data IO manager to pass an empty file name parameter here return false; } QDir pluginsDir = QDir(qApp->applicationDirPath()); #if defined(Q_OS_WIN) if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release") pluginsDir.cdUp(); #elif defined(Q_OS_MAC) if (pluginsDir.dirName() == "MacOS") { pluginsDir.cdUp(); pluginsDir.cdUp(); pluginsDir.cdUp(); } #endif if (p.OPS == "Vaa3D-Neuron2-APP2") { if (pluginsDir.cd("plugins/neuron_tracing/Vaa3D_Neuron2")==false) { v3d_msg("Cannot find ./plugins/neuron_tracing/Vaa3D_Neuron2 directory!"); return false; } } else if (p.OPS == "Fetch Highrez Image Data from File") { // @FIXED by Alessandro on 2015-09-30. // Since TeraFly is part of Vaa3D, here we can directly call TeraFly's domenu function w/o using QPluginLoader. curw->getImageData()->setCustomStructPointer((void *)(&p)); //to pass parameters to the imaging plugin tf::TeraFly::doaction(p.OPS); return true; } else if (p.OPS == "Load file using Vaa3D data IO manager") { if (pluginsDir.cd("plugins/data_IO/data_IO_manager")==false) { v3d_msg("Cannot find ./plugins/data_IO/data_IO_manager directory!"); return false; } } else { if (pluginsDir.cd("plugins/smartscope_controller")==false) { v3d_msg("Cannot find ./plugins/smartscope_controller directory!"); return false; } } QStringList fileList = pluginsDir.entryList(QDir::Files); if (fileList.size()<1) { v3d_msg("Cannot find any file in the ./plugins/smartscope_controller directory!"); return false; } QString fullpath = pluginsDir.absoluteFilePath(fileList.at(0)); //always just use the first file (assume it is the only one) found in the folder as the "correct" dll //the real dll name should be "microimaging.dll" QPluginLoader* loader = new QPluginLoader(fullpath); if (!loader) { qDebug("ERROR in V3d_PluginLoader::searchPluginFiles the imaging module(%s)", qPrintable(fullpath)); return false; } v3d_msg(fullpath, 0); V3d_PluginLoader mypluginloader(mainwindow); if (curw) { //mypluginloader.runPlugin(loader, QString("about this plugin")); curw->getImageData()->setCustomStructPointer((void *)(&p)); //to pass parameters to the imaging plugin QTime t; t.start(); mypluginloader.runPlugin(loader, p.OPS); //mypluginloader.runPlugin(loader, "about"); v3d_msg(QString("** invoke time for the plugin is [%1] ms.").arg(t.elapsed()*1000), 0); } else //for data IO manager in which case curw is NULL { QTime t; t.start(); mypluginloader.runPlugin(loader, p.datafilename); //the data IO manager is specially designed to pass the datafilename parameter in this way. 2013-12-02. by PHC. what an ugly design here! v3d_msg(QString("** invoke time for the plugin is [%1] ms.").arg(t.elapsed()*1000), 0); } } catch (...) { v3d_msg("Catch a problem in v3d_imaging() wrapper function.", 1); return false; } return true; }
void QxFileBrowser::updateGotoMenu() { for (int i = 0, n = cwdPast_.count(); i < n; ++i) { if (!QDir(cwdPast_.at(i)).exists()) { cwdPast_.removeAt(i); --i; --n; } } if (gotoMenu_) { disconnect(gotoMenu_, 0, 0, 0); gotoMenu_->setAttribute(Qt::WA_DeleteOnClose, true); // destruction workaround, HACK gotoMenu_->close(); } gotoMenu_ = new QMenu(this); { QFont font = gotoMenu_->font(); font.setPixelSize(styleManager()->constant("dirOpenMenuFontSizePx")); gotoMenu_->setFont(font); } connect(gotoMenu_, SIGNAL(triggered(QAction*)), this, SLOT(cwdSet(QAction*))); actionToPath_.clear(); QFileIconProvider iconProvider; QDir dir = QDir::current(); while (!dir.isRoot()) { dir.cdUp(); QAction* action = gotoMenu_->addAction(iconProvider.icon(QFileInfo(dir.path())), dir.isRoot() ? QDir::separator() : dir.dirName()); actionToPath_[action] = dir.path(); } gotoMenu_->addSeparator(); recentMenu_ = gotoMenu_->addMenu(tr("Recent Places")); { QFont font = recentMenu_->font(); font.setPixelSize(styleManager()->constant("dirOpenMenuFontSizePx")); recentMenu_->setFont(font); } // QxDesignHack::beautify(recentMenu_); connect(recentMenu_, SIGNAL(triggered(QAction*)), this, SLOT(cwdSet(QAction*))); int n = cwdPast_.count(); recentMenu_->setDisabled(n == 0); for (int i = n-1; i >= 0; --i) { QString path = cwdPast_[i]; QString name = path; // QFileInfo(path).fileName(); if (name == QString()) name = QDir::separator(); QAction* action = recentMenu_->addAction(iconProvider.icon(QFileInfo(path)), name); actionToPath_[action] = path; } gotoButton_->setMenu(gotoMenu_); }
int main(int argc, char *argv[]) { //See http://doc.qt.io/qt-5/qopenglwidget.html#opengl-function-calls-headers-and-qopenglfunctions /** Calling QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance is mandatory on some platforms (for example, OS X) when an OpenGL core profile context is requested. This is to ensure that resource sharing between contexts stays functional as all internal contexts are created using the correct version and profile. **/ { QSurfaceFormat format = QSurfaceFormat::defaultFormat(); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); format.setStencilBufferSize(0); #ifdef CC_GL_WINDOW_USE_QWINDOW format.setStereo(true); #endif #ifdef Q_OS_MAC format.setStereo(false); format.setVersion( 2, 1 ); format.setProfile( QSurfaceFormat::CoreProfile ); #endif #ifdef QT_DEBUG format.setOption(QSurfaceFormat::DebugContext); #endif QSurfaceFormat::setDefaultFormat(format); } ccApplication a(argc, argv); //Locale management { //Force 'english' locale so as to get a consistent behavior everywhere QLocale locale = QLocale(QLocale::English); locale.setNumberOptions(QLocale::c().numberOptions()); QLocale::setDefault(locale); #ifdef Q_OS_UNIX //We reset the numeric locale for POSIX functions //See http://qt-project.org/doc/qt-5/qcoreapplication.html#locale-settings setlocale(LC_NUMERIC, "C"); #endif } #ifdef USE_VLD VLDEnable(); #endif #ifdef Q_OS_MAC // This makes sure that our "working directory" is not within the application bundle QDir appDir = QCoreApplication::applicationDirPath(); if ( appDir.dirName() == "MacOS" ) { appDir.cdUp(); appDir.cdUp(); appDir.cdUp(); QDir::setCurrent( appDir.absolutePath() ); } #endif if (!QGLFormat::hasOpenGL()) { QMessageBox::critical(0, "Error", "This application needs OpenGL to run!"); return EXIT_FAILURE; } if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_1) == 0) { QMessageBox::critical(0, "Error", "This application needs OpenGL 2.1 at least to run!"); return EXIT_FAILURE; } //common data initialization FileIOFilter::InitInternalFilters(); //load all known I/O filters (plugins will come later!) ccNormalVectors::GetUniqueInstance(); //force pre-computed normals array initialization ccColorScalesManager::GetUniqueInstance(); //force pre-computed color tables initialization ccViewer w/*(0,Qt::Window|Qt::CustomizeWindowHint)*/; #ifdef Q_OS_MAC a.setViewer( &w ); #endif //register minimal logger to display errors ccViewerLog logger(&w); ccLog::RegisterInstance(&logger); w.show(); //files to open are passed as argument if (argc > 1) { //parse arguments QStringList filenames; int i = 1; while ( i < argc) { QString argument = QString(argv[i++]).toUpper(); //Argument '-WIN X Y W H' (to set window size and position) if (argument.toUpper() == "-WIN") { bool ok = true; if (i+3 < argc) { bool converionOk; int x = QString(argv[i ]).toInt(&converionOk); ok &= converionOk; int y = QString(argv[i+1]).toInt(&converionOk); ok &= converionOk; int width = QString(argv[i+2]).toInt(&converionOk); ok &= converionOk; int height = QString(argv[i+3]).toInt(&converionOk); ok &= converionOk; i += 4; if (ok) { //change window position and size w.move(x,y); w.resize(width,height); } } if (!ok) { ccLog::Warning("Invalid arguments! 4 integer values are expected after '-win' (X Y W H)"); break; } } else if (argument == "-TOP") { w.setWindowFlags(w.windowFlags() | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint); w.show(); } else //any other argument is assumed to be a filename (that will we try to load) { filenames << argument; } } if (!filenames.empty()) w.addToDB(filenames); } #ifdef Q_OS_MAC // process events to load any files on the command line QCoreApplication::processEvents(); #endif w.checkForLoadedEntities(); int result = a.exec(); //release global structures FileIOFilter::UnregisterAll(); return result; }
void Package::reverse_directory(QDir & d, bool rec) { if (! allowed(DirFilter, d.dirName())) return; // reads files QFileInfoList list = d.entryInfoList(QDir::Files | QDir::Readable); if (!list.isEmpty()) { QFileInfoList::iterator it = list.begin(); while (it != list.end()) { if ((*it).extension(FALSE) == Ext) { if (allowed(FileFilter, (*it).fileName())) reverse_file(WrapperStr((*it).filePath().toAscii().constData()), WrapperStr(my_baseName(&(*it)).toAscii().constData())); if (progress) progress->tic(); app->processEvents(); } ++it; } /* while ((fi = it.current()) != 0) { if (fi->extension(FALSE) == Ext) { if (allowed(FileFilter, fi->fileName())) reverse_file(WrapperStr(fi->filePath()), WrapperStr(my_baseName(fi))); if (progress) progress->tic(); app->processEvents(); } ++it; }*/ } if (rec) { // sub directories list = d.entryInfoList(QDir::Dirs | QDir::NoSymLinks); if (!list.isEmpty()) { QFileInfoList::iterator itd = list.begin(); while (itd != list.end()) { if ((*itd).fileName()[0] != '.') { QDir sd((*itd).filePath()); Package * p = find(WrapperStr(sd.dirName().toAscii().constData()), TRUE); if (p != 0) p->reverse_directory(sd, TRUE); } ++itd; } } } }
int main(int argc, char **argv) { ccApplication::init(); ccApplication app(argc, argv); //store the log message until a valid logging instance is registered ccLog::EnableMessageBackup(true); //restore some global parameters { QSettings settings; settings.beginGroup(ccPS::GlobalShift()); double maxAbsCoord = settings.value(ccPS::MaxAbsCoord(), ccGlobalShiftManager::MaxCoordinateAbsValue()).toDouble(); double maxAbsDiag = settings.value(ccPS::MaxAbsDiag(), ccGlobalShiftManager::MaxBoundgBoxDiagonal()).toDouble(); settings.endGroup(); ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2").arg(maxAbsCoord, 0, 'e', 0).arg(maxAbsDiag, 0, 'e', 0)); ccGlobalShiftManager::SetMaxCoordinateAbsValue(maxAbsCoord); ccGlobalShiftManager::SetMaxBoundgBoxDiagonal(maxAbsDiag); } //Command line mode? bool commandLine = (argc > 1 && argv[1][0] == '-'); //specific commands int lastArgumentIndex = 1; QTranslator translator; if (commandLine) { //translation file selection if (QString(argv[lastArgumentIndex]).toUpper() == "-LANG") { QString langFilename = QString(argv[2]); //Load translation file if (translator.load(langFilename, QCoreApplication::applicationDirPath())) { qApp->installTranslator(&translator); } else { QMessageBox::warning(0, QObject::tr("Translation"), QObject::tr("Failed to load language file '%1'").arg(langFilename)); } commandLine = false; lastArgumentIndex += 2; } } //splash screen QScopedPointer<QSplashScreen> splash(nullptr); QTimer splashTimer; //standard mode if (!commandLine) { if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_1) == 0) { QMessageBox::critical(0, "Error", "This application needs OpenGL 2.1 at least to run!"); return EXIT_FAILURE; } //splash screen QPixmap pixmap(QString::fromUtf8(":/CC/images/imLogoV2Qt.png")); splash.reset(new QSplashScreen(pixmap, Qt::WindowStaysOnTopHint)); splash->show(); QApplication::processEvents(); } //global structures initialization FileIOFilter::InitInternalFilters(); //load all known I/O filters (plugins will come later!) ccNormalVectors::GetUniqueInstance(); //force pre-computed normals array initialization ccColorScalesManager::GetUniqueInstance(); //force pre-computed color tables initialization //load the plugins ccPluginManager::loadPlugins(); int result = 0; //command line mode if (commandLine) { //command line processing (no GUI) result = ccCommandLineParser::Parse(argc, argv, ccPluginManager::pluginList()); } else { //main window init. MainWindow* mainWindow = MainWindow::TheInstance(); if (!mainWindow) { QMessageBox::critical(0, "Error", "Failed to initialize the main application window?!"); return EXIT_FAILURE; } mainWindow->initPlugins(); mainWindow->show(); QApplication::processEvents(); //show current Global Shift parameters in Console { ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2") .arg(ccGlobalShiftManager::MaxCoordinateAbsValue(), 0, 'e', 0) .arg(ccGlobalShiftManager::MaxBoundgBoxDiagonal(), 0, 'e', 0)); } if (argc > lastArgumentIndex) { if (splash) { splash->close(); } //any additional argument is assumed to be a filename --> we try to load it/them QStringList filenames; for (int i = lastArgumentIndex; i < argc; ++i) { QString arg(argv[i]); //special command: auto start a plugin if (arg.startsWith(":start-plugin:")) { QString pluginName = arg.mid(14); QString pluginNameUpper = pluginName.toUpper(); //look for this plugin bool found = false; for ( ccPluginInterface *plugin : ccPluginManager::pluginList() ) { if (plugin->getName().replace(' ', '_').toUpper() == pluginNameUpper) { found = true; bool success = plugin->start(); if (!success) { ccLog::Error(QString("Failed to start the plugin '%1'").arg(plugin->getName())); } break; } } if (!found) { ccLog::Error(QString("Couldn't find the plugin '%1'").arg(pluginName.replace('_', ' '))); } } else { filenames << QString::fromLocal8Bit(argv[i]); } } mainWindow->addToDB(filenames); } else if (splash) { //count-down to hide the timer (only effective once the application will have actually started!) QObject::connect(&splashTimer, &QTimer::timeout, [&]() { if (splash) splash->close(); QCoreApplication::processEvents(); splash.reset(); }); splashTimer.setInterval(1000); splashTimer.start(); } //change the default path to the application one (do this AFTER processing the command line) QDir workingDir = QCoreApplication::applicationDirPath(); #ifdef Q_OS_MAC // This makes sure that our "working directory" is not within the application bundle if ( workingDir.dirName() == "MacOS" ) { workingDir.cdUp(); workingDir.cdUp(); workingDir.cdUp(); } #endif QDir::setCurrent(workingDir.absolutePath()); //let's rock! try { result = app.exec(); } catch (const std::exception& e) { QMessageBox::warning(0, "CC crashed!", QString("Hum, it seems that CC has crashed... Sorry about that :)\n") + e.what()); } catch (...) { QMessageBox::warning(0, "CC crashed!", "Hum, it seems that CC has crashed... Sorry about that :)"); } //release the plugins for ( ccPluginInterface *plugin : ccPluginManager::pluginList() ) { plugin->stop(); //just in case } } //release global structures MainWindow::DestroyInstance(); FileIOFilter::UnregisterAll(); #ifdef CC_TRACK_ALIVE_SHARED_OBJECTS //for debug purposes unsigned alive = CCShareable::GetAliveCount(); if (alive > 1) { printf("Error: some shared objects (%u) have not been released on program end!",alive); system("PAUSE"); } #endif return result; }
QgsGrassRasterProvider::QgsGrassRasterProvider( QString const &uri ) : QgsRasterDataProvider( uri ) , mNoDataValue( std::numeric_limits<double>::quiet_NaN() ) { QgsDebugMsg( "QgsGrassRasterProvider: constructing with uri '" + uri + "'." ); if ( !QgsGrass::init() ) { return; } // Parse URI, it is the same like using GDAL, i.e. path to raster cellhd, i.e. // /path/to/gisdbase/location/mapset/cellhd/map QFileInfo fileInfo( uri ); if ( !fileInfo.exists() ) // then we keep it valid forever { appendError( ERR( tr( "cellhd file %1 does not exist" ).arg( uri ) ) ); return; } mMapName = fileInfo.fileName(); QDir dir = fileInfo.dir(); QString element = dir.dirName(); if ( element != QLatin1String( "cellhd" ) ) { appendError( ERR( tr( "Groups not yet supported" ) ) ); return; } dir.cdUp(); // skip cellhd mMapset = dir.dirName(); dir.cdUp(); mLocation = dir.dirName(); dir.cdUp(); mGisdbase = dir.path(); QgsDebugMsg( QString( "gisdbase: %1" ).arg( mGisdbase ) ); QgsDebugMsg( QString( "location: %1" ).arg( mLocation ) ); QgsDebugMsg( QString( "mapset: %1" ).arg( mMapset ) ); QgsDebugMsg( QString( "mapName: %1" ).arg( mMapName ) ); mTimestamp = dataTimestamp(); mRasterValue.set( mGisdbase, mLocation, mMapset, mMapName ); //mValidNoDataValue = true; QString error; mCrs = QgsGrass::crs( mGisdbase, mLocation, error ); appendIfError( error ); QgsDebugMsg( "mCrs: " + mCrs.toWkt() ); // the block size can change of course when the raster is overridden // ibut it is only called once when statistics are calculated error.clear(); QgsGrass::size( mGisdbase, mLocation, mMapset, mMapName, &mCols, &mRows, error ); appendIfError( error ); error.clear(); mInfo = QgsGrass::info( mGisdbase, mLocation, mMapset, mMapName, QgsGrassObject::Raster, QStringLiteral( "info" ), QgsRectangle(), 0, 0, 3000, error ); appendIfError( error ); mGrassDataType = mInfo[QStringLiteral( "TYPE" )].toInt(); QgsDebugMsg( "mGrassDataType = " + QString::number( mGrassDataType ) ); // TODO: avoid showing these strange numbers in GUI // TODO: don't save no data values in project file, add a flag if value was defined by user double myInternalNoDataValue; if ( mGrassDataType == CELL_TYPE ) { myInternalNoDataValue = std::numeric_limits<int>::min(); } else if ( mGrassDataType == DCELL_TYPE ) { // Don't use numeric limits, raster layer is using // std::fabs( myValue - mNoDataValue ) <= TINY_VALUE // if the mNoDataValue would be a limit, the subtraction could overflow. // No data value is shown in GUI, use some nice number. // Choose values with small representation error. // limit: 1.7976931348623157e+308 //myInternalNoDataValue = -1e+300; myInternalNoDataValue = std::numeric_limits<double>::quiet_NaN(); } else { if ( mGrassDataType != FCELL_TYPE ) { QgsDebugMsg( "unexpected data type" ); } // limit: 3.40282347e+38 //myInternalNoDataValue = -1e+30; myInternalNoDataValue = std::numeric_limits<float>::quiet_NaN(); } mNoDataValue = myInternalNoDataValue; mSrcHasNoDataValue.append( true ); mSrcNoDataValue.append( mNoDataValue ); mUseSrcNoDataValue.append( true ); QgsDebugMsg( QString( "myInternalNoDataValue = %1" ).arg( myInternalNoDataValue ) ); // TODO: refresh mRows and mCols if raster was rewritten // We have to decide some reasonable block size, not to big to occupate too much // memory, not too small to result in too many calls to readBlock -> qgis.d.rast // for statistics int typeSize = dataTypeSize( dataType( 1 ) ); if ( mCols > 0 && typeSize > 0 ) { const int cache_size = 10000000; // ~ 10 MB mYBlockSize = cache_size / typeSize / mCols; if ( mYBlockSize > mRows ) { mYBlockSize = mRows; } QgsDebugMsg( "mYBlockSize = " + QString::number( mYBlockSize ) ); mValid = true; } }
void ChannelData::handleChannels(int id, QValueList<ChanInfo> *chanlist) { QString fileprefix = SetupIconCacheDirectory(); QDir::setCurrent(fileprefix); fileprefix += "/"; QValueList<ChanInfo>::iterator i = chanlist->begin(); for (; i != chanlist->end(); i++) { QString localfile = ""; if ((*i).iconpath != "") { QDir remotefile = QDir((*i).iconpath); QString filename = remotefile.dirName(); localfile = fileprefix + filename; QFile actualfile(localfile); if (!actualfile.exists()) { QString command = QString("wget ") + (*i).iconpath; system(command); } } MSqlQuery query(MSqlQuery::InitCon()); QString querystr; if ((*i).old_xmltvid != "") { querystr.sprintf("SELECT xmltvid FROM channel WHERE xmltvid = '%s'", (*i).old_xmltvid.ascii()); query.exec(querystr); if (query.isActive() && query.size() > 0) { VERBOSE(VB_GENERAL, QString("Converting old xmltvid (%1) to " "new (%2)") .arg((*i).old_xmltvid) .arg((*i).xmltvid)); query.exec(QString("UPDATE channel SET xmltvid = '%1' WHERE xmltvid = '%2';") .arg((*i).xmltvid) .arg((*i).old_xmltvid)); if (!query.numRowsAffected()) MythContext::DBError("xmltvid conversion",query); } } querystr.sprintf("SELECT chanid,name,callsign,channum,finetune," "icon,freqid,tvformat FROM channel WHERE " "xmltvid = '%s' AND sourceid = %d;", (*i).xmltvid.ascii(), id); query.exec(querystr); if (query.isActive() && query.size() > 0) { query.next(); QString chanid = query.value(0).toString(); if (interactive) { QString name = QString::fromUtf8(query.value(1).toString()); QString callsign = QString::fromUtf8(query.value(2).toString()); QString chanstr = QString::fromUtf8(query.value(3).toString()); QString finetune = QString::fromUtf8(query.value(4).toString()); QString icon = QString::fromUtf8(query.value(5).toString()); QString freqid = QString::fromUtf8(query.value(6).toString()); QString tvformat = QString::fromUtf8(query.value(7).toString()); cout << "### " << endl; cout << "### Existing channel found" << endl; cout << "### " << endl; cout << "### xmltvid = " << (*i).xmltvid.local8Bit() << endl; cout << "### chanid = " << chanid.local8Bit() << endl; cout << "### name = " << name.local8Bit() << endl; cout << "### callsign = " << callsign.local8Bit() << endl; cout << "### channum = " << chanstr.local8Bit() << endl; if (channel_preset) cout << "### freqid = " << freqid.local8Bit() << endl; cout << "### finetune = " << finetune.local8Bit() << endl; cout << "### tvformat = " << tvformat.local8Bit() << endl; cout << "### icon = " << icon.local8Bit() << endl; cout << "### " << endl; (*i).name = name; (*i).callsign = callsign; (*i).chanstr = chanstr; (*i).finetune = finetune; (*i).freqid = freqid; (*i).tvformat = tvformat; promptForChannelUpdates(i, atoi(chanid.ascii())); if ((*i).callsign == "") (*i).callsign = chanid; if (name != (*i).name || callsign != (*i).callsign || chanstr != (*i).chanstr || finetune != (*i).finetune || freqid != (*i).freqid || icon != localfile || tvformat != (*i).tvformat) { MSqlQuery subquery(MSqlQuery::InitCon()); subquery.prepare("UPDATE channel SET chanid = :CHANID, " "name = :NAME, callsign = :CALLSIGN, " "channum = :CHANNUM, finetune = :FINE, " "icon = :ICON, freqid = :FREQID, " "tvformat = :TVFORMAT " " WHERE xmltvid = :XMLTVID " "AND sourceid = :SOURCEID;"); subquery.bindValue(":CHANID", chanid); subquery.bindValue(":NAME", (*i).name.utf8()); subquery.bindValue(":CALLSIGN", (*i).callsign.utf8()); subquery.bindValue(":CHANNUM", (*i).chanstr); subquery.bindValue(":FINE", (*i).finetune.toInt()); subquery.bindValue(":ICON", localfile); subquery.bindValue(":FREQID", (*i).freqid); subquery.bindValue(":TVFORMAT", (*i).tvformat); subquery.bindValue(":XMLTVID", (*i).xmltvid); subquery.bindValue(":SOURCEID", id); if (!subquery.exec()) { VERBOSE(VB_IMPORTANT, QString("DB Error: Channel " "update failed, SQL query was: %1") .arg(querystr)); } else { cout << "### " << endl; cout << "### Change performed" << endl; cout << "### " << endl; } } else { cout << "### " << endl; cout << "### Nothing changed" << endl; cout << "### " << endl; } } else { if (!non_us_updating && localfile != "") { MSqlQuery subquery(MSqlQuery::InitCon()); subquery.prepare("UPDATE channel SET icon = :ICON WHERE " "chanid = :CHANID;"); subquery.bindValue(":ICON", localfile); subquery.bindValue(":CHANID", chanid); if (!subquery.exec()) MythContext::DBError("Channel icon change", subquery); } } } else { int major, minor; long long freq; get_atsc_stuff((*i).chanstr, id, (*i).freqid.toInt(), major, minor, freq); if (interactive && ((minor == 0) || (freq > 0))) { cout << "### " << endl; cout << "### New channel found" << endl; cout << "### " << endl; cout << "### name = " << (*i).name.local8Bit() << endl; cout << "### callsign = " << (*i).callsign.local8Bit() << endl; cout << "### channum = " << (*i).chanstr.local8Bit() << endl; if (channel_preset) cout << "### freqid = " << (*i).freqid.local8Bit() << endl; cout << "### finetune = " << (*i).finetune.local8Bit() << endl; cout << "### tvformat = " << (*i).tvformat.local8Bit() << endl; cout << "### icon = " << localfile.local8Bit() << endl; cout << "### " << endl; uint chanid = promptForChannelUpdates(i,0); if ((*i).callsign == "") (*i).callsign = QString::number(chanid); int mplexid = 0; if ((chanid > 0) && (minor > 0)) mplexid = ChannelUtil::CreateMultiplex(id, "atsc", freq, "8vsb"); if (((mplexid > 0) || ((minor == 0) && (chanid > 0))) && ChannelUtil::CreateChannel( mplexid, id, chanid, (*i).callsign, (*i).name, (*i).chanstr, 0 /*service id*/, major, minor, false /*use on air guide*/, false /*hidden*/, false /*hidden in guide*/, (*i).freqid, localfile, (*i).tvformat, (*i).xmltvid)) { cout << "### " << endl; cout << "### Channel inserted" << endl; cout << "### " << endl; } else { cout << "### " << endl; cout << "### Channel skipped" << endl; cout << "### " << endl; } } else if (!non_us_updating && ((minor == 0) || (freq > 0))) { // We only do this if we are not asked to skip it with the // --updating flag. int mplexid = 0, chanid = 0; if (minor > 0) { mplexid = ChannelUtil::CreateMultiplex( id, "atsc", freq, "8vsb"); } if ((mplexid > 0) || (minor == 0)) chanid = ChannelUtil::CreateChanID(id, (*i).chanstr); if ((*i).callsign.isEmpty()) { QStringList words = QStringList::split(" ",(*i).name.simplifyWhiteSpace().upper()); QString callsign = ""; QString w1 = words.size() > 0 ? words[0] : QString(); QString w2 = words.size() > 1 ? words[1] : QString(); if (w1.isEmpty()) callsign = QString::number(chanid); else if (w2.isEmpty()) callsign = words[0].left(5); else { callsign = w1.left(w2.length() == 1 ? 4:3); callsign += w2.left(5 - callsign.length()); } (*i).callsign = callsign; } if (chanid > 0) { QString cstr = QString((*i).chanstr); if(channel_preset && cstr.isEmpty()) cstr = QString::number(chanid % 1000); ChannelUtil::CreateChannel( mplexid, id, chanid, (*i).callsign, (*i).name, cstr, 0 /*service id*/, major, minor, false /*use on air guide*/, false /*hidden*/, false /*hidden in guide*/, (*i).freqid, localfile, (*i).tvformat, (*i).xmltvid); } } } } }
int main(int argc, char **argv) { //See http://doc.qt.io/qt-5/qopenglwidget.html#opengl-function-calls-headers-and-qopenglfunctions /** Calling QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance is mandatory on some platforms (for example, OS X) when an OpenGL core profile context is requested. This is to ensure that resource sharing between contexts stays functional as all internal contexts are created using the correct version and profile. **/ { QSurfaceFormat format = QSurfaceFormat::defaultFormat(); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); format.setOption(QSurfaceFormat::StereoBuffers, true); format.setStencilBufferSize(0); #ifdef CC_GL_WINDOW_USE_QWINDOW format.setStereo(true); #endif #ifdef Q_OS_MAC format.setStereo(false); format.setVersion( 2, 1 ); format.setProfile( QSurfaceFormat::CoreProfile ); #endif #ifdef QT_DEBUG format.setOption(QSurfaceFormat::DebugContext, true); #endif QSurfaceFormat::setDefaultFormat(format); } //The 'AA_ShareOpenGLContexts' attribute must be defined BEFORE the creation of the Q(Gui)Application //DGM: this is mandatory to enable exclusive full screen for ccGLWidget (at least on Windows) QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts); //QT initialiation qccApplication app(argc, argv); //Locale management { //Force 'english' locale so as to get a consistent behavior everywhere QLocale locale = QLocale(QLocale::English); locale.setNumberOptions(QLocale::c().numberOptions()); QLocale::setDefault(locale); #ifdef Q_OS_UNIX //We reset the numeric locale for POSIX functions //See http://qt-project.org/doc/qt-5/qcoreapplication.html#locale-settings setlocale(LC_NUMERIC, "C"); #endif } #ifdef USE_VLD VLDEnable(); #endif #ifdef Q_OS_MAC // This makes sure that our "working directory" is not within the application bundle QDir appDir = QCoreApplication::applicationDirPath(); if ( appDir.dirName() == "MacOS" ) { appDir.cdUp(); appDir.cdUp(); appDir.cdUp(); QDir::setCurrent( appDir.absolutePath() ); } #endif //splash screen QSplashScreen* splash = 0; QTime splashStartTime; //restore some global parameters { QSettings settings; settings.beginGroup(ccPS::GlobalShift()); double maxAbsCoord = settings.value(ccPS::MaxAbsCoord(), ccGlobalShiftManager::MaxCoordinateAbsValue()).toDouble(); double maxAbsDiag = settings.value(ccPS::MaxAbsDiag(), ccGlobalShiftManager::MaxBoundgBoxDiagonal()).toDouble(); settings.endGroup(); ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2").arg(maxAbsCoord, 0, 'e', 0).arg(maxAbsDiag, 0, 'e', 0)); ccGlobalShiftManager::SetMaxCoordinateAbsValue(maxAbsCoord); ccGlobalShiftManager::SetMaxBoundgBoxDiagonal(maxAbsDiag); } //Command line mode? bool commandLine = (argc > 1 && argv[1][0] == '-'); //specific case: translation file selection int lastArgumentIndex = 1; QTranslator translator; if (commandLine && QString(argv[1]).toUpper() == "-LANG") { QString langFilename = QString(argv[2]); //Load translation file if (translator.load(langFilename, QCoreApplication::applicationDirPath())) { qApp->installTranslator(&translator); } else { QMessageBox::warning(0, QObject::tr("Translation"), QObject::tr("Failed to load language file '%1'").arg(langFilename)); } commandLine = false; lastArgumentIndex = 3; } //command line mode if (!commandLine) { if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_1) == 0) { QMessageBox::critical(0, "Error", "This application needs OpenGL 2.1 at least to run!"); return EXIT_FAILURE; } //splash screen splashStartTime.start(); QPixmap pixmap(QString::fromUtf8(":/CC/images/imLogoV2Qt.png")); splash = new QSplashScreen(pixmap, Qt::WindowStaysOnTopHint); splash->show(); QApplication::processEvents(); } //global structures initialization ccTimer::Init(); FileIOFilter::InitInternalFilters(); //load all known I/O filters (plugins will come later!) ccNormalVectors::GetUniqueInstance(); //force pre-computed normals array initialization ccColorScalesManager::GetUniqueInstance(); //force pre-computed color tables initialization int result = 0; if (commandLine) { //command line processing (no GUI) result = ccCommandLineParser::Parse(argc, argv); } else { //main window init. MainWindow* mainWindow = MainWindow::TheInstance(); if (!mainWindow) { QMessageBox::critical(0, "Error", "Failed to initialize the main application window?!"); return EXIT_FAILURE; } mainWindow->show(); QApplication::processEvents(); //show current Global Shift parameters in Console { ccLog::Print(QString("[Global Shift] Max abs. coord = %1 / max abs. diag = %2") .arg(ccGlobalShiftManager::MaxCoordinateAbsValue(), 0, 'e', 0) .arg(ccGlobalShiftManager::MaxBoundgBoxDiagonal(), 0, 'e', 0)); } if (argc > lastArgumentIndex) { if (splash) splash->close(); //any additional argument is assumed to be a filename --> we try to load it/them QStringList filenames; for (int i = lastArgumentIndex; i<argc; ++i) filenames << QString(argv[i]); mainWindow->addToDB(filenames); } if (splash) { //we want the splash screen to be visible a minimum amount of time (1000 ms.) while (splashStartTime.elapsed() < 1000) { splash->raise(); QApplication::processEvents(); //to let the system breath! } splash->close(); QApplication::processEvents(); delete splash; splash = 0; } //let's rock! try { result = app.exec(); } catch(...) { QMessageBox::warning(0, "CC crashed!","Hum, it seems that CC has crashed... Sorry about that :)"); } } //release global structures MainWindow::DestroyInstance(); FileIOFilter::UnregisterAll(); #ifdef CC_TRACK_ALIVE_SHARED_OBJECTS //for debug purposes unsigned alive = CCShareable::GetAliveCount(); if (alive > 1) { printf("Error: some shared objects (%u) have not been released on program end!",alive); system("PAUSE"); } #endif return result; }
/************************************************************ * WriteToFile * ----------------------------------------------------------- * - Overloaded * - see WriteToFile(Qstring) * Returns true only if it successfully writes * Returns false if it fails to open, write or if there are * no customers in the list. * ------------------------------------------------------------ * File path is set when first establishing the database *************************************************************/ bool CustomerList::WriteToFile() { Node<Customer>* _customerPtr; QDir dataPath = QDir::current(); bool writeStatus; // Failstate signal writeStatus = false; // Initialize QFile and write failed, Appended File to path, QFile Creates while(dataPath.dirName() != "Class-Project") { dataPath.cdUp(); } dataPath.cd("Database-Files"); QFile customerDataFile((dataPath.path() + "/CustomerList.txt")); if(customerDataFile.open((QIODevice::ReadWrite | QIODevice::Text)|QIODevice::Truncate) && !isEmpty()) { qDebug () << "Customer file opened "; QTextStream out(&customerDataFile); _customerPtr = _head; while(_customerPtr != 0) { out << _customerPtr->GetData().getUserName() << "\n"; out << _customerPtr->GetData().getAddressLine1() << "\n"; out << _customerPtr->GetData().getAddressLine2() << "\n"; out << _customerPtr->GetData().getInterest() << "\n"; out << _customerPtr->GetData().getKey() << "\n"; out << _customerPtr->GetData().getPassword() << "\n"; out << _customerPtr->GetData().getEmail() << "\n"; out << _customerPtr->GetData().getAccountNum() << "\n"; out << _customerPtr->GetData().getAccessStr() << "\n"; if((_customerPtr = _customerPtr->GetNext()) != 0) { out << "\n"; } }// END WHILE // Flushes output buffer out.flush(); writeStatus = true; } // END OPEN FILE IF // Flushes and coses the data file customerDataFile.flush(); customerDataFile.close(); // Returns True or False status return writeStatus; }// **** END METHOD **** //