void PDF::slotPrintButton() { QDir monRepertoire; bool firstpage = true; SeriesInfos.SetChapter(ui->StartChap->value()); monRepertoire.setPath(SeriesInfos.GetChapterFolder()); if (monRepertoire.exists()) { QPdfWriter pdfWriter(SeriesInfos.GetSeriesFolder() + "/" + SeriesInfos.GetSeriesName() + " Tome " + SeriesInfos.GetVolume() + ".pdf"); pdfWriter.setPageSize(QPagedPaintDevice::A4); const qreal horizontalMarginMM = 10.0; // 10 mm margin on each side const qreal verticalMarginMM = 10.0; QPagedPaintDevice::Margins margins; margins.left = margins.right = horizontalMarginMM; margins.top = margins.bottom = verticalMarginMM; pdfWriter.setMargins(margins); QPixmap pixmap; QPainter painter; while ((monRepertoire.exists()) && (ui->EndChap->value() >= SeriesInfos.GetChapter().toInt())) { QStringList listOfFiles = monRepertoire.entryList(); for (int i = 2; i < listOfFiles.size(); i++) { QString imagePath = monRepertoire.absolutePath() + "/" + listOfFiles.at(i); if ((imagePath.contains("jpg")) || (imagePath.contains("png"))) { pixmap.load(imagePath); if (pixmap.width() > pixmap.height()) { if (ui->Vertical->isChecked()) { if (firstpage == false) { pdfWriter.newPage(); } else { painter.begin(&pdfWriter); } QTransform t; pixmap = pixmap.transformed(t.rotate(90),Qt::SmoothTransformation); painter.drawPixmap(QRectF(0, 0, pdfWriter.width(), pdfWriter.height()), pixmap, QRectF(0, 0, pixmap.width(), pixmap.height())); } else { pdfWriter.setPageOrientation(QPageLayout::Landscape); if (firstpage == false) { pdfWriter.newPage(); } else { painter.begin(&pdfWriter); } painter.drawPixmap(QRectF(0, 0, pdfWriter.width(), pdfWriter.height()), pixmap, QRectF(0, 0, pixmap.width(), pixmap.height())); pdfWriter.setPageOrientation(QPageLayout::Portrait); } } else { if (firstpage == false) { pdfWriter.newPage(); } else { painter.begin(&pdfWriter); } painter.drawPixmap(QRectF(0, 0, pdfWriter.width(), pdfWriter.height()), pixmap, QRectF(0, 0, pixmap.width(), pixmap.height())); } firstpage = false; } } SeriesInfos.UpdateChapterVal(); monRepertoire.setPath(SeriesInfos.GetChapterFolder()); } emit UpdateVolume(CurrentIdx); painter.end(); } this->close(); }
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice, QString fname, QString currentPath) { if (!currentPath.isEmpty() && !currentPath.endsWith(QLatin1String("/"))) currentPath += '/'; QDomDocument document; { QString errorMsg; int errorLine, errorColumn; if(!document.setContent(inputDevice, &errorMsg, &errorLine, &errorColumn)) { fprintf(stderr, "pyrcc4 Parse Error:%s:%d:%d [%s]\n", fname.toLatin1().constData(), errorLine, errorColumn, errorMsg.toLatin1().constData()); return false; } } for(QDomElement root = document.firstChild().toElement(); !root.isNull(); root = root.nextSibling().toElement()) { if (root.tagName() != QLatin1String(TAG_RCC)) continue; for (QDomElement child = root.firstChild().toElement(); !child.isNull(); child = child.nextSibling().toElement()) { if (child.tagName() == QLatin1String(TAG_RESOURCE)) { QLocale lang = QLocale::c(); if (child.hasAttribute(ATTRIBUTE_LANG)) lang = QLocale(child.attribute(ATTRIBUTE_LANG)); QString prefix; if (child.hasAttribute(ATTRIBUTE_PREFIX)) prefix = child.attribute(ATTRIBUTE_PREFIX); if (!prefix.startsWith(QLatin1String("/"))) prefix.prepend('/'); if (!prefix.endsWith(QLatin1String("/"))) prefix += '/'; for (QDomNode res = child.firstChild(); !res.isNull(); res = res.nextSibling()) { if (res.toElement().tagName() == QLatin1String(TAG_FILE)) { QString fileName(res.firstChild().toText().data()); if (fileName.isEmpty()) fprintf(stderr, "Warning: Null node in XML\n"); QString alias; if (res.toElement().hasAttribute(ATTRIBUTE_ALIAS)) alias = res.toElement().attribute(ATTRIBUTE_ALIAS); else alias = fileName; int compressLevel = mCompressLevel; if (res.toElement().hasAttribute(ATTRIBUTE_COMPRESS)) compressLevel = res.toElement().attribute(ATTRIBUTE_COMPRESS).toInt(); int compressThreshold = mCompressThreshold; if (res.toElement().hasAttribute(ATTRIBUTE_THRESHOLD)) compressThreshold = res.toElement().attribute(ATTRIBUTE_THRESHOLD).toInt(); // Special case for -no-compress. Overrides all other settings. if (mCompressLevel == -2) compressLevel = 0; alias = QDir::cleanPath(alias); while (alias.startsWith("../")) alias.remove(0, 3); alias = prefix + alias; QFileInfo file(currentPath + fileName); if (!file.exists()) { fprintf(stderr, "Cannot find file: %s\n", fileName.toLatin1().constData()); continue ; } else if (file.isFile()) { addFile(alias, RCCFileInfo(alias.section('/', -1), file, lang, RCCFileInfo::NoFlags, compressLevel, compressThreshold)); } else { QDir dir; if(file.isDir()) { dir.setPath(file.filePath()); } else { dir.setPath(file.path()); dir.setNameFilters(QStringList(file.fileName())); if(alias.endsWith(file.fileName())) alias = alias.left(alias.length()-file.fileName().length()); } if (!alias.endsWith(QLatin1String("/"))) alias += '/'; QFileInfoList children = dir.entryInfoList(); for(int i = 0; i < children.size(); ++i) { if(children[i].fileName() != QLatin1String(".") && children[i].fileName() != QLatin1String("..")) addFile(alias + children[i].fileName(), RCCFileInfo(children[i].fileName(), children[i], lang, RCCFileInfo::NoFlags, compressLevel, compressThreshold)); } } } } } } } if(this->root == 0) { fprintf(stderr, "No resources in resource description.\n"); return false; } return true; }
void IconView::HandleImport(void) { QFileInfo path; QDir importdir; // Makes import directory samba/windows friendly (no colon) QString idirname = m_currDir + "/" + MythDate::current().toString("yyyy-MM-dd_hh-mm-ss"); importdir.mkdir(idirname); importdir.setPath(idirname); for (QStringList::const_iterator it = m_paths.begin(); it != m_paths.end(); ++it) { path.setFile(*it); if (path.isDir() && path.isReadable()) { ImportFromDir(*it, importdir.absolutePath()); } else if (path.isFile() && path.isExecutable()) { if (m_allowImportScripts) { QString cmd = *it + " " + importdir.absolutePath(); MythScreenStack *popupStack = GetMythMainWindow()->GetStack("popup stack"); MythUIBusyDialog *busy = new MythUIBusyDialog(tr("Importing images from camera. Please wait..."), popupStack, "importbusydialog"); if (busy->Create()) { popupStack->AddScreen(busy, false); } else { delete busy; busy = NULL; } ImportThread *import = new ImportThread(cmd); import->start(); while (!import->isFinished()) { usleep(500); qApp->processEvents(); } delete import; if (busy) busy->Close(); } else { ShowOkPopup(tr("Found an import script (%1) but running them has been disabled in the settings!") .arg(*it)); importdir.rmdir(importdir.absolutePath()); return; } } else { LOG(VB_GENERAL, LOG_ERR, LOC + QString("Could not read or execute %1").arg(*it)); ShowOkPopup(tr("Could not read or execute %1").arg(*it)); } } importdir.setFilter(QDir::Files | QDir::Readable | QDir::NoDotAndDotDot); importdir.refresh(); if (importdir.count() == 0) { ShowOkPopup(tr("Nothing found to import")); importdir.rmdir(importdir.absolutePath()); return; } else ShowOkPopup(tr("Found %n image(s)", "", importdir.count())); LoadDirectory(m_currDir); }
QStringList Q3FileDialog::winGetOpenFileNames(const QString &filter, QString* initialDirectory, QWidget *parent, const char* /*name*/, const QString& caption, QString* selectedFilter) { QStringList result; QFileInfo fi; QDir dir; QString isel; if (initialDirectory && initialDirectory->left(5) == QLatin1String("file:")) initialDirectory->remove(0, 5); fi = QFileInfo(*initialDirectory); if (initialDirectory && !fi.isDir()) { *initialDirectory = fi.dirPath(true); isel = fi.fileName(); } if (!fi.exists()) *initialDirectory = QDir::homeDirPath(); QString title = caption; if (title.isNull()) title = tr("Open "); DWORD selFilIdx = 0; int idx = 0; if (selectedFilter && !selectedFilter->isEmpty()) { QStringList filterLst = makeFiltersList(filter); idx = filterLst.findIndex(*selectedFilter); } if (parent) { QEvent e(QEvent::WindowBlocked); QApplication::sendEvent(parent, &e); QApplicationPrivate::enterModal(parent); } OPENFILENAME* ofn = makeOFN(parent, isel, *initialDirectory, title, winFilter(filter), ExistingFiles); 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.absFilePath(); 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.absFilePath(); if (!res.isEmpty()) result.append(res); offset += f.length() + 1; } } } cleanUpOFN(&ofn); if (parent) { QApplicationPrivate::leaveModal(parent); QEvent e(QEvent::WindowUnblocked); QApplication::sendEvent(parent, &e); } if (!result.isEmpty()) { *initialDirectory = fi.dirPath(); // only save the path if there is a result if (selectedFilter) *selectedFilter = selFilter(filter, selFilIdx); } return result; }
bool ParseOptions(__DIE_OPTIONS *pOptions,QStringList *pListArguments,QStringList *pListFiles) { QString sParam; QString sTemp; QStringList listTemp1; for(int i=1; i<pListArguments->count(); i++) { sParam=pListArguments->at(i); if(sParam.toLower().contains("-showerrors:")) { sTemp=sParam.section(":",1,1).toLower(); if(sTemp=="yes") { pOptions->bShowErrors=true; } else if(sTemp=="no") { pOptions->bShowErrors=false; } else { printf("Invalid parameter: %s",sParam.toAscii().data()); return false; } } else if(sParam.toLower().contains("-showoptions:")) { sTemp=sParam.section(":",1,1).toLower(); if(sTemp=="yes") { pOptions->bShowOptions=true; } else if(sTemp=="no") { pOptions->bShowOptions=false; } else { printf("Invalid parameter: %s",sParam.toAscii().data()); return false; } } else if(sParam.toLower().contains("-showversion:")) { sTemp=sParam.section(":",1,1).toLower(); if(sTemp=="yes") { pOptions->bShowVersion=true; } else if(sTemp=="no") { pOptions->bShowVersion=false; } else { printf("Invalid parameter: %s",sParam.toAscii().data()); return false; } } else if(sParam.toLower().contains("-subfolders:")) { sTemp=sParam.section(":",1,1).toLower(); if(sTemp=="yes") { pOptions->bScanSubfolders=true; } else if(sTemp=="no") { pOptions->bScanSubfolders=false; } else { printf("Invalid parameter: %s",sParam.toAscii().data()); return false; } } else if(sParam.toLower().contains("-showentropy:")) { sTemp=sParam.section(":",1,1).toLower(); if(sTemp=="yes") { pOptions->bShowEntropy=true; } else if(sTemp=="no") { pOptions->bShowEntropy=false; } else { printf("Invalid parameter: %s",sParam.toAscii().data()); return false; } } else if(sParam.toLower().contains("-singlelineoutput:")) { sTemp=sParam.section(":",1,1).toLower(); if(sTemp=="yes") { pOptions->bSingleLineOutput=true; } else if(sTemp=="no") { pOptions->bSingleLineOutput=false; } else { printf("Invalid parameter %s",sParam.toAscii().data()); return false; } } else if(sParam.toLower().contains("-showfileformatonce:")) { sTemp=sParam.section(":",1,1).toLower(); if(sTemp=="yes") { pOptions->bShowFileFormatOnce=true; } else if(sTemp=="no") { pOptions->bShowFileFormatOnce=false; } else { printf("Invalid parameter: %s",sParam.toAscii().data()); return false; } } else if(sParam.toLower().contains("-fullscan:")) { sTemp=sParam.section(":",1,1).toLower(); if(sTemp=="yes") { pOptions->bFullScan=true; } else if(sTemp=="no") { pOptions->bFullScan=false; } else { printf("Invalid parameter: %s",sParam.toAscii().data()); return false; } } else if(sParam.toLower().contains("-database:")) { sTemp=sParam.section(":",1,-1).toLower(); QDir _dir; if(_dir.exists(Utils::convertPath(sTemp))) { pOptions->sDataBasePath=sTemp; } else { printf("Invalid database name: %s",sTemp.toAscii().data()); return false; } } else { listTemp1.append(sParam); } } if(listTemp1.count()==0) { printf("No file specified"); return false; } QFile file; QDir dir; // QDir dir2; // int nNumberOfSlash=0; // QStringList listTemp2; // QFileInfoList fil; // QString sBaseName; for(int i=0; i<listTemp1.count(); i++) { file.setFileName(listTemp1.at(i)); dir.setPath(listTemp1.at(i)); if(listTemp1.at(i)==".") { continue; } else if(listTemp1.at(i)=="..") { continue; } else if(dir.exists()) { FindFiles(listTemp1.at(i),pListFiles,pOptions->bScanSubfolders); } else if(file.exists()) { pListFiles->append(listTemp1.at(i)); } else if(listTemp1.at(i).contains("*")||listTemp1.at(i).contains("?")) { QStringList nameFilters; nameFilters.append(listTemp1.at(i)); QDir _dir; QFileInfoList listFI=_dir.entryInfoList(nameFilters); for(int j=0; j<listFI.count(); j++) { if(listFI.at(j).isDir()) { FindFiles(listFI.at(j).absoluteFilePath(),pListFiles,pOptions->bScanSubfolders); } else if(listFI.at(j).isFile()) { pListFiles->append(listFI.at(j).absoluteFilePath()); } } } else { printf("Invalid parameter or file name: %s",listTemp1.at(i).toAscii().data()); return false; } // if(listTemp1.at(i).contains("*")||listTemp1.at(i).contains("?")) // { // sTemp=listTemp1.at(i); // sTemp.replace("/",QDir::separator()); // sTemp.replace("\\",QDir::separator()); // nNumberOfSlash=sTemp.count(QDir::separator()); // if(nNumberOfSlash) // { // dir2.setPath(sTemp.section(QDir::separator(),0,nNumberOfSlash-1)+QDir::separator()); // sTemp=sTemp.section(QDir::separator(),nNumberOfSlash); // } // fil=dir2.entryInfoList(QStringList()<<sTemp); // for(int j=0;j<fil.count();j++) // { // sBaseName=fil.at(j).baseName(); // if((sBaseName!=".")&&(sBaseName!="..")&&(sBaseName!="")) // { // listTemp2.append(fil.at(j).absoluteFilePath()); // } // } // } // else // { // listTemp2.append(listTemp1.at(i)); // } } // QDir _dir; // QFileInfoList listFI=_dir.entryInfoList(nameFilters); //// listAnother2.append(dir2.entryList(listFilters)); // for(int i=0;i<listTemp2.count();i++) // { // file.setFileName(listTemp2.at(i)); // dir.setPath(listTemp2.at(i)); // if(listTemp2.at(i)==".") // { // continue; // } // else if(listTemp2.at(i)=="..") // { // continue; // } // else if(dir.exists()) // { // FindFiles(listTemp2.at(i),pListFiles,pOptions->bScanSubfolders); // } // else if(file.exists()) // { // pListFiles->append(listTemp2.at(i)); // } // else // { // printf("Invalid parameter or file name: %s",listTemp2.at(i).toAscii().data()); // return false; // } // } return true; }
void MythUIFileBrowser::updateLocalFileList() { QDir d; d.setPath(m_subDirectory); d.setNameFilters(m_nameFilter); d.setFilter(m_typeFilter); d.setSorting(QDir::Name | QDir::DirsFirst | QDir::IgnoreCase); if (!d.exists()) { VERBOSE(VB_IMPORTANT, "MythUIFileBrowser: current directory does not exist!"); m_locationEdit->SetText("/"); m_subDirectory = "/"; d.setPath("/"); } QFileInfoList list = d.entryInfoList(); bool showBackButton = false; if (list.isEmpty()) { MythUIButtonListItem* item = new MythUIButtonListItem(m_fileList, tr("Parent Directory")); item->DisplayState("upfolder", "nodetype"); } else { QFileInfoList::const_iterator it = list.begin(); const QFileInfo *fi; while (it != list.end()) { fi = &(*it); MFileInfo finfo(fi->filePath()); if (finfo.fileName() == ".") { ++it; continue; } QString displayName = finfo.fileName(); QString type; if (displayName == "..") { if (m_subDirectory.endsWith("/")) { ++it; continue; } displayName = tr("Parent"); type = "upfolder"; showBackButton = true; } else if (finfo.isDir()) { type = "folder"; } else if (finfo.isExecutable()) { type = "executable"; } else if (finfo.isFile()) { type = "file"; } MythUIButtonListItem* item = new MythUIButtonListItem(m_fileList, displayName, qVariantFromValue(finfo)); if (IsImage(finfo.suffix())) { item->SetImage(finfo.absoluteFilePath()); type = "image"; } item->SetText(FormatSize(finfo.size()), "filesize"); item->SetText(finfo.absoluteFilePath(), "fullpath"); item->DisplayState(type, "nodetype"); ++it; } } if (m_backButton) m_backButton->SetEnabled(showBackButton); m_locationEdit->SetText(m_subDirectory); }
QStringList ScPaths::hyphDirs() const { //dictionaryPaths QString macPortsPath("/opt/local/share/hunspell/"); QString finkPath("/sw/share/hunspell/"); QString osxLibreOfficePath("/Applications/LibreOffice.app/Contents/Resources/extensions"); QString osxUserLibreOfficePath(QDir::homePath()+"/Applications/LibreOffice.app/Contents/Resources/extensions"); QString linuxLocalPath("/usr/local/share/hunspell/"); QString linuxHunspellPath("/usr/share/hunspell/"); QString linuxMyspellPath("/usr/share/myspell/"); QString linuxHyphen1Path("/usr/share/hyphen/"); QString windowsLOPath("LibreOffice 3.5/share/extensions"); QDir d; QStringList hyphDirs; hyphDirs.append(userDictDir(ScPaths::Hyph, false)); hyphDirs.append(m_shareDir + "dicts/hyph/"); #ifdef Q_OS_MAC d.setPath(macPortsPath); if (d.exists()) hyphDirs.append(macPortsPath); d.setPath(finkPath); if (d.exists()) hyphDirs.append(finkPath); d.setPath(osxLibreOfficePath); if (d.exists()) { QStringList dictDirFilters("dict-*"); QStringList dictDirList(d.entryList(dictDirFilters, QDir::Dirs, QDir::Name)); QString dir; foreach (dir, dictDirList) hyphDirs.append(osxLibreOfficePath + "/" + dir + "/"); } d.setPath(osxUserLibreOfficePath); if (d.exists()) { QStringList dictDirFilters("dict-*"); QStringList dictDirList(d.entryList(dictDirFilters, QDir::Dirs, QDir::Name)); QString dir; foreach (dir, dictDirList) hyphDirs.append(osxUserLibreOfficePath + "/" + dir + "/"); } #elif defined(_WIN32) QString progFiles = windowsSpecialDir(CSIDL_PROGRAM_FILES); d.setPath(progFiles+windowsLOPath); if (d.exists()) { QStringList dictDirFilters("dict-*"); QStringList dictDirList(d.entryList(dictDirFilters, QDir::Dirs, QDir::Name)); QString dir; foreach (dir, dictDirList) hyphDirs.append(progFiles+windowsLOPath + "/" + dir + "/"); } #elif defined(Q_OS_LINUX) d.setPath(linuxHyphen1Path); if (d.exists()) hyphDirs.append(linuxHyphen1Path); d.setPath(linuxHunspellPath); if (d.exists()) hyphDirs.append(linuxHunspellPath); d.setPath(linuxMyspellPath); if (d.exists()) hyphDirs.append(linuxMyspellPath); d.setPath(linuxLocalPath); if (d.exists()) hyphDirs.append(linuxLocalPath); #endif return hyphDirs; }
SettingsDialog::SettingsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SettingsDialog) { ui->setupUi(this); // autodetect paths SteamConfig steam; QString baseInstall = steam["software/valve/steam/baseinstallfolder_1"]; QDir steamDir = QDir(baseInstall); // check if the path is empty before calling anything that acts on it // otherwise qdir complains if (baseInstall.isEmpty() || !steamDir.exists()) { // find the OS's application folder steamDir.setPath(QStandardPaths::standardLocations( QStandardPaths::ApplicationsLocation).first()); steamDir.setPath(steamDir.absoluteFilePath("Steam")); } if (!steamDir.exists()) { // find the home folder steamDir.setPath(QStandardPaths::standardLocations( QStandardPaths::GenericDataLocation).first()); steamDir.setPath(steamDir.absoluteFilePath("Steam")); } QString installDir = steam["software/valve/steam/apps/105600/installdir"]; QDir terrariaDir = QDir(installDir); if (installDir.isEmpty() || !terrariaDir.exists()) terrariaDir.setPath(steamDir.absoluteFilePath("SteamApps/common/Terraria")); defaultTextures = ""; if (terrariaDir.exists()) defaultTextures = terrariaDir.absoluteFilePath("Content/Images"); QDir worldDir = QDir( QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation) .first()); worldDir.setPath(worldDir.absoluteFilePath("My Games/Terraria/Worlds")); if (!worldDir.exists()) { // try linux path worldDir.setPath(QStandardPaths::standardLocations( QStandardPaths::GenericDataLocation).first()); worldDir.setPath(worldDir.absoluteFilePath("Terraria/Worlds")); } QStringList steamWorldDirs; QDir userDir = QDir(steamDir.absoluteFilePath("userdata")); for (const QFileInfo dir : userDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Dirs)) { QString steamWorldDir = QDir(dir.absoluteFilePath()). absoluteFilePath("105600/remote/worlds"); if (QDir(steamWorldDir).exists()) steamWorldDirs += steamWorldDir; } defaultSaves = QStringList(worldDir.absolutePath()) + steamWorldDirs; QSettings info; useDefSave = info.value("useDefSave", true).toBool(); customSave = info.value("customSave", defaultSaves[0]).toString(); useDefTex = info.value("useDefTex", true).toBool(); customTextures = info.value("customTextures", defaultTextures).toString(); }
void favoritos::findInPath() { QString xdgDataDirs; char *xdgDataDirsEnv = getenv("XDG_DATA_DIRS"); if(xdgDataDirsEnv != NULL) { xdgDataDirs = xdgDataDirsEnv; } else { xdgDataDirs = "/usr/local/share/:/usr/share/"; } QStringList folderSplit = xdgDataDirs.split(':'); QStringList folders; QDir dir; for(int countDirs = 0; countDirs < folderSplit.size(); ++countDirs) { if(folderSplit[countDirs].right(1) != "/") folderSplit[countDirs] = folderSplit[countDirs] + "/applications"; else folderSplit[countDirs] = folderSplit[countDirs] + "applications"; dir.setPath(folderSplit[countDirs]); if(dir.exists()) folders << folderSplit[countDirs]; } folders.removeDuplicates(); QList<QString> listFavApps; //Escritório listFavApps.append("libreoffice-writer.desktop"); listFavApps.append("libreoffice-calc.desktop"); listFavApps.append("libreoffice-impress.desktop"); listFavApps.append("libreoffice-draw.desktop"); /* if(plataforma == "xfce") { xfce4-settings-manager } */ //Gráficas listFavApps.append("gimp.desktop"); listFavApps.append("inkscape.desktop"); listFavApps.append("xsane.desktop"); //Internet listFavApps.append("google-chrome.desktop"); listFavApps.append("firefox.desktop"); listFavApps.append("brasero.desktop"); listFavApps.append("chromium-browser.desktop"); //Multimídia listFavApps.append("vlc.desktop"); listFavApps.append("vlc.desktop"); //xdg-open detectDE /* if(plataforma == "xfce") { xfce4-settings-manager } */ listFavApps.append("configurações"); listFavApps.append("calculadora"); listFavApps.append("gerenciador de arquivos"); listFavApps.append("terminal"); listFavApps.append("tocador de audio/vídeo"); listFavApps.append("k3b"); for(int countItens = 0; countItens <= 12; ++countItens) { foreach(const QString& path, folders) { QDir dir(path); QFileInfoList fileInfos = dir.entryInfoList(QStringList("*.desktop"), QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Files); foreach(const QFileInfo& fileInfo, fileInfos) { if(listFavApps.at(countItens) == fileInfo.fileName()) readFile(fileInfo.filePath()); } } }
//******************************************************************** // // Method: hide // Parameter: none, read input // create instance of Intermediary // // Purpose: use Intermediary to hide // //******************************************************************** void MainWindow::hide() { ui->saveLabel->clear(); //TODO plain to QString* //-> problem bei im->hide_1Bit QString plain; if(ui->textFromDocRadio->isChecked()) { QString plainPath = ui->textPathTextField->text(); QFile file(plainPath); file.open(QIODevice::ReadOnly | QIODevice::Text); QTextStream in(&file); plain = in.readAll(); file.close(); } else if(ui->textFromFieldRadio->isChecked()) plain = ui->textEdit->toPlainText(); //if(textFromFieldRadio) //encrypt if(ui->encryptCheckBox->isChecked()) { ui->saveLabel->setText("Encrypting..."); plain = *(encrypt(&plain)); ui->saveLabel->clear(); } QString oldPath = ui->picPathTextField->text(); im = new Intermediary(oldPath); if(ui->textFromDocRadio->isChecked() && ui->textPathTextField->text().endsWith(".png")) { im->setImage(ui->textPathTextField->text()); } else { im->setText(&plain,format); } QString savePath; ui->saveLabel->setText("Hiding..."); if(im->isReady_1Bit()) { savePath = QFileDialog::getSaveFileName(this, tr("Save File"), actDir.absolutePath(), tr("*.png *.jpg")); im->hide_1Bit(savePath); } else { int action = popupProblemDialog(); qDebug()<<action; while(action != CANCEL) { if( action == DENSITY) { int w = noiseWarningDialog(); if(im->isReady_3Bit() && w == 1) { savePath = QFileDialog::getSaveFileName(this, tr("Save File"), actDir.absolutePath(), tr("*.png *.jpg")); im->hide_3Bit(savePath); action = CANCEL; } else { action = popupProblemDialog(); if( action == DENSITY) { w = noiseWarningDialog(); if(im->isReady_3Bit() && w == 1) { savePath = QFileDialog::getSaveFileName(this, tr("Save File"), actDir.absolutePath(), tr("*.png *.jpg")); im->hide_6Bit(savePath); action = CANCEL; } else { notEnough(); action = CANCEL; } } } } else if(action == PICS) { apd = new AddPicDialog(im); apd->setActDir(actDir.absolutePath()); apd->exec(); action = CANCEL; } else if(action == NEWPIC) { im->images->remove(savePath); chosePicture(); im->addImage(ui->picPathTextField->text()); if(im->isReady_1Bit()) { savePath = QFileDialog::getSaveFileName(this, tr("Save File"), actDir.absolutePath(), tr("*.png *.jpg")); im->hide_1Bit(savePath); action = CANCEL; } else { action = popupProblemDialog(); } } else { action=CANCEL; } } } ui->saveLabel->clear(); ui->picPathTextField_2->clear(); if(!savePath.isEmpty()) { actDir.setPath(savePath); ui->picPathTextField_2->addItem(savePath); showSuccessfulHiding(savePath); } }
//******************************************************************** // // Method: find // Parameter: none, read input // create instance of Intermediary // // Purpose: use Intermediary to find, output found text or picture // //******************************************************************** void MainWindow::find() { QString path = ui->picPathTextField_2->item(0)->text(); im = new Intermediary(path); for(int index = 1; index < (ui->picPathTextField_2->count()); index++) { im->addImage(ui->picPathTextField_2->item(index)->text()); } if(im->imageOrTextHidden() == 1) //1 => text, 0 => picture { qDebug("Hidden text found."); QString* plain = im->getHiddenText(); //decrypt if(ui->decryptCheckBox->isChecked()) { plain = decrypt(plain); } if(ui->textToFieldRadio->isChecked()) { ui->picField->clear(); ui->textEdit_2->setText(*plain); } else if(ui->textToDocRadio->isChecked()) { QString newPath = QFileDialog::getSaveFileName( this, "Save Textfile", actDir.absolutePath(), "Text Files(*.txt)"); actDir.setPath(newPath); QFile fileOut(newPath); if (fileOut.open(QIODevice::WriteOnly | QIODevice::Text)) { QTextStream streamFileOut(&fileOut); streamFileOut.setCodec("UTF-8"); streamFileOut.setGenerateByteOrderMark(true); streamFileOut << *plain; streamFileOut.flush(); fileOut.close(); } } } else if(im->imageOrTextHidden() == 0) { qDebug("Hidden image found."); QImage* image; image = im->getHiddenImage(); if(ui->textToFieldRadio->isChecked()) { ui->textEdit_2->clear(); QPixmap img = QPixmap::fromImage(*image); if (img.height() > ui->picField->height() && img.width() > ui->picField->width()) { img = img.scaled(ui->picField->width(), ui->picField->height()); } else if(img.height() > ui->picField->height()) { img = img.scaledToHeight(ui->picField->height()); } else if(img.width() > ui->picField->width()) { img = img.scaledToWidth(ui->picField->width()); } ui->picField->setPixmap(img); } else { QString newPath = QFileDialog::getSaveFileName( this, "Save Image", actDir.absolutePath(), "Image Files(*.png)"); actDir.setPath(newPath); image->save(newPath,"PNG",100); } } ui->saveLabel->clear(); }
int PluginManager::load() { Logger::log("PluginManager::load(): Loading plugins modified since " + m_lastLoaded.toString(Qt::ISODate), Logger::LowVerbosity); int count = 0; QDir dir; foreach (const QString &path, PLUGIN_PATHS) { dir.setPath(path); foreach (const QFileInfo &info, dir.entryInfoList(QStringList() << "*.json", QDir::Files, QDir::Time)) { if (info.lastModified() > m_lastLoaded) { ServicePluginConfig *config = getConfigByFilePath(info.absoluteFilePath()); if (!config) { config = new ServicePluginConfig(this); if (config->load(info.absoluteFilePath())) { if (config->pluginType() == "qt") { QPluginLoader loader(config->pluginFilePath()); QObject *obj = loader.instance(); if (obj) { if (ServicePlugin *plugin = qobject_cast<ServicePlugin*>(obj)) { m_plugins << ServicePluginPair(config, plugin); ++count; Logger::log("PluginManager::load(). Qt Plugin loaded: " + config->id(), Logger::MediumVerbosity); } else { loader.unload(); Logger::log("PluginManager::load(). Error loading Qt plugin: " + config->id()); } } else { Logger::log("PluginManager::load(). Qt plugin is NULL: " + config->id()); } } else if (config->pluginType() == "js") { JavaScriptServicePlugin *js = new JavaScriptServicePlugin(config->id(), config->pluginFilePath(), this); m_plugins << ServicePluginPair(config, js); ++count; Logger::log("PluginManager::load(). JavaScript plugin loaded: " + config->id(), Logger::MediumVerbosity); } else { ExternalServicePlugin *ext = new ExternalServicePlugin(config->id(), config->pluginFilePath(), this); m_plugins << ServicePluginPair(config, ext); ++count; Logger::log("PluginManager::load(). External plugin loaded: " + config->id(), Logger::MediumVerbosity); } } else { delete config; } } } else { break; } } }
/**Duplicates selected macro * New file has same name as original but with "@" and 3-digit number appended * Begins with "@001" and increments until available name is found * "MyMacro.FCMacro" becomes "*****@*****.**" * "*****@*****.**" becomes "*****@*****.**" unless there is * no already existing "*****@*****.**" */ void DlgMacroExecuteImp::on_duplicateButton_clicked() { QDir dir; QTreeWidgetItem* item = 0; int index = tabMacroWidget->currentIndex(); if (index == 0) { //user-specific item = userMacroListBox->currentItem(); dir.setPath(this->macroPath); } if (!item){ return; } QString oldName = item->text(0); QFileInfo oldfi(dir, oldName); QFile oldfile(oldfi.absoluteFilePath()); QString completeSuffix = oldfi.completeSuffix(); //everything after the first "." QString baseName = oldfi.baseName(); //everything before first "." QString neutralSymbol = QString::fromStdString("@"); QString last3 = baseName.right(3); bool ok = true; //was conversion to int successful? int nLast3 = last3.toInt(&ok); last3 = QString::fromStdString("001"); //increment beginning with 001 no matter what if (ok ){ //last3 were all digits, so we strip them from the base name if (baseName.size()>3){ //if <= 3 leave be (e.g. 2.py becomes [email protected]) baseName = baseName.left(baseName.size()-3); //strip digits if (baseName.endsWith(neutralSymbol)){ baseName = baseName.left(baseName.size()-1); //trim the "@", will be added back later } } } //at this point baseName = the base name without any digits, e.g. "MyMacro" //neutralSymbol = "@" //last3 is a string representing 3 digits, always "001" at this time //completeSuffix = FCMacro or py or FCMacro.py or else suffix will become FCMacro below QString oldNameDigitized = baseName+neutralSymbol+last3+QString::fromStdString(".")+completeSuffix; QFileInfo fi(dir, oldNameDigitized); // increment until we find available name with smallest digits // test from "001" through "999", then give up and let user enter name of choice while (fi.exists()) { nLast3 = last3.toInt()+1; if (nLast3 >=1000){ //avoid infinite loop, 999 files will have to be enough break; } last3 = QString::number(nLast3); while (last3.size()<3){ last3.prepend(QString::fromStdString("0")); //pad 0's if needed } oldNameDigitized = baseName+neutralSymbol+last3+QString::fromStdString(".")+completeSuffix; fi = QFileInfo(dir,oldNameDigitized); } // give user a chance to pick a different name from digitized name suggested QString fn = QInputDialog::getText(this, tr("Duplicate Macro"), tr("Enter new name:"), QLineEdit::Normal, oldNameDigitized, 0); if (!fn.isEmpty() && fn != oldName) { QString suffix = QFileInfo(fn).suffix().toLower(); if (suffix != QLatin1String("fcmacro") && suffix != QLatin1String("py")){ fn += QLatin1String(".FCMacro"); } QFileInfo fi(dir, fn); // check again if new name exists in case user changed it if (fi.exists()) { QMessageBox::warning(this, tr("Existing file"), tr("'%1'\n already exists.").arg(fi.absoluteFilePath())); } else if (!oldfile.copy(fi.absoluteFilePath())) { QMessageBox::warning(this, tr("Duplicate Failed"), tr("Failed to duplicate to '%1'.\nPerhaps a file permission error?").arg(fi.absoluteFilePath())); } this->fillUpList(); //repopulate list to show new file } }
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> calculationArg("c","calculation","Calculation to perform. For example: 'sum(DatasetA),sum(DatasetB)' ",true,"","string"); TCLAP::ValueArg<std::string> shapeArg("s","shapefile","Shapefile to use",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> descArg("S","descriptions","Descriptions for the calculations separated by coma. Default value is the calculation string",false,"","string"); TCLAP::ValueArg<std::string> fieldArg("f","fields","Field of shapefile to include in result separared by coma. Default value all",false,"all","string"); TCLAP::ValueArg<std::string> whereArg("w","where","WHERE statement for shapefile",false,"","string"); TCLAP::ValueArg<std::string> groupArg("g","group","GROUP fields statements for shapefile",false,"","string"); TCLAP::ValueArg<std::string> ouputArg("t","outputType","Output type: (h)uman readable or (c)omputer readable",false,"h","string"); TCLAP::ValueArg<std::string> outputFileArg("o","outputFile","If output type is computer, output xml file. Default ./executesql_out.xml",false,"./executesql_out.xml","string"); //Switches TCLAP::SwitchArg remoteSwitch("r","remote","Connect to remote host", cmd, false); cmd.add(databaseArg); cmd.add(calculationArg); cmd.add(ouputArg); cmd.add(shapeArg); cmd.add(whereArg); cmd.add(groupArg); cmd.add(pathArg); cmd.add(hostArg); cmd.add(portArg); cmd.add(userArg); cmd.add(passArg); cmd.add(descArg); cmd.add(fieldArg); cmd.add(outputFileArg); //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 calculation = QString::fromUtf8(calculationArg.getValue().c_str()); QString format = QString::fromUtf8(ouputArg.getValue().c_str()); QString description = QString::fromUtf8(descArg.getValue().c_str()); QString shape = QString::fromUtf8(shapeArg.getValue().c_str()); QString cmdWhere = QString::fromUtf8(whereArg.getValue().c_str()); QString cmdgroup = QString::fromUtf8(groupArg.getValue().c_str()); QString strfields = QString::fromUtf8(fieldArg.getValue().c_str()); QString outfile = QString::fromUtf8(outputFileArg.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(); QString sql; QSqlQuery qry(mydb); if (!shapeFileExists(shape,mydb)) { gbtLog(QObject::tr("The shapefile does not exists")); mydb.close(); con.closeConnection(); return 1; } QStringList sfields; sfields = getFields(strfields,shape,mydb); if (constructSQL(calculation,sql,mydb,shape,sfields,cmdWhere,cmdgroup,description)) { gbtLog(QObject::tr("Error in calculation.")); mydb.close(); con.closeConnection(); return 1; } //gbtLog(sql); if (!qry.exec(sql)) { gbtLog(QObject::tr("Error in calculation.")); gbtLog(qry.lastError().databaseText()); mydb.close(); con.closeConnection(); return 1; } if (format == "h") printResult(qry); else genXML(outfile,qry); //---------------Print or save result------------------------------- int Hours; int Minutes; int Seconds; int Milliseconds; Milliseconds = procTime.elapsed(); Hours = Milliseconds / (1000*60*60); Minutes = (Milliseconds % (1000*60*60)) / (1000*60); Seconds = ((Milliseconds % (1000*60*60)) % (1000*60)) / 1000; if (format == "h") gbtLog("Finished in " + QString::number(Hours) + " Hours," + QString::number(Minutes) + " Minutes and " + QString::number(Seconds) + " Seconds."); mydb.close(); con.closeConnection(); return 0; } return 0; }
int main(int argc, char ** argv) { #ifdef DEBUG QsLogging::Logger & logger = QsLogging::Logger::instance(); logger.setLoggingLevel(QsLogging::TraceLevel); QDir dir; dir.setPath(qApp->applicationDirPath()); dir.remove(QString("cpp_utils") + QString(".log")); const QString sLogPath(QDir(qApp->applicationDirPath()).filePath(QString("cpp_generator") + QString(".log"))); QsLogging::DestinationPtr fileDestination(QsLogging::DestinationFactory::MakeFileDestination(sLogPath)); QsLogging::DestinationPtr debugDestination(QsLogging::DestinationFactory::MakeDebugOutputDestination()); logger.addDestination(debugDestination.get()); logger.addDestination(fileDestination.get()); QSettings settings(QSettings::IniFormat, QSettings::UserScope, "DoUML", "settings"); settings.setIniCodec(QTextCodec::codecForName("UTF-8")); QString locale = settings.value("Main/encoding").toString(); QTextCodec* codec = QTextCodec::codecForName(locale.toLatin1().constData()); QTextCodec::setCodecForLocale(codec); QLOG_INFO() << " STARTING CPP_GENERATOR"; #endif //QTest::qSleep(7000); int port_index; #ifndef _RUN_PLUGOUT_EXTERNAL_ if (argc == 2) { port_index = 1; QLOG_INFO() << "Got two arguments from Douml as argv"; QLOG_INFO() << "Using first port index mode"; } else if (argc == 3) { QLOG_INFO() << "Got three arguments from Douml as argv"; if (argv[1][1] == 'v') { QLOG_INFO() << "Using verbose mode"; set_verbose(); } else { QLOG_INFO() << "Using preserve mode"; set_preserve(); } QLOG_INFO() << "Using second port index mode"; port_index = 2; } else if (argc == 4) { QLOG_INFO() << "Got four arguments from Douml as argv"; QLOG_INFO() << "Using preserve mode"; QLOG_INFO() << "Using verbose mode"; QLOG_INFO() << "Using third port index mode"; set_verbose(); set_preserve(); port_index = 3; } else { QLOG_INFO() << "Got too little or too much arguments from Douml, exiting"; return 0; } if (UmlCom::connect(QString(argv[port_index]).toUInt())) { #else port_index = 1; if (UmlCom::connect(5000)) { #endif try { UmlCom::trace("<b>C++ generator</b> release 2.18<br>"); UmlCom::traceAutoRaise(FALSE); UmlCom::targetItem()->generate(); QString s; s = "<hr><font face=helvetica>Generation done : %1 warnings, %2 errors</font><br>"; s=s.arg(QString::number(n_warnings())).arg(QString::number(n_errors())); UmlCom::trace(s.toLatin1().constData()); UmlCom::showTrace(); UmlCom::message(""); UmlCom::bye(n_errors()); } catch (...) { QLOG_INFO() << "unhandled exception caught"; } } UmlCom::close(); return 0; }
void IconView::HandleImport(void) { QFileInfo path; QDir importdir; #if 0 DialogBox *importDlg = new DialogBox(GetMythMainWindow(), tr("Import pictures?")); importDlg->AddButton(tr("No")); importDlg->AddButton(tr("Yes")); DialogCode code = importDlg->exec(); importDlg->deleteLater(); if (kDialogCodeButton1 != code) return; #endif // Makes import directory samba/windows friendly (no colon) QString idirname = m_currDir + "/" + MythDate::current().toString("yyyy-MM-dd_hh-mm-ss"); importdir.mkdir(idirname); importdir.setPath(idirname); for (QStringList::const_iterator it = m_paths.begin(); it != m_paths.end(); ++it) { path.setFile(*it); if (path.isDir() && path.isReadable()) { ImportFromDir(*it, importdir.absolutePath()); } #if 0 else if (path.isFile() && path.isExecutable()) { // TODO this should not be enabled by default!!! QString cmd = *it + " " + importdir.absolutePath(); LOG(VB_GENERAL, LOG_INFO, LOC + QString("Executing %1").arg(cmd)); myth_system(cmd); } #endif else { LOG(VB_GENERAL, LOG_ERR, LOC + QString("Could not read or execute %1").arg(*it)); } } importdir.refresh(); if (importdir.count() == 0) { #if 0 DialogBox *nopicsDlg = new DialogBox(GetMythMainWindow(), tr("Nothing found to import")); nopicsDlg->AddButton(tr("OK")); nopicsDlg->exec(); nopicsDlg->deleteLater(); #endif return; } LoadDirectory(m_currDir); }
void ThemesDlg::populateListbox() { ThemeWidget* item; QDir dir; QStringList dirs; QStringList t; KStandardDirs ksd; tableThemes->clear(); item = new ThemeWidget; item->iconLabel->setPixmap(KIconLoader::global()->loadIcon("get-hot-new-stuff", KIconLoader::NoGroup, KIconLoader::SizeHuge)); item->setHeaderText(i18n("Get New Stuff")); item->setDescriptionText(i18n("Download new themes.")); item->buttonGo->setText(i18n("New Stuff...")); item->buttonGo->setEnabled(true); QObject::connect(item->buttonGo, SIGNAL(clicked()), this, SLOT(getNewStuff())); tableThemes->insertItem((QWidget*)(item)); item = new ThemeWidget; item->iconLabel->setPixmap(KIconLoader::global()->loadIcon("document-open", KIconLoader::NoGroup, KIconLoader::SizeHuge)); item->setHeaderText(i18n("Open Local Theme")); item->setDescriptionText(i18n("Add local theme to the list.")); item->buttonGo->setProperty("stdItem", 18); item->buttonGo->setText(i18nc("Open theme button", "Open...")); QObject::connect((QObject*)(item->buttonGo), SIGNAL(clicked()), (QObject*)(this), SLOT(openLocalTheme())); tableThemes->insertItem((QWidget*)item); dirs = ksd.findDirs("data", QString(kapp->objectName()) + "/themes"); // Get custom dirs from config here? QStringList::Iterator itend(dirs.end()); for (QStringList::Iterator it = dirs.begin(); it != itend; ++it) { QStringList types; types << "*.skz" << "*.theme"; dir.setPath(*it); t = dir.entryList(types); for (QStringList::Iterator it = t.begin(); it != t.end(); ++it) { item = new ThemeWidget(new ThemeFile(dir.filePath(*it))); tableThemes->insertItem((QWidget*)item); item->buttonGo->setText(i18n("Uninstall")); QObject::connect((QObject*)item->buttonGo, SIGNAL(clicked()), (QObject*)this, SLOT(uninstall())); } } t = SuperKarambaSettings::userAddedThemes(); for (QStringList::Iterator it = t.begin(); it != t.end(); ++it) { ThemeFile* file = new ThemeFile(*it); if (file->isValid()) { item = new ThemeWidget(file); tableThemes->insertItem((QWidget*)item); item->buttonGo->setText(i18n("Uninstall")); QObject::connect((QObject*)item->buttonGo, SIGNAL(clicked()), (QObject*)this, SLOT(uninstall())); } else delete file; } tableThemes->setSelected(0); }
bool RCCResourceLibrary::interpretResourceFile(QIODevice *inputDevice, const QString &fname, QString currentPath, bool ignoreErrors) { Q_ASSERT(m_errorDevice); const QChar slash = QLatin1Char('/'); if (!currentPath.isEmpty() && !currentPath.endsWith(slash)) currentPath += slash; QDomDocument document; { QString errorMsg; int errorLine = 0; int errorColumn = 0; if (!document.setContent(inputDevice, &errorMsg, &errorLine, &errorColumn)) { if (ignoreErrors) return true; const QString msg = QString::fromUtf8("RCC Parse Error: '%1' Line: %2 Column: %3 [%4]\n").arg(fname).arg(errorLine).arg(errorColumn).arg(errorMsg); m_errorDevice->write(msg.toUtf8()); return false; } } QDomElement domRoot = document.firstChildElement(m_strings.TAG_RCC).toElement(); if (!domRoot.isNull() && domRoot.tagName() == m_strings.TAG_RCC) { for (QDomNode node = domRoot.firstChild(); !node.isNull(); node = node.nextSibling()) { if (!node.isElement()) continue; QDomElement child = node.toElement(); if (!child.isNull() && child.tagName() == m_strings.TAG_RESOURCE) { QLocale::Language language = QLocale::c().language(); QLocale::Country country = QLocale::c().country(); if (child.hasAttribute(m_strings.ATTRIBUTE_LANG)) { QString attribute = child.attribute(m_strings.ATTRIBUTE_LANG); QLocale lang = QLocale(attribute); language = lang.language(); if (2 == attribute.length()) { // Language only country = QLocale::AnyCountry; } else { country = lang.country(); } } QString prefix; if (child.hasAttribute(m_strings.ATTRIBUTE_PREFIX)) prefix = child.attribute(m_strings.ATTRIBUTE_PREFIX); if (!prefix.startsWith(slash)) prefix.prepend(slash); if (!prefix.endsWith(slash)) prefix += slash; for (QDomNode res = child.firstChild(); !res.isNull(); res = res.nextSibling()) { if (res.isElement() && res.toElement().tagName() == m_strings.TAG_FILE) { QString fileName(res.firstChild().toText().data()); if (fileName.isEmpty()) { const QString msg = QString::fromUtf8("RCC: Warning: Null node in XML of '%1'\n").arg(fname); m_errorDevice->write(msg.toUtf8()); } QString alias; if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_ALIAS)) alias = res.toElement().attribute(m_strings.ATTRIBUTE_ALIAS); else alias = fileName; int compressLevel = m_compressLevel; if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_COMPRESS)) compressLevel = res.toElement().attribute(m_strings.ATTRIBUTE_COMPRESS).toInt(); int compressThreshold = m_compressThreshold; if (res.toElement().hasAttribute(m_strings.ATTRIBUTE_THRESHOLD)) compressThreshold = res.toElement().attribute(m_strings.ATTRIBUTE_THRESHOLD).toInt(); // Special case for -no-compress. Overrides all other settings. if (m_compressLevel == -2) compressLevel = 0; alias = QDir::cleanPath(alias); while (alias.startsWith(QLatin1String("../"))) alias.remove(0, 3); alias = QDir::cleanPath(m_resourceRoot) + prefix + alias; QString absFileName = fileName; if (QDir::isRelativePath(absFileName)) absFileName.prepend(currentPath); QFileInfo file(absFileName); if (!file.exists()) { m_failedResources.push_back(absFileName); const QString msg = QString::fromUtf8("RCC: Error in '%1': Cannot find file '%2'\n").arg(fname).arg(fileName); m_errorDevice->write(msg.toUtf8()); if (ignoreErrors) continue; else return false; } else if (file.isFile()) { const bool arc = addFile(alias, RCCFileInfo(alias.section(slash, -1), file, language, country, RCCFileInfo::NoFlags, compressLevel, compressThreshold) ); if (!arc) m_failedResources.push_back(absFileName); } else { QDir dir; if (file.isDir()) { dir.setPath(file.filePath()); } else { dir.setPath(file.path()); dir.setNameFilters(QStringList(file.fileName())); if (alias.endsWith(file.fileName())) alias = alias.left(alias.length()-file.fileName().length()); } if (!alias.endsWith(slash)) alias += slash; QDirIterator it(dir, QDirIterator::FollowSymlinks|QDirIterator::Subdirectories); while (it.hasNext()) { it.next(); QFileInfo child(it.fileInfo()); if (child.fileName() != QLatin1String(".") && child.fileName() != QLatin1String("..")) { const bool arc = addFile(alias + child.fileName(), RCCFileInfo(child.fileName(), child, language, country, RCCFileInfo::NoFlags, compressLevel, compressThreshold) ); if (!arc) m_failedResources.push_back(child.fileName()); } } } } } } } } if (m_root == 0) { const QString msg = QString::fromUtf8("RCC: Warning: No resources in '%1'.\n").arg(fname); m_errorDevice->write(msg.toUtf8()); if (!ignoreErrors && m_format == Binary) { // create dummy entry, otherwise loading qith QResource will crash m_root = new RCCFileInfo(QString(), QFileInfo(), QLocale::C, QLocale::AnyCountry, RCCFileInfo::Directory); } } return true; }
void SyncAction::sync(SyncFile * parent, FolderActionGroup * f*g) { if (!parent) return; SyncFile * sf = NULL; QFileInfo fi; QDir dir; int latest_index_arr[f*g->count()]; int latest_index = 0, c; MTFileInfo * newest_fi = NULL; FolderActionGroup * sub_fag = NULL; sf_queue << parent; for (int i = 0; i < parent->childCount(); ++i) { sf = parent->childAt(i); latest_index = 0; if (newest_fi) { delete newest_fi; newest_fi = NULL; } if (sf->isInDatabase() && sf->numFoundFolders() < f*g->count()) { // was deleted deleteFileOrFolder(sf, f*g); } else if (sf->isDir()) { sub_fag = new FolderActionGroup; for (int n = 0; n < f*g->count(); ++n) { dir.setPath(f*g->at(n)); if (!sf->existsInFolder(f*g->idAt(n))) { if (options->canCopy(f*g->idAt(n)) && (sf->childCount() || options->createEmptyFolders(f*g->idAt(n)))) { if (createFolder(sf, new FolderActionGroup(f*g->idAt(n), dir.absoluteFilePath(sf->getName())))) sub_fag->insert(f*g->idAt(n), dir.absoluteFilePath(sf->getName())); } } else { sub_fag->insert(f*g->idAt(n), dir.absoluteFilePath(sf->getName())); } } if (options->syncSubdirs()) sync(sf, sub_fag); delete sub_fag; } else { // is not dir for (int n = 0; n < f*g->count(); ++n) { if (sf->fileStatusInFolder(f*g->idAt(n)) == SyncFile::Obsolete) { // Found, checked and obsolete latest_index_arr[n] = latest_index - 1; } else if (sf->existsInFolder(f*g->idAt(n))) { // Found but not checked yet dir.setPath(f*g->at(n)); fi.setFile(dir.absoluteFilePath(sf->getName())); if (!newest_fi) { newest_fi = new MTFileInfo(fi, f*g->idAt(n)); latest_index_arr[n] = latest_index; } else { if (sf->fileStatusInFolder(f*g->idAt(n)) == SyncFile::OK || // checked before and is newest (c = file_compare->compareTwoFiles(&fi, newest_fi)) == 0) { // equal to the newest latest_index_arr[n] = latest_index; } else if (c > 0) { // fi is newer newest_fi->setFile(fi.absoluteFilePath()); newest_fi->setFolderId(f*g->idAt(n)); latest_index_arr[n] = ++latest_index; } else { // fi is older latest_index_arr[n] = latest_index - 1; } } } else { // Not found latest_index_arr[n] = -2; } } if (latest_index < 0) // probably never happens... continue; for (int n = 0; n < f*g->count(); ++n) { dir.setPath(f*g->at(n)); if (latest_index_arr[n] == -2) { // does not exist if (options->canCopy(f*g->idAt(n))) copyFile(sf, new FolderActionGroup(newest_fi->folderId(), newest_fi->absoluteFilePath(), f*g->idAt(n), dir.absoluteFilePath(sf->getName()))); } else if (latest_index_arr[n] < latest_index) { // is obsolete if (options->canUpdate(f*g->idAt(n))) updateFile(sf, new FolderActionGroup(newest_fi->folderId(), newest_fi->absoluteFilePath(), f*g->idAt(n), dir.absoluteFilePath(sf->getName()))); } else { // is fine sf->setFileStatusInFolder(f*g->idAt(n), SyncFile::OK); } } if (newest_fi) { sf->setLastModified(newest_fi->lastModified()); } } emit this->anotherItemChecked(); } sf_queue.takeLast(); }
int main( int argc, char **argv ) { std::string s; std::map<int,std::pair<int,int> > pos; vector<string> coord; set<int> exist; set<pair<int,int> > connec; std::ifstream i("../data/pos.txt"); if(i.fail()) printf("could not open pos.txt\n"); std::ofstream o("../data/data.xml"); o<<"<data x0=\"60.396\" y=\"5.32\" width=\"0.003\" height=\"0.002\">\n"; getline(i, s); QString ts,con; coord = split(s," "); int yoff = tolong(coord[1]); int xoff = tolong(coord[0]); printf("using offset %i,%i\n",xoff,yoff); while (getline(i, s)) { // s contains the input line, without final newline char. coord = split(s," "); //if(coord.size()!=3) { //printf("erreur : %i for line %i ",coord.size(),coord[0].c_str()); //exit(1); } ts="<spot id=\""+QString((coord[0]))+"\">\n"; ts+=" <position x=\""+QString(tostring(tolong(coord[1])+xoff))+"\" y=\""+QString(tostring(-tolong(coord[2])+yoff))+"\" z=\"0\"/>\n"; QDir d; d.setPath("../data/clips"); d.setFilter( QDir::Files | QDir::Hidden | QDir::NoSymLinks ); d.setSorting( QDir::Size | QDir::Reversed ); char pouet[10]; sprintf(pouet,"%02i",tolong(coord[0])); d.setNameFilter("shot"+string(pouet)+"*"); const QFileInfoList *list = d.entryInfoList(); QFileInfoListIterator it( *list ); QFileInfo *fi; int clips=0; while ( (fi = it.current()) != 0 ) { ts+= " <moviefile>"+QString(fi->fileName().latin1())+"</moviefile>\n"; ++it; ++clips; } ts+="</spot>\n\n"; if(clips>0) { exist.insert(tolong(coord[0])); o<<ts.latin1(); } for(int i=3;i<coord.size();i++) connec.insert(make_pair(tolong(coord[0]),tolong(coord[i]))); } for(set<pair<int,int> >::iterator it=connec.begin();it!=connec.end();++it) if(exist.find(it->first)!=exist.end() && exist.find(it->second)!=exist.end()) o<<" <connection from=\""+QString(tostring(it->first))+"\" to=\""+QString(tostring(it->second))+"\" />\n"; o<<"</data>\n"; o.close(); return 0; }
void doSetupQtProfile(const QString &profileName, Settings *settings, const QtEnvironment &_qtEnvironment) { QtEnvironment qtEnvironment = _qtEnvironment; qtEnvironment.staticBuild = checkForStaticBuild(qtEnvironment); // determine whether user apps require C++11 if (qtEnvironment.qtConfigItems.contains(QLatin1String("c++11")) && qtEnvironment.staticBuild) qtEnvironment.configItems.append(QLatin1String("c++11")); Profile profile(profileName, settings); profile.removeProfile(); const QString settingsTemplate(QLatin1String("Qt.core.%1")); profile.setValue(settingsTemplate.arg(QLatin1String("config")), qtEnvironment.configItems); profile.setValue(settingsTemplate.arg(QLatin1String("qtConfig")), qtEnvironment.qtConfigItems); profile.setValue(settingsTemplate.arg(QLatin1String("binPath")), qtEnvironment.binaryPath); profile.setValue(settingsTemplate.arg(QLatin1String("libPath")), qtEnvironment.libraryPath); profile.setValue(settingsTemplate.arg(QLatin1String("pluginPath")), qtEnvironment.pluginPath); profile.setValue(settingsTemplate.arg(QLatin1String("incPath")), qtEnvironment.includePath); profile.setValue(settingsTemplate.arg(QLatin1String("mkspecPath")), qtEnvironment.mkspecPath); profile.setValue(settingsTemplate.arg(QLatin1String("docPath")), qtEnvironment.documentationPath); profile.setValue(settingsTemplate.arg(QLatin1String("version")), qtEnvironment.qtVersion); profile.setValue(settingsTemplate.arg(QLatin1String("libInfix")), qtEnvironment.qtLibInfix); profile.setValue(settingsTemplate.arg(QLatin1String("buildVariant")), qtEnvironment.buildVariant); // TODO: Remove in 1.5 profile.setValue(settingsTemplate.arg(QLatin1String("availableBuildVariants")), qtEnvironment.buildVariant); profile.setValue(settingsTemplate.arg(QLatin1String("staticBuild")), qtEnvironment.staticBuild); // Set the minimum operating system versions appropriate for this Qt version const QString windowsVersion = guessMinimumWindowsVersion(qtEnvironment); QString osxVersion, iosVersion, androidVersion; if (!windowsVersion.isEmpty()) { // Is target OS Windows? const Version qtVersion = Version(qtEnvironment.qtMajorVersion, qtEnvironment.qtMinorVersion, qtEnvironment.qtPatchVersion); qtEnvironment.entryPointLibsDebug = fillEntryPointLibs(qtEnvironment, qtVersion, true); qtEnvironment.entryPointLibsRelease = fillEntryPointLibs(qtEnvironment, qtVersion, false); } else if (qtEnvironment.mkspecPath.contains(QLatin1String("macx"))) { profile.setValue(settingsTemplate.arg(QLatin1String("frameworkBuild")), qtEnvironment.frameworkBuild); if (qtEnvironment.qtMajorVersion >= 5) { osxVersion = QLatin1String("10.6"); } else if (qtEnvironment.qtMajorVersion == 4 && qtEnvironment.qtMinorVersion >= 6) { QDir qconfigDir; if (qtEnvironment.frameworkBuild) { qconfigDir.setPath(qtEnvironment.libraryPath); qconfigDir.cd(QLatin1String("QtCore.framework/Headers")); } else { qconfigDir.setPath(qtEnvironment.includePath); qconfigDir.cd(QLatin1String("Qt")); } QFile qconfig(qconfigDir.absoluteFilePath(QLatin1String("qconfig.h"))); if (qconfig.open(QIODevice::ReadOnly)) { bool qtCocoaBuild = false; QTextStream ts(&qconfig); QString line; do { line = ts.readLine(); if (QRegExp(QLatin1String("\\s*#define\\s+QT_MAC_USE_COCOA\\s+1\\s*"), Qt::CaseSensitive).exactMatch(line)) { qtCocoaBuild = true; break; } } while (!line.isNull()); if (ts.status() == QTextStream::Ok) osxVersion = qtCocoaBuild ? QLatin1String("10.5") : QLatin1String("10.4"); } if (osxVersion.isEmpty()) { throw ErrorInfo(Internal::Tr::tr("Error reading qconfig.h; could not determine " "whether Qt is using Cocoa or Carbon")); } } if (qtEnvironment.qtConfigItems.contains(QLatin1String("c++11"))) osxVersion = QLatin1String("10.7"); } if (qtEnvironment.mkspecPath.contains(QLatin1String("ios")) && qtEnvironment.qtMajorVersion >= 5) iosVersion = QLatin1String("5.0"); if (qtEnvironment.mkspecPath.contains(QLatin1String("android"))) { if (qtEnvironment.qtMajorVersion >= 5) androidVersion = QLatin1String("2.3"); else if (qtEnvironment.qtMajorVersion == 4 && qtEnvironment.qtMinorVersion >= 8) androidVersion = QLatin1String("1.6"); // Necessitas } // ### TODO: wince, winphone, blackberry if (!windowsVersion.isEmpty()) profile.setValue(QLatin1String("cpp.minimumWindowsVersion"), windowsVersion); if (!osxVersion.isEmpty()) profile.setValue(QLatin1String("cpp.minimumOsxVersion"), osxVersion); if (!iosVersion.isEmpty()) profile.setValue(QLatin1String("cpp.minimumIosVersion"), iosVersion); if (!androidVersion.isEmpty()) profile.setValue(QLatin1String("cpp.minimumAndroidVersion"), androidVersion); createModules(profile, settings, qtEnvironment); }
static PRL_RESULT GetEntryLists( const QString & aVmHomeDir, QList<QPair<QFileInfo, QString> > & dirList, QList<QPair<QFileInfo, QString> > & fileList) { QString VmHomeDir = QFileInfo(aVmHomeDir).absoluteFilePath(); QFileInfo dirInfo; QFileInfoList entryList; QDir dir; QDir startDir(VmHomeDir); int i, j; QFileInfo config, config_backup, log, statlog; config.setFile(VmHomeDir, VMDIR_DEFAULT_VM_CONFIG_FILE); config_backup.setFile(VmHomeDir, VMDIR_DEFAULT_VM_CONFIG_FILE VMDIR_DEFAULT_VM_BACKUP_SUFFIX); log.setFile(VmHomeDir, "parallels.log"); statlog.setFile(VmHomeDir, PRL_VMTIMING_LOGFILENAME); dirInfo.setFile(VmHomeDir); if (!dirInfo.exists()) { WRITE_TRACE(DBG_FATAL, "Directory %s does not exist", QSTR2UTF8(VmHomeDir)); return (PRL_ERR_VMDIR_INVALID_PATH); } dirList.append(qMakePair(dirInfo, QString("."))); for (i = 0; i < dirList.size(); ++i) { /* CDir::absoluteDir() is equal CDir::dir() : return parent directory */ dir.setPath(dirList.at(i).first.absoluteFilePath()); entryList = dir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files | QDir::Dirs | QDir::Hidden); WRITE_TRACE(DBG_DEBUG, "Directory %s", QSTR2UTF8(dirList.at(i).first.absoluteFilePath())); for (j = 0; j < entryList.size(); ++j) { const QFileInfo& fileInfo = entryList.at(j); if (dirInfo == fileInfo) { WRITE_TRACE(DBG_FATAL, "Infinite recursion in : %s", QSTR2UTF8(dirInfo.absoluteFilePath())); return (PRL_ERR_FAILURE); } if (!fileInfo.absoluteFilePath().startsWith(VmHomeDir)) { WRITE_TRACE(DBG_FATAL, "Path %s does not starts from VM home dir (%s)", QSTR2UTF8(fileInfo.absoluteFilePath()), QSTR2UTF8(VmHomeDir)); return PRL_ERR_FAILURE; } ; if (fileInfo.isDir()) { dirList.append(qMakePair( fileInfo, startDir.relativeFilePath(fileInfo.absoluteFilePath()))); } else { /* skip config & config backup */ if (fileInfo.absoluteFilePath() == config.absoluteFilePath()) continue; if (fileInfo.absoluteFilePath() == config_backup.absoluteFilePath()) continue; /* skip parallels.log */ if (fileInfo.absoluteFilePath() == log.absoluteFilePath()) continue; if (fileInfo.absoluteFilePath() == statlog.absoluteFilePath()) /* will save statistic.log to temporary file */ fileList.append(qMakePair(statlog, QString(PRL_VMTIMING_LOGFILENAME VMDIR_DEFAULT_VM_MIGRATE_SUFFIX))); else fileList.append(qMakePair( fileInfo, startDir.relativeFilePath(fileInfo.absoluteFilePath()))); } WRITE_TRACE(DBG_DEBUG, "%x\t%s.%s\t%s", int(fileInfo.permissions()), QSTR2UTF8(fileInfo.owner()), QSTR2UTF8(fileInfo.group()), QSTR2UTF8(fileInfo.absoluteFilePath())); } entryList.clear(); } /* remove VM home directory */ dirList.removeFirst(); return (PRL_ERR_SUCCESS); }
QStringList KateProjectWorker::filesFromGit(const QDir &dir, bool recursive) { // init libgit2, we require at least 0.22 which has this function! // do this here to have init in this thread done, shutdown afterwards again! git_libgit2_init(); QStringList files; git_repository *repo = nullptr; git_object *root_tree = nullptr, *tree = nullptr; // check if the repo can be opened. // git_repository_open_ext() will return 0 if everything is OK; // if not, return an empty files list const QByteArray repoPathUtf8 = dir.path().toUtf8(); if (git_repository_open_ext(&repo, repoPathUtf8.constData(), 0, NULL)) { git_libgit2_shutdown(); return files; } // get the working directory of the repo // if none was found, return an empty files list const char *working_dir = nullptr; if ((working_dir = git_repository_workdir(repo)) == nullptr) { git_repository_free(repo); git_libgit2_shutdown(); return files; } if (git_revparse_single(&root_tree, repo, "HEAD^{tree}")) { git_repository_free(repo); git_libgit2_shutdown(); return files; } QDir workdir; workdir.setPath(QString::fromUtf8(working_dir)); const QByteArray relpathUtf8 = workdir.relativeFilePath(dir.path()).toUtf8(); if (relpathUtf8.isEmpty() || relpathUtf8 == ".") { // git_object_lookup_bypath is not able to resolv "." as path tree = root_tree; } else { if (git_object_lookup_bypath(&tree, root_tree, relpathUtf8.constData(), GIT_OBJ_TREE)) { git_object_free(root_tree); git_repository_free(repo); git_libgit2_shutdown(); return files; } } QString path = workdir.absolutePath() + QDir::separator(); files.append(gitSearchTree(tree, path, recursive)); if (recursive && relpathUtf8.isEmpty()) { files.append(gitSearchSubmodules(repo, path)); } files.append(gitSearchStatusList(repo, path)); if (tree != root_tree) { git_object_free(tree); } git_object_free(root_tree); git_repository_free(repo); git_libgit2_shutdown(); return files; }
void g_setProperty(const char* what, const char* arg) { QString argGet = QString::fromUtf8(arg); int arg1 = 0; int arg2 = 0; int arg3 = 0; QString argString = ""; if ( g_checkStringProperty(true,what)) { argString = argGet; argString.replace("\\","\\\\"); } else { QStringList arrayArg = argGet.split("|",QString::KeepEmptyParts); arg1 = arrayArg.at(0).toInt(); arg2 = arrayArg.at(1).toInt(); arg3 = arrayArg.at(2).toInt(); } /*------------------------------------------------------------------*/ if (strcmp(what, "cursor") == 0) { QStringList acceptedValue; acceptedValue << "arrow" << "upArrow" << "cross" << "wait" << "IBeam"; acceptedValue << "sizeVer" << "sizeHor" << "sizeBDiag" << "sizeFDiag" << "sizeAll"; acceptedValue << "blank" << "splitV" << "splitH" << "pointingHand" << "forbidden"; acceptedValue << "whatsThis" << "busy" << "openHand" << "closedHand" << "dragCopy"; acceptedValue << "dragMove" << "dragLink"; // value of cursor also taken from index of the text, do not change the list if (acceptedValue.contains(argString)) { arg1 = acceptedValue.indexOf(argString); MainWindow::getInstance()->setCursor((Qt::CursorShape) arg1); } else { QString info = "Accepted value for "; info.append(what); info.append(" :"); MainWindow::getInstance()->printToOutput(info.toStdString().c_str()); for( int i=0; i<acceptedValue.size(); ++i ) { MainWindow::getInstance()->printToOutput( QString("- ").append(acceptedValue.at(i)).toStdString().c_str() ); } } /*------------------------------------------------------------------*/ } else if (strcmp(what, "windowPosition") == 0) { MainWindow::getInstance()->move(arg1,arg2); /*------------------------------------------------------------------*/ } else if (strcmp(what, "windowSize") == 0) { MainWindow::getInstance()->resizeWindow(arg1,arg2); /*------------------------------------------------------------------*/ } else if (strcmp(what, "minimumSize") == 0) { MainWindow::getInstance()->setMinimumSize(QSize(arg1,arg2)); /*------------------------------------------------------------------*/ } else if (strcmp(what, "maximumSize") == 0) { MainWindow::getInstance()->setMaximumSize(QSize(arg1,arg2)); /*------------------------------------------------------------------*/ } else if (strcmp(what, "windowColor") == 0) { if (arg1 > 255) { arg1 = 255; } else if(arg1 < 0) { arg1 = 255; } if (arg2 > 255) { arg2 = 255; } else if(arg2 < 0) { arg2 = 255; } if (arg3 > 255) { arg3 = 255; } else if(arg3 < 0) { arg3 = 255; } QPalette palette; QColor backgroundColor = QColor(arg1, arg2, arg3); palette.setColor(QPalette::Window, backgroundColor); MainWindow::getInstance()->setPalette(palette); /*------------------------------------------------------------------*/ } else if (strcmp(what, "windowTitle") == 0) { MainWindow::getInstance()->setWindowTitle(argString); /*------------------------------------------------------------------*/ } else if (strcmp(what, "windowModel") == 0) { QStringList acceptedValue; acceptedValue << "reset" << "stayOnTop" << "stayOnBottom" << "frameless" << "noTitleBar"; acceptedValue << "noButton" << "onlyMinimize" << "onlyMaximize" << "onlyClose" << "noMinimize"; acceptedValue << "noMaximize" << "noClose" << "helpButton"; if (acceptedValue.contains(argString)) { Qt::WindowFlags flags = MainWindow::getInstance()->windowFlags(); if (argString == "reset") { flags = Qt::Window; } else if (argString == "stayOnTop") { flags |= Qt::WindowStaysOnTopHint; } else if (argString == "stayOnBottom") { flags |= Qt::WindowStaysOnBottomHint; } else if (argString == "frameless") { flags |= Qt::FramelessWindowHint; } else if (argString == "noTitleBar") { flags = Qt::Window; flags |= Qt::CustomizeWindowHint; } else if (argString == "noButton") { flags = Qt::Window; flags |= Qt::WindowTitleHint; } else if (argString == "noClose") { flags = Qt::Window; flags |= Qt::WindowMinimizeButtonHint; } else if (argString == "onlyMaximize") { flags = Qt::Window; flags |= Qt::WindowMaximizeButtonHint; } else if (argString == "onlyClose") { flags = Qt::Window; flags |= Qt::WindowCloseButtonHint; } else if (argString == "noMinimize") { flags = Qt::Window; flags |= Qt::WindowMaximizeButtonHint; flags |= Qt::WindowCloseButtonHint; } else if (argString == "noMaximize") { flags = Qt::Window; flags |= Qt::WindowMinimizeButtonHint; flags |= Qt::WindowCloseButtonHint; } else if (argString == "noClose") { flags = Qt::Window; flags |= Qt::WindowMinimizeButtonHint; flags |= Qt::WindowMaximizeButtonHint; } else if (argString == "helpButton") { flags = Qt::Window; flags |= Qt::WindowContextHelpButtonHint; flags |= Qt::WindowCloseButtonHint; } MainWindow::getInstance()->setWindowFlags(flags); if (MainWindow::getInstance()->fullScreen()) { MainWindow::getInstance()->showFullScreen(); } else { MainWindow::getInstance()->showNormal(); } } else { QString info = "Accepted value for "; info.append(what); info.append(" :"); MainWindow::getInstance()->printToOutput(info.toStdString().c_str()); for( int i=0; i<acceptedValue.size(); ++i ) { MainWindow::getInstance()->printToOutput( QString("- ").append(acceptedValue.at(i)).toStdString().c_str() ); } } /*------------------------------------------------------------------*/ } else if (strcmp(what, "cursorPosition") == 0) { QCursor::setPos(arg1,arg2); /*------------------------------------------------------------------*/ } else if (strcmp(what, "clipboard") == 0) { QClipboard *clipboard = QApplication::clipboard(); clipboard->setText(argString); /*------------------------------------------------------------------*/ } else if (strcmp(what, "mkDir") == 0) { QStringList argSplit = argString.split("|",QString::KeepEmptyParts); if(argSplit.size() == 1) { MainWindow::getInstance()->printToOutput("[[Usage Example]]"); MainWindow::getInstance()->printToOutput("application:set(\"mkDir\",application:get(\"directory\",\"executable\")..\"|dirName\")"); } else { QDir dirPath = QDir::temp(); dirPath.setPath(argSplit.at(0)); dirPath.mkdir(argSplit.at(1)); } /*------------------------------------------------------------------*/ } else if (strcmp(what, "documentDirectory") == 0) { setDocumentsDirectory(argString.toStdString().c_str()); /*------------------------------------------------------------------*/ } else if (strcmp(what, "temporaryDirectory") == 0) { setTemporaryDirectory(argString.toStdString().c_str()); } else { // feel free to change this list QStringList acceptedWhat; acceptedWhat << "windowPosition(x,y)"; acceptedWhat << "windowSize(w,h)"; acceptedWhat << "minimumSize(w,h)"; acceptedWhat << "maximumSize(w,h)"; acceptedWhat << "windowColor(r,g,b)"; acceptedWhat << "windowTitle(text)"; acceptedWhat << "windowModel(type//help)"; acceptedWhat << "cursor(type//help)"; acceptedWhat << "cursorPosition(x,y)"; acceptedWhat << "clipboard(text)"; acceptedWhat << "mkdir(path|dirName//help)"; acceptedWhat << "documentDirectory(path)"; acceptedWhat << "temporaryDirectory(path)"; MainWindow::getInstance()->printToOutput("Accepted value for Desktop's application:set()"); for( int i=0; i<acceptedWhat.size(); ++i ) { MainWindow::getInstance()->printToOutput( QString("- ").append(acceptedWhat.at(i)).toStdString().c_str() ); } } }
bool KImGalleryPlugin::createHtml(const KURL& url, const QString& sourceDirName, int recursionLevel, const QString& imageFormat) { if(m_cancelled) return false; if( !parent() || !parent()->inherits("KonqDirPart")) return false; KonqDirPart * part = static_cast<KonqDirPart *>(parent()); QStringList subDirList; if (m_recurseSubDirectories && (recursionLevel >= 0)) { //recursionLevel == 0 means endless QDir toplevel_dir = QDir( sourceDirName ); toplevel_dir.setFilter( QDir::Dirs | QDir::Readable | QDir::Writable ); subDirList = toplevel_dir.entryList(); for (QStringList::ConstIterator it = subDirList.begin(); it != subDirList.end() && !m_cancelled; it++) { const QString currentDir = *it; if (currentDir == "." || currentDir == "..") { continue;} //disregard the "." and ".." directories QDir subDir = QDir( url.directory() + "/" + currentDir ); if (!subDir.exists()) { subDir.setPath( url.directory() ); if (!(subDir.mkdir(currentDir, false))) { KMessageBox::sorry(part->widget(), i18n("Couldn't create folder: %1").arg(subDir.path())); continue; } else { subDir.setPath( url.directory() + "/" + currentDir ); } } if(!createHtml( KURL( subDir.path() + "/" + url.fileName() ), sourceDirName + "/" + currentDir, recursionLevel > 1 ? recursionLevel - 1 : 0, imageFormat)) { return false; } } } if (m_useCommentFile) { loadCommentFile(); } kdDebug(90170) << "sourceDirName: " << sourceDirName << endl; //We're interested in only the patterns, so look for the first | //#### perhaps an accessor should be added to KImageIO instead? QString filter = KImageIO::pattern(KImageIO::Reading).section('|', 0, 0); QDir imageDir( sourceDirName, filter.latin1(), QDir::Name|QDir::IgnoreCase, QDir::Files|QDir::Readable); const QString imgGalleryDir = url.directory(); kdDebug(90170) << "imgGalleryDir: " << imgGalleryDir << endl; // Create the "thumbs" subdirectory if necessary QDir thumb_dir( imgGalleryDir + QString::fromLatin1("/thumbs/")); if (createDirectory(thumb_dir, imgGalleryDir, "thumbs") == false) return false; // Create the "images" subdirectory if necessary QDir images_dir( imgGalleryDir + QString::fromLatin1("/images/")); if (m_copyFiles) { if (createDirectory(images_dir, imgGalleryDir, "images") == false) return false; } QFile file( url.path() ); kdDebug(90170) << "url.path(): " << url.path() << ", thumb_dir: "<< thumb_dir.path() << ", imageDir: "<< imageDir.path() << endl; if ( imageDir.exists() && file.open(IO_WriteOnly) ) { QTextStream stream(&file); stream.setEncoding(QTextStream::Locale); createHead(stream); createBody(stream, sourceDirName, subDirList, imageDir, url, imageFormat); //ugly file.close(); return !m_cancelled; } else { KMessageBox::sorry(m_part->widget(),i18n("Couldn't open file: %1").arg(url.path(+1))); return false; } }
Config::Config() { int i = 0; xmppwinFound = false; connectionFound = false; otherFound = false; noConfig = false; QByteArray config; //Loads last configuration from ~/.Kapture/conf.xml QDir *confDir = new QDir(QDir::homePath() + "/.Kapture/"); if (!confDir->exists()) { QDir::home().mkdir(".Kapture"); } confDir->setPath(QDir::homePath() + "/.Kapture/"); if (!confDir->exists()) { noConfig = true; QMessageBox::critical(0, QString("Jabber"), QString("Unable to create config file. Check permissions for\n \"$HOME/.Kapture/conf.xml\""), QMessageBox::Ok); return; } QFile *conf = new QFile(QDir::homePath() + "/.Kapture/conf.xml"); conf->open(QIODevice::ReadOnly); config = conf->readAll(); d.setContent(config); if (d.documentElement().tagName() != "Kapture") { noConfig = true; return; } classes = d.documentElement().childNodes(); for(i = 0; i < classes.count() ;i++) { if (classes.at(i).toElement().tagName() == "xmppwin") { xmppwinFound = true; xmppwinN = i; } if (classes.at(i).toElement().tagName() == "connection") { connectionFound = true; connectionN = i; } if (classes.at(i).toElement().tagName() == "other") { otherFound = true; otherN = i; } } // Loading xmppwin class data. if (xmppwinFound) { QDomNodeList profilesNodeList = classes.at(xmppwinN).childNodes(); for (int j = 0; j < profilesNodeList.count(); j++) { cJid = Jid(""); cPassword = ""; cPersonnalServer = ""; cPort = "5222"; cProfile = profilesNodeList.at(j).toElement().attribute("name"); QDomNodeList infos = profilesNodeList.at(j).childNodes(); for (i = 0; i < infos.count(); i++) { if (infos.at(i).toElement().tagName() == "jid" && infos.at(i).hasChildNodes()) cJid = Jid(infos.at(i).firstChild().toText().data()); if (infos.at(i).toElement().tagName() == "password" && infos.at(i).hasChildNodes()) cPassword = QByteArray::fromBase64(infos.at(i).firstChild().toText().data().toLatin1()); if (infos.at(i).toElement().tagName() == "server" && infos.at(i).hasChildNodes()) cPersonnalServer = infos.at(i).firstChild().toText().data(); if (infos.at(i).toElement().tagName() == "port" && infos.at(i).hasChildNodes()) cPort = infos.at(i).firstChild().toText().data(); } Profile *profile = new Profile(cProfile); profile->setData(cJid, cPassword, cPersonnalServer, cPort); profiles << *profile; } } // Loading connection class data if (connectionFound) { QDomNodeList connectionNodeList = classes.at(connectionN).childNodes(); for (int i = 0; i < connectionNodeList.count(); i++) { // File Transfer Port if (connectionNodeList.at(i).localName() == "ftport") cFTPort = connectionNodeList.at(i).toElement().attribute("val", "8010"); // Proxy if (connectionNodeList.at(i).localName() == "proxy") cProxy = connectionNodeList.at(i).toElement().attribute("val", ""); // Resource if (connectionNodeList.at(i).localName() == "resource") cResource = connectionNodeList.at(i).toElement().attribute("val", "Kapture"); } } else { // Default Values cFTPort = "8010"; cProxy = ""; cResource = "Kapture"; } // Loading Other class data if (otherFound) { QDomNodeList otherNodeList = classes.at(otherN).childNodes(); for (int i = 0; i < otherNodeList.count(); i++) { if (otherNodeList.at(i).localName() == "systray") cUseSysTray = otherNodeList.at(i).toElement().attribute("val", "true") == "true" ? true : false; } } else { // Default Values. cUseSysTray = true; } /* TODO: * Should create an initial config if there's none at all. */ }
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; }
//开始编译 void FMainWidgt::sartCompling() { qDebug() << ">>>>> Current ComplingIndex>>> " << m_nCurrentComplingIndex; if(m_nCurrentComplingIndex == m_pSourceProFileModel->rowCount()) { setErrorStatusTip(eCompli_Completed); if(m_nCurrentErrorCount > 0) { ui->logTabWgt->setCurrentWidget(ui->errorLogTab); } return ; } //判断当前编译是否已经成功,如果成功跳转下一行, int nCompileStatus = m_pSourceProFileModel->data(m_pSourceProFileModel->index(m_nCurrentComplingIndex, eCol_CompilingStatus), Qt::UserRole+1).toInt(); while(nCompileStatus == eCompile_Succeed) { if(m_nCurrentComplingIndex + 1 >= m_pSourceProFileModel->rowCount()) { setErrorStatusTip(eCompli_Completed); return ; } m_nCurrentComplingIndex++; nCompileStatus = m_pSourceProFileModel->data(m_pSourceProFileModel->index(m_nCurrentComplingIndex, eCol_CompilingStatus), Qt::UserRole+1).toInt(); } QString sProFileName = m_pSourceProFileModel->data(m_pSourceProFileModel->index(m_nCurrentComplingIndex, eCol_FileName), Qt::UserRole+1).toString(); QFileInfo proFileInfo(sProFileName); qDebug() << proFileInfo.baseName(); QString sBuildPath = ui->compiledPathLdt->text()+ "/" + proFileInfo.baseName() + "_build"; QDir buildDir; buildDir.setPath(sBuildPath); if(!buildDir.exists()) { buildDir.mkpath(sBuildPath); } QDir::setCurrent(sBuildPath); QStringList lArguments; lArguments << sProFileName; m_nProcessFlg = eCreateMakeFile_Process; m_pCurrProcess->start(ui->qmakePathLndt->text(), lArguments); }
/*! constructs command line of htags(1) and executes it. * \retval TRUE success * \retval FALSE an error has occurred. */ bool Htags::execute(const QCString &htmldir) { static QStrList &inputSource = Config_getList("INPUT"); static bool quiet = Config_getBool("QUIET"); static bool warnings = Config_getBool("WARNINGS"); static QCString htagsOptions = ""; //Config_getString("HTAGS_OPTIONS"); static QCString projectName = Config_getString("PROJECT_NAME"); static QCString projectNumber = Config_getString("PROJECT_NUMBER"); QCString cwd = QDir::currentDirPath().utf8(); if (inputSource.isEmpty()) { g_inputDir.setPath(cwd); } else if (inputSource.count()==1) { g_inputDir.setPath(inputSource.first()); if (!g_inputDir.exists()) err("error: Cannot find directory %s. " "Check the value of the INPUT tag in the configuration file.\n", inputSource.first() ); } else { err("error: If you use USE_HTAGS then INPUT should specific a single directory. \n"); return FALSE; } /* * Construct command line for htags(1). */ QCString commandLine = " -g -s -a -n "; if (!quiet) commandLine += "-v "; if (warnings) commandLine += "-w "; if (!htagsOptions.isEmpty()) { commandLine += ' '; commandLine += htagsOptions; } if (!projectName.isEmpty()) { commandLine += "-t \""; commandLine += projectName; if (!projectNumber.isEmpty()) { commandLine += '-'; commandLine += projectNumber; } commandLine += "\" "; } commandLine += " \"" + htmldir + "\""; QCString oldDir = QDir::currentDirPath().utf8(); QDir::setCurrent(g_inputDir.absPath()); //printf("CommandLine=[%s]\n",commandLine.data()); portable_sysTimerStart(); bool result=portable_system("htags",commandLine,FALSE)==0; portable_sysTimerStop(); QDir::setCurrent(oldDir); return result; }
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"); //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","Password. Default no password",false,"","string"); TCLAP::ValueArg<std::string> descriptionArg("s","description","New description for the dataset",false,"","string"); TCLAP::ValueArg<std::string> unitArg("U","units","New unit for the dataset",false,"","string"); TCLAP::ValueArg<std::string> metaArg("m","metadata","File containing metadata",false,"None","string"); //Switches TCLAP::SwitchArg remoteSwitch("r","remote","Connect to remote host", cmd, false); cmd.add(databaseArg); cmd.add(datasetArg); cmd.add(pathArg); cmd.add(hostArg); cmd.add(portArg); cmd.add(userArg); cmd.add(passArg); cmd.add(descriptionArg); cmd.add(unitArg); cmd.add(metaArg); //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 description = QString::fromUtf8(descriptionArg.getValue().c_str()); QString unit = QString::fromUtf8(unitArg.getValue().c_str()); QString meta = QString::fromUtf8(metaArg.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(); QString sql; QSqlQuery qry(mydb); sql = "SELECT dataset_desc,dataset_unit FROM datasetinfo WHERE dataset_id = '" + tableName + "'"; if (qry.exec(sql)) { if (qry.first()) { if (description.isEmpty()) description = qry.value(0).toString(); if (unit.isEmpty()) unit = qry.value(1).toString(); } else { gbtLog(QObject::tr("Dataset does not exists")); gbtLog(qry.lastError().databaseText()); mydb.close(); con.closeConnection(); return 1; } } else { gbtLog(QObject::tr("Cannot read dataset.")); gbtLog(qry.lastError().databaseText()); mydb.close(); con.closeConnection(); return 1; } sql = "UPDATE datasetinfo SET dataset_desc = '" + description + "', "; sql = sql + "dataset_unit = '" + unit + "'"; sql = sql + " WHERE dataset_id = '" + tableName + "'"; if (!qry.exec(sql)) { gbtLog(QObject::tr("Cannot update dataset.")); gbtLog(qry.lastError().databaseText()); mydb.close(); con.closeConnection(); return 1; } if (meta != "None") { if (QFile::exists(meta)) { QFile metaFile(meta); if(metaFile.open(QIODevice::ReadOnly)) { QByteArray ba; ba = metaFile.readAll(); metaFile.close(); qry.prepare("UPDATE datasetinfo SET dataset_metadata = :metafile WHERE dataset_id = '" + tableName + "'"); qry.bindValue(":metafile", ba); if (!qry.exec()) { gbtLog(QObject::tr("Cannot insert the metadata.")); gbtLog(qry.lastError().databaseText()); } qry.clear(); } else { gbtLog(QObject::tr("Cannot open the metadata file.")); gbtLog(qry.lastError().databaseText()); } } else { gbtLog(QObject::tr("The metadata file does not exits.")); gbtLog(qry.lastError().databaseText()); } } int Hours; int Minutes; int Seconds; int Milliseconds; Milliseconds = procTime.elapsed(); Hours = Milliseconds / (1000*60*60); Minutes = (Milliseconds % (1000*60*60)) / (1000*60); Seconds = ((Milliseconds % (1000*60*60)) % (1000*60)) / 1000; gbtLog("Finished in " + QString::number(Hours) + " Hours," + QString::number(Minutes) + " Minutes and " + QString::number(Seconds) + " Seconds."); mydb.close(); con.closeConnection(); return 0; } return 0; }