本文整理汇总了C++中QDir类的典型用法代码示例。如果您正苦于以下问题:C++ QDir类的具体用法?C++ QDir怎么用?C++ QDir使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QDir类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: QLatin1String
void HistoryManager::save()
{
QSettings settings;
settings.beginGroup(QLatin1String("history"));
settings.setValue(QLatin1String("historyLimit"), m_historyLimit);
bool saveAll = m_lastSavedUrl.isEmpty();
int first = m_history.count() - 1;
if (!saveAll) {
// find the first one to save
for (int i = 0; i < m_history.count(); ++i) {
if (m_history.at(i).url == m_lastSavedUrl) {
first = i - 1;
break;
}
}
}
if (first == m_history.count() - 1)
saveAll = true;
QString directory = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
if (directory.isEmpty())
directory = QDir::homePath() + QLatin1String("/.") + QCoreApplication::applicationName();
if (!QFile::exists(directory)) {
QDir dir;
dir.mkpath(directory);
}
QFile historyFile(directory + QLatin1String("/history"));
// When saving everything use a temporary file to prevent possible data loss.
QTemporaryFile tempFile;
tempFile.setAutoRemove(false);
bool open = false;
if (saveAll) {
open = tempFile.open();
} else {
open = historyFile.open(QFile::Append);
}
if (!open) {
qWarning() << "Unable to open history file for saving"
<< (saveAll ? tempFile.fileName() : historyFile.fileName());
return;
}
QDataStream out(saveAll ? &tempFile : &historyFile);
for (int i = first; i >= 0; --i) {
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
HistoryItem item = m_history.at(i);
stream << HISTORY_VERSION << item.url << item.dateTime << item.title;
out << data;
}
tempFile.close();
if (saveAll) {
if (historyFile.exists() && !historyFile.remove())
qWarning() << "History: error removing old history." << historyFile.errorString();
if (!tempFile.rename(historyFile.fileName()))
qWarning() << "History: error moving new history over old." << tempFile.errorString() << historyFile.fileName();
}
m_lastSavedUrl = m_history.value(0).url;
}
示例2: ULTRACOPIER_DEBUGCONSOLE
bool WriteThread::internalOpen()
{
//do a bug
ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] internalOpen destination: ")+file.fileName());
if(stopIt)
{
ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] close because stopIt is at true"));
emit closed();
return false;
}
if(file.isOpen())
{
ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] already open! destination: ")+file.fileName());
return false;
}
if(file.fileName().isEmpty())
{
errorString_internal=tr("Path resolution error (Empty path)");
ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,QStringLiteral("[")+QString::number(id)+QStringLiteral("] ")+QStringLiteral("Unable to open: %1, error: %2").arg(file.fileName()).arg(errorString_internal));
emit error();
return false;
}
ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] before the mutex"));
//set to LISTBLOCKSIZE
if(sequential)
{
while(writeFull.available()<1)
writeFull.release();
if(writeFull.available()>1)
writeFull.acquire(writeFull.available()-1);
}
else
{
while(writeFull.available()<numberOfBlock)
writeFull.release();
if(writeFull.available()>numberOfBlock)
writeFull.acquire(writeFull.available()-numberOfBlock);
}
ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] after the mutex"));
stopIt=false;
endDetected=false;
#ifdef ULTRACOPIER_PLUGIN_DEBUG
stat=InodeOperation;
#endif
//mkpath check if exists and return true if already exists
QFileInfo destinationInfo(file);
QDir destinationFolder;
{
mkpathTransfer->acquire();
if(!destinationFolder.exists(destinationInfo.absolutePath()))
{
ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] ")+QStringLiteral("Try create the path: %1")
.arg(destinationInfo.absolutePath()));
if(!destinationFolder.mkpath(destinationInfo.absolutePath()))
{
if(!destinationFolder.exists(destinationInfo.absolutePath()))
{
/// \todo do real folder error here
errorString_internal="mkpath error on destination";
ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,QStringLiteral("[")+QString::number(id)+QStringLiteral("] ")+QStringLiteral("Unable create the folder: %1, error: %2")
.arg(destinationInfo.absolutePath())
.arg(errorString_internal));
emit error();
#ifdef ULTRACOPIER_PLUGIN_DEBUG
stat=Idle;
#endif
mkpathTransfer->release();
return false;
}
}
}
mkpathTransfer->release();
}
ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] after the mkpath"));
if(stopIt)
{
ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] close because stopIt is at true"));
emit closed();
return false;
}
//try open it
QIODevice::OpenMode flags=QIODevice::ReadWrite;
if(!buffer)
flags|=QIODevice::Unbuffered;
{
QMutexLocker lock_mutex(&writeFileListMutex);
if(writeFileList.count(file.fileName(),this)==0)
{
writeFileList.insert(file.fileName(),this);
if(writeFileList.count(file.fileName())>1)
{
ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,QStringLiteral("[")+QString::number(id)+QStringLiteral("] in waiting because same file is found"));
return false;
}
}
}
bool fileWasExists=file.exists();
if(file.open(flags))
{
ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,QStringLiteral("[")+QString::number(id)+QStringLiteral("] after the open"));
//.........这里部分代码省略.........
示例3: isRelative
/*!
\overload
Sets the file that the QFileInfo provides information about to \a
file in directory \a dir.
If \a file includes a relative path, the QFileInfo will also
have a relative path.
\sa isRelative()
*/
void QFileInfo::setFile(const QDir &dir, const QString &file)
{
setFile(dir.filePath(file));
}
示例4: initSettings
//Init settings
void initSettings()
{
//open file
#ifdef Q_OS_WIN
QSettings settings("HKEY_CURRENT_USER\\Software\\moonplayer", QSettings::NativeFormat);
#else
QDir dir = QDir::home();
if (!dir.cd(".moonplayer"))
{
dir.mkdir(".moonplayer");
dir.cd(".moonplayer");
}
if (!dir.exists("plugins"))
dir.mkdir("plugins");
if (!dir.exists("skins"))
dir.mkdir("skins");
QSettings settings(QDir::homePath() + "/.config/moonplayer.ini", QSettings::IniFormat);
#endif
//read settings
#ifdef Q_OS_WIN
if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA)
vout = settings.value("Video/out", "direct3d").toString();
else
vout = settings.value("Video/out", "directx").toString();
#else
vout = settings.value("Video/out", "xv").toString();
path = "/usr/share/moonplayer";
#endif
framedrop = settings.value("Video/framedrop", true).toBool();
doubleBuffer = settings.value("Video/double", true).toBool();
fixLastFrame = settings.value("Video/fixlastframe", false).toBool();
ffodivxvdpau = settings.value("Video/ffodivxvdpau", true).toBool();
aout = settings.value("Audio/out", "auto").toString();
softvol = settings.value("Audio/softvol", false).toBool();
volume = settings.value("Audio/volume", 10).toInt();
currentSkin = settings.value("Player/current_skin", 0).toInt();
autoResize = settings.value("Player/auto_resize", true).toBool();
enableScreenshot = settings.value("Player/screenshot", true).toBool();
rememberUnfinished = settings.value("Player/remember_unfinished", true).toBool();
proxy = settings.value("Net/proxy").toString();
port = settings.value("Net/port").toInt();
cacheSize = settings.value("Net/cache_size", 4096).toInt();
cacheMin = settings.value("Net/cache_min", 50).toInt();
maxTasks = settings.value("Net/max_tasks", 3).toInt();
downloadDir = settings.value("Net/download_dir", QDir::homePath()).toString();
quality = (Quality) settings.value("Plugins/quality", (int) SUPER).toInt();
autoCombine = settings.value("Plugins/auto_combine", false).toBool();
autoCloseWindow = settings.value("Plugins/auto_close_window", true).toBool();
danmakuAlpha = settings.value("Danmaku/alpha", 0.9).toDouble();
danmakuFont = settings.value("Danmaku/font", "").toString();
danmakuSize = settings.value("Danmaku/size", 0).toInt();
durationScrolling = settings.value("Danmaku/dm", 0).toInt();
durationStill = settings.value("Danmaku/ds", 6).toInt();
//init proxy
if (proxy.isEmpty())
access_manager->setProxy(QNetworkProxy(QNetworkProxy::NoProxy));
else
access_manager->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, proxy, port));
//init skins
QDir skinDir(path);
skinDir.cd("skins");
skinList = skinDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name);
#ifdef Q_OS_LINUX
dir.cd("skins");
skinList.append(dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Name));
#endif
if (currentSkin >= skinList.size())
currentSkin = 0;
}
示例5: main
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//Command line arguments
TCLAP::CmdLine cmd("GOBLET (c) 2012, International Livestock Research Institute (ILRI) \n Developed by Carlos Quiros ([email protected])", ' ', "1.0 (Beta 1)");
//Required arguments
TCLAP::ValueArg<std::string> databaseArg("d","database","Database name",true,"","string");
TCLAP::ValueArg<std::string> datasetArg("t","dataset","Dataset name",true,"","string");
TCLAP::ValueArg<std::string> classArg("c","classdefinition","Class definition: 'ClassNumber:valueFrom ValueTo,ClassNumber:valueFrom ValueTo,...'",true,"","string");
//Non required arguments
TCLAP::ValueArg<std::string> pathArg("a","path","Path to database. Default .",false,".","string");
TCLAP::ValueArg<std::string> hostArg("H","host","Connect to host. Default localhost",false,"localhost","string");
TCLAP::ValueArg<std::string> portArg("P","port","Port number to use. Default 3306",false,"3306","string");
TCLAP::ValueArg<std::string> userArg("u","user","User. Default empty",false,"","string");
TCLAP::ValueArg<std::string> passArg("p","password","Passwork. Default no password",false,"","string");
TCLAP::ValueArg<std::string> extentArg("e","extent","Extent: '(upperLeft degrees lat,log) (lowerRight degrees lat,log)'",false,"","string");
TCLAP::ValueArg<std::string> shpConstraintArg("S","constraintbyshapes","Constraint classification using shapes: ShapeDataSet:shapeID,ShapeID,....",false,"","string");
TCLAP::ValueArg<std::string> defValArg("v","defaultvalue","Default value 0",false,"0","string");
//Switches
TCLAP::SwitchArg remoteSwitch("r","remote","Connect to remote host", cmd, false);
cmd.add(databaseArg);
cmd.add(datasetArg);
cmd.add(classArg);
cmd.add(extentArg);
cmd.add(shpConstraintArg);
cmd.add(pathArg);
cmd.add(hostArg);
cmd.add(portArg);
cmd.add(userArg);
cmd.add(passArg);
cmd.add(defValArg);
//Parsing the command lines
cmd.parse( argc, argv );
//Getting the variables from the command
bool remote = remoteSwitch.getValue();
QString path = QString::fromUtf8(pathArg.getValue().c_str());
QString dbName = QString::fromUtf8(databaseArg.getValue().c_str());
QString host = QString::fromUtf8(hostArg.getValue().c_str());
QString port = QString::fromUtf8(portArg.getValue().c_str());
QString userName = QString::fromUtf8(userArg.getValue().c_str());
QString password = QString::fromUtf8(passArg.getValue().c_str());
QString tableName = QString::fromUtf8(datasetArg.getValue().c_str());
QString classDef = QString::fromUtf8(classArg.getValue().c_str());
QString extent = QString::fromUtf8(extentArg.getValue().c_str());
QString shapes = QString::fromUtf8(shpConstraintArg.getValue().c_str());
QString defvalue = QString::fromUtf8(defValArg.getValue().c_str());
myDBConn con;
QSqlDatabase mydb;
if (!remote)
{
QDir dir;
dir.setPath(path);
if (con.connectToDB(dir.absolutePath()) == 1)
{
if (!dir.cd(dbName))
{
gbtLog(QObject::tr("The database does not exists"));
con.closeConnection();
return 1;
}
mydb = QSqlDatabase::addDatabase(con.getDriver(),"connection1");
}
}
else
{
mydb = QSqlDatabase::addDatabase("QMYSQL","connection1");
mydb.setHostName(host);
mydb.setPort(port.toInt());
if (!userName.isEmpty())
mydb.setUserName(userName);
if (!password.isEmpty())
mydb.setPassword(password);
}
mydb.setDatabaseName(dbName);
if (!mydb.open())
{
gbtLog(QObject::tr("Cannot open database"));
con.closeConnection();
return 1;
}
else
{
QTime procTime;
procTime.start();
//We need to check if dataset is a grid
getClasses(classDef);
if (classes.count() ==0 )
{
gbtLog(QObject::tr("There are no classes!"));
mydb.close();
con.closeConnection();
//.........这里部分代码省略.........
示例6: remove
void FS::remove(const QDir &dir)
{
if (!QDir(dir).removeRecursively()) {
throw FileSystemException("Unable to remove " + dir.dirName());
}
}
示例7: qt_win_get_open_file_names
QStringList qt_win_get_open_file_names(const QFileDialogArgs &args,
QString *initialDirectory,
QString *selectedFilter)
{
QFileInfo fi;
QDir dir;
if (initialDirectory && initialDirectory->left(5) == QLatin1String("file:"))
initialDirectory->remove(0, 5);
fi = QFileInfo(*initialDirectory);
if (initialDirectory && !fi.isDir()) {
*initialDirectory = fi.absolutePath();
}
if (!fi.exists())
*initialDirectory = QDir::homePath();
DWORD selFilIdx = 0;
QStringList filterLst = qt_win_make_filters_list(args.filter);
int idx = 0;
if (selectedFilter) {
idx = filterLst.indexOf(*selectedFilter);
}
// Windows Vista (& above) allows users to search from file dialogs. If user selects
// multiple files belonging to different folders from these search results, the
// GetOpenFileName() will return only one folder name for all the files. To retrieve
// the correct path for all selected files, we have to use Common Item Dialog interfaces.
#ifndef Q_WS_WINCE
if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA && QSysInfo::WindowsVersion < QSysInfo::WV_NT_based)
return qt_win_CID_get_open_file_names(args, initialDirectory, filterLst, selectedFilter, idx);
#endif
QStringList result;
QDialog modal_widget;
modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true);
modal_widget.setParent(args.parent, Qt::Window);
QApplicationPrivate::enterModal(&modal_widget);
bool hideFiltersDetails = args.options & QFileDialog::HideNameFilterDetails;
OPENFILENAME* ofn = qt_win_make_OFN(args.parent, args.selection,
args.directory, args.caption,
qt_win_filter(args.filter, hideFiltersDetails),
QFileDialog::ExistingFiles,
args.options);
if (idx)
ofn->nFilterIndex = idx + 1;
if (GetOpenFileName(ofn)) {
QString fileOrDir = QString::fromWCharArray(ofn->lpstrFile);
selFilIdx = ofn->nFilterIndex;
int offset = fileOrDir.length() + 1;
if (ofn->lpstrFile[offset] == 0) {
// Only one file selected; has full path
fi.setFile(fileOrDir);
QString res = fi.absoluteFilePath();
if (!res.isEmpty())
result.append(res);
}
else {
// Several files selected; first string is path
dir.setPath(fileOrDir);
QString f;
while(!(f = QString::fromWCharArray(ofn->lpstrFile + offset)).isEmpty()) {
fi.setFile(dir, f);
QString res = fi.absoluteFilePath();
if (!res.isEmpty())
result.append(res);
offset += f.length() + 1;
}
}
}
qt_win_clean_up_OFN(&ofn);
QApplicationPrivate::leaveModal(&modal_widget);
qt_win_eatMouseMove();
if (!result.isEmpty()) {
*initialDirectory = fi.path(); // only save the path if there is a result
if (selectedFilter)
*selectedFilter = qt_win_selected_filter(args.filter, selFilIdx);
}
return result;
}
示例8: main
int main(int argc, char** argv)
{
ctkLogger::configure();
ctkLogger logger ( "org.commontk.dicom.DICOMRetieveApp" );
logger.setDebug();
if (argc < 9)
{
print_usage();
return EXIT_FAILURE;
}
QCoreApplication app(argc, argv);
QTextStream out(stdout);
QString StudyUID ( argv[1] );
QDir OutputDirectory ( argv[2] );
QString CallingAETitle ( argv[3] );
bool ok;
int CallingPort = QString ( argv[4] ).toInt ( &ok );
if ( !ok )
{
std::cerr << "Could not convert " << argv[4] << " to an integer for the callingPort" << std::endl;
print_usage();
return EXIT_FAILURE;
}
QString CalledAETitle ( argv[5] );
QString Host ( argv[6] );
int CalledPort = QString ( argv[7] ).toInt ( &ok );
if ( !ok )
{
std::cerr << "Could not convert " << argv[7] << " to an integer for the calledPoint" << std::endl;
print_usage();
return EXIT_FAILURE;
}
QString MoveDestinationAETitle ( argv[8] );
ctkDICOMRetrieve retrieve;
retrieve.setCallingAETitle ( CallingAETitle );
retrieve.setCallingPort ( CallingPort );
retrieve.setCalledAETitle ( CalledAETitle );
retrieve.setCalledPort ( CalledPort );
retrieve.setHost ( Host );
retrieve.setMoveDestinationAETitle ( MoveDestinationAETitle );
logger.info ( "StudyUID: " + StudyUID + "\n"
+ "OutputDirectory: " + OutputDirectory.absolutePath() + "\n"
+ "CallingAETitle: " + CallingAETitle + "\n"
+ "CallingPort: " + QString::number ( CallingPort ) + "\n"
+ "CalledAEtitle: " + CalledAETitle + "\n"
+ "Host: " + Host + "\n"
+ "CalledPort: " + QString::number ( CalledPort ) + "\n" );
logger.info ( "Starting to retrieve" );
try
{
retrieve.retrieveStudy ( StudyUID, OutputDirectory );
}
catch (std::exception e)
{
logger.error ( "Retrieve failed" );
return EXIT_FAILURE;
}
logger.info ( "Retrieve success" );
return EXIT_SUCCESS;
}
示例9: QMainWindow
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
// Creazione finestra
ui->setupUi(this);
mDialogSendIp = NULL;
mDialogText = NULL;
mDialogAbout = NULL;
mNetworkSession = NULL;
// Creazione menu'
mSendFileAction = new QAction("Send a file", this);
menuBar()->addAction(mSendFileAction);
connect(mSendFileAction, SIGNAL(triggered()), this, SLOT(selectFileToSend()));
mSendTextAction = new QAction("Send text message", this);
menuBar()->addAction(mSendTextAction);
connect(mSendTextAction, SIGNAL(triggered()), this, SLOT(showSendTextDialog()));
mSendToIPAction = new QAction("Send by IP", this);
menuBar()->addAction(mSendToIPAction);
connect(mSendToIPAction, SIGNAL(triggered()), this, SLOT(sendToIp()));
mCurrentIPAction = new QAction("Current IP address", this);
menuBar()->addAction(mCurrentIPAction);
connect(mCurrentIPAction, SIGNAL(triggered()), this, SLOT(showCurrentIP()));
mChangeFolderAction = new QAction("Change folder", this);
menuBar()->addAction(mChangeFolderAction);
connect(mChangeFolderAction, SIGNAL(triggered()), this, SLOT(changeFolder()));
mChangeNameAction = new QAction("Change user name", this);
menuBar()->addAction(mChangeNameAction);
connect(mChangeNameAction, SIGNAL(triggered()), this, SLOT(changeName()));
mAboutAction = new QAction("About Dukto", this);
menuBar()->addAction(mAboutAction);
connect(mAboutAction, SIGNAL(triggered()), this, SLOT(showAbout()));
// Progress dialog per operazioni
mProgressDialog = new QProgressDialog("", "", 0, 100);
mProgressDialog->setWindowModality(Qt::WindowModal);
// Connecting dialog
mConnectingDialog = new QProgressDialog("\nConnecting...", "", 0, 0);
mConnectingDialog->setCancelButton(NULL);
mConnectingDialog->setAutoClose(false);
mConnectingDialog->setMinimumDuration(0);
mConnectingDialog->setWindowModality(Qt::WindowModal);
// Percorso salvato
QSettings settings("msec.it", "Dukto");
QString path = settings.value("dukto/currentpath", "C:/Dukto").toString();
QDir d;
if (d.mkpath(path))
{
QDir::setCurrent(path);
ui->labelDest->setText("Folder: " + path.replace('/', "\\"));
}
// Percorso di default
else
{
path = "C:/Dukto";
d.mkpath(path);
QDir::setCurrent(path);
ui->labelDest->setText("Folder: " + path.replace('/', "\\"));
settings.setValue("dukto/currentpath", path);
}
// Inizialmente nascondo la lista
ui->listWidget->setVisible(false);
}
示例10: QString
void GrabberSettings::Load(void)
{
QDir TVScriptPath = QString("%1metadata/Television/").arg(GetShareDir());
QStringList TVScripts = TVScriptPath.entryList(QDir::Files);
QDir MovieScriptPath = QString("%1metadata/Movie/").arg(GetShareDir());
QStringList MovieScripts = MovieScriptPath.entryList(QDir::Files);
QDir GameScriptPath = QString("%1metadata/Game/").arg(GetShareDir());
QStringList GameScripts = GameScriptPath.entryList(QDir::Files);
if (MovieScripts.count())
{
for (QStringList::const_iterator i = MovieScripts.begin();
i != MovieScripts.end(); ++i)
{
QString commandline = QString("%1/%2")
.arg(MovieScriptPath.path()).arg(*i);
MythSystemLegacy grabber(commandline, QStringList() << "-v", kMSRunShell | kMSStdOut);
grabber.Run();
grabber.Wait();
QByteArray result = grabber.ReadAll();
if (!result.isEmpty())
{
QDomDocument doc;
doc.setContent(result, true);
QDomElement root = doc.documentElement();
if (!root.isNull())
{
MetaGrabberScript *script = ParseGrabberVersion(root);
if (!script->GetName().isEmpty())
m_movieGrabberList.append(script);
}
}
}
}
if (TVScripts.count())
{
for (QStringList::const_iterator i = TVScripts.end() - 1;
i != TVScripts.begin() - 1; --i)
{
QString commandline = QString("%1/%2")
.arg(TVScriptPath.path()).arg(*i);
MythSystemLegacy grabber(commandline, QStringList() << "-v", kMSRunShell | kMSStdOut);
grabber.Run();
grabber.Wait();
QByteArray result = grabber.ReadAll();
if (!result.isEmpty())
{
QDomDocument doc;
doc.setContent(result, true);
QDomElement root = doc.documentElement();
if (!root.isNull())
{
MetaGrabberScript *script = ParseGrabberVersion(root);
if (!script->GetName().isEmpty())
m_tvGrabberList.append(script);
}
}
}
}
if (GameScripts.count())
{
for (QStringList::const_iterator i = GameScripts.end() - 1;
i != GameScripts.begin() - 1; --i)
{
QString commandline = QString("%1/%2")
.arg(GameScriptPath.path()).arg(*i);
MythSystemLegacy grabber(commandline, QStringList() << "-v", kMSRunShell | kMSStdOut);
grabber.Run();
grabber.Wait();
QByteArray result = grabber.ReadAll();
if (!result.isEmpty())
{
QDomDocument doc;
doc.setContent(result, true);
QDomElement root = doc.documentElement();
if (!root.isNull())
{
MetaGrabberScript *script = ParseGrabberVersion(root);
if (!script->GetName().isEmpty())
m_gameGrabberList.append(script);
}
}
}
}
}
示例11: strcpy
void
pfmPage::slotPFMFileEdit (const QString &string)
{
pfm_def->name = string;
if (!pfm_def->name.endsWith (".pfm")) pfm_def->name += ".pfm";
mBinSize->setEnabled (TRUE);
gBinSize->setEnabled (TRUE);
minDepth->setEnabled (TRUE);
maxDepth->setEnabled (TRUE);
precision->setEnabled (TRUE);
area_browse->setEnabled (TRUE);
area_map->setEnabled (TRUE);
area_pfm->setEnabled (TRUE);
area_nsew->setEnabled (TRUE);
// Watch out for directory names that might be typed in.
if (QFileInfo (string).isDir ()) return;
FILE *fp;
NV_INT32 hnd;
PFM_OPEN_ARGS open_args;
strcpy (open_args.list_path, pfm_def->name.toAscii ());
// Try to open the file. If it exists we will not allow the user to change the bin size,
// depth precision, etc.
pfm_def->existing = NVFalse;
if ((fp = fopen (open_args.list_path, "r")) != NULL)
{
fclose (fp);
open_args.checkpoint = 0;
if ((hnd = open_existing_pfm_file (&open_args)) >= 0)
{
NV_CHAR file[512];
get_target_file (hnd, open_args.list_path, file);
feature_edit->setText (QString (file));
get_mosaic_file (hnd, open_args.list_path, file);
mosaic_edit->setText (QString (file));
close_pfm_file (hnd);
area_edit->setText (tr ("Defined in PFM structure"));
mBinSize->setEnabled (FALSE);
gBinSize->setEnabled (FALSE);
minDepth->setEnabled (FALSE);
maxDepth->setEnabled (FALSE);
precision->setEnabled (FALSE);
area_browse->setEnabled (FALSE);
area_map->setEnabled (FALSE);
area_pfm->setEnabled (FALSE);
area_nsew->setEnabled (FALSE);
pfm_def->existing = NVTrue;
}
else
{
QMessageBox::warning (this, tr ("Open PFM Structure"),
tr ("The file ") + QDir::toNativeSeparators (QString (open_args.list_path)) +
tr (" is not a PFM structure or there was an error reading the file.") +
tr (" The error message returned was:\n\n") +
QString (pfm_error_str (pfm_error)));
if (pfm_error == CHECKPOINT_FILE_EXISTS_ERROR)
{
fprintf (stderr, "\n\n%s\n", pfm_error_str (pfm_error));
exit (-1);
}
return;
}
}
else
{
if (area_edit->text () == tr ("Defined in PFM structure")) area_edit->clear ();
feature_edit->setText ("NONE");
mosaic_edit->setText ("NONE");
QFileInfo fi = QFileInfo (pfm_def->name);
if (fi.isRelative ())
{
// Get the absolute path name
QDir dir;
pfm_def->name.prepend ("/");
//.........这里部分代码省略.........
示例12: kDebug
void FormatImporter::importBaskets()
{
kDebug() << "Import Baskets: Preparing...";
// Some preliminary preparations (create the destination folders and the basket tree file):
QDir dirPrep;
dirPrep.mkdir(Global::savesFolder());
dirPrep.mkdir(Global::basketsFolder());
QDomDocument document("basketTree");
QDomElement root = document.createElement("basketTree");
document.appendChild(root);
// First up, establish a list of every baskets, ensure the old order (if any), and count them.
QStringList baskets;
// Read the 0.5.0 baskets order:
QDomDocument *doc = XMLWork::openFile("container", Global::savesFolder() + "container.baskets");
if (doc != 0) {
QDomElement docElem = doc->documentElement();
QDomElement basketsElem = XMLWork::getElement(docElem, "baskets");
QDomNode n = basketsElem.firstChild();
while (!n.isNull()) {
QDomElement e = n.toElement();
if ((!e.isNull()) && e.tagName() == "basket")
baskets.append(e.text());
n = n.nextSibling();
}
}
// Then load the baskets that weren't loaded (import < 0.5.0 ones):
QDir dir(Global::savesFolder(), QString::null, QDir::Name | QDir::IgnoreCase, QDir::Dirs | QDir::NoSymLinks);
QStringList list = dir.entryList();
if (list.count() > 2) // Pass "." and ".."
for (QStringList::Iterator it = list.begin(); it != list.end(); ++it) // For each folder
if (*it != "." && *it != ".." && dir.exists(Global::savesFolder() + *it + "/.basket")) // If it can be a basket folder
if (! (baskets.contains((*it) + "/")) && baskets.contains(*it) ) // And if it is not already in the imported baskets list
baskets.append(*it);
kDebug() << "Import Baskets: Found " << baskets.count() << " baskets to import.";
// Import every baskets:
int i = 0;
for (QStringList::iterator it = baskets.begin(); it != baskets.end(); ++it) {
++i;
kDebug() << "Import Baskets: Importing basket " << i << " of " << baskets.count() << "...";
// Move the folder to the new repository (normal basket) or copy the folder (mirorred folder):
QString folderName = *it;
if (folderName.startsWith("/")) { // It was a folder mirror:
KMessageBox::information(0, i18n("<p>Folder mirroring is not possible anymore (see <a href='http://basket.kde.org/'>basket.kde.org</a> for more information).</p>"
"<p>The folder <b>%1</b> has been copied for the basket needs. You can either delete this folder or delete the basket, or use both. But remember that "
"modifying one will not modify the other anymore as they are now separate entities.</p>", folderName), i18n("Folder Mirror Import"),
"", KMessageBox::AllowLink);
// Also modify folderName to be only the folder name and not the full path anymore:
QString newFolderName = folderName;
if (newFolderName.endsWith("/"))
newFolderName = newFolderName.left(newFolderName.length() - 1);
newFolderName = newFolderName.mid(newFolderName.lastIndexOf('/') + 1);
newFolderName = Tools::fileNameForNewFile(newFolderName, Global::basketsFolder());
FormatImporter f;
f.copyFolder(folderName, Global::basketsFolder() + newFolderName);
folderName = newFolderName;
} else
dir.rename(Global::savesFolder() + folderName, Global::basketsFolder() + folderName); // Move the folder
// Import the basket structure file and get the properties (to add them in the tree basket-properties cache):
QDomElement properties = importBasket(folderName);
// Add it to the XML document:
QDomElement basketElement = document.createElement("basket");
root.appendChild(basketElement);
basketElement.setAttribute("folderName", folderName);
basketElement.appendChild(properties);
}
// Finalize (write to disk and delete now useless files):
kDebug() << "Import Baskets: Finalizing...";
QFile file(Global::basketsFolder() + "baskets.xml");
if (file.open(QIODevice::WriteOnly)) {
QTextStream stream(&file);
stream.setCodec("UTF-8");
QString xml = document.toString();
stream << "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
stream << xml;
file.close();
}
Tools::deleteRecursively(Global::savesFolder() + ".tmp");
dir.remove(Global::savesFolder() + "container.baskets");
kDebug() << "Import Baskets: Finished.";
}
示例13: dirTest
void dirTest(){
QDir dir = Backend::directoryOf(QStringLiteral("/translations"));
QVERIFY(dir.exists());
dir = Backend::directoryOf(QStringLiteral("/dirDoesNotExist"));
QVERIFY(!dir.exists());
}
示例14: confirmValidProjectName
/*
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();
}
示例15: YamlNode
bool HierarchyTreePlatformNode::Save(YamlNode* node, bool saveAll)
{
YamlNode* platform = new YamlNode(YamlNode::TYPE_MAP);
platform->Set(WIDTH_NODE, GetWidth());
platform->Set(HEIGHT_NODE, GetHeight());
MultiMap<String, YamlNode*> &platformsMap = node->AsMap();
platformsMap.erase(GetName().toStdString());
platformsMap.insert(std::pair<String, YamlNode*>(GetName().toStdString(), platform));
ActivatePlatform();
MultiMap<String, YamlNode*> &platformMap = platform->AsMap();
YamlNode* screens = new YamlNode(YamlNode::TYPE_ARRAY);
platformMap.erase(SCREENS_NODE);
platformMap.insert(std::pair<String, YamlNode*>(SCREENS_NODE, screens));
YamlNode* aggregators = new YamlNode(YamlNode::TYPE_MAP);
platformMap.erase(AGGREGATORS_NODE);
platformMap.insert(std::pair<String, YamlNode*>(AGGREGATORS_NODE, aggregators));
// Add the Localization info - specific for each Platform.
SaveLocalization(platform);
QString platformFolder = GetPlatformFolder();
QDir dir;
dir.mkpath(platformFolder);
bool result = true;
//save aggregators node before save screens
for (HIERARCHYTREENODESCONSTITER iter = GetChildNodes().begin();
iter != GetChildNodes().end();
++iter)
{
HierarchyTreeAggregatorNode* node = dynamic_cast<HierarchyTreeAggregatorNode*>(*iter);
if (!node)
continue;
QString path = QString(SCREEN_PATH).arg(platformFolder).arg(node->GetName());
MultiMap<String, YamlNode*> &aggregatorsMap = aggregators->AsMap();
YamlNode* aggregator = new YamlNode(YamlNode::TYPE_MAP);
result &= node->Save(aggregator, path, saveAll);
aggregatorsMap.erase(node->GetName().toStdString());
aggregatorsMap.insert(std::pair<String, YamlNode*>(node->GetName().toStdString(), aggregator));
}
for (HIERARCHYTREENODESCONSTITER iter = GetChildNodes().begin();
iter != GetChildNodes().end();
++iter)
{
HierarchyTreeAggregatorNode* node = dynamic_cast<HierarchyTreeAggregatorNode*>(*iter);
if (node)
continue; //skip aggregators
HierarchyTreeScreenNode* screenNode = dynamic_cast<HierarchyTreeScreenNode*>(*iter);
if (!screenNode)
continue;
QString screenPath = QString(SCREEN_PATH).arg(platformFolder).arg(screenNode->GetName());
result &= screenNode->Save(screenPath, saveAll);
screens->AddValueToArray(screenNode->GetName().toStdString());
}
return result;
}