CC_FILE_ERROR OFFFilter::loadFile(QString filename, ccHObject& container, LoadParameters& parameters) { //try to open file QFile fp(filename); if (!fp.open(QIODevice::ReadOnly | QIODevice::Text)) return CC_FERR_READING; QTextStream stream(&fp); QString currentLine = stream.readLine(); if (!currentLine.toUpper().startsWith("OFF")) return CC_FERR_MALFORMED_FILE; //check if the number of vertices/faces/etc. are on the first line (yes it happens :( ) QStringList tokens = currentLine.split(QRegExp("\\s+"),QString::SkipEmptyParts); if (tokens.size() == 4) { tokens.removeAt(0); } else { currentLine = GetNextLine(stream); //end of file already?! if (currentLine.isNull()) return CC_FERR_MALFORMED_FILE; //read the number of vertices/faces tokens = currentLine.split(QRegExp("\\s+"),QString::SkipEmptyParts); if (tokens.size() < 2/*3*/) //should be 3 but we only use the 2 firsts... return CC_FERR_MALFORMED_FILE; } bool ok = false; unsigned vertCount = tokens[0].toUInt(&ok); if (!ok) return CC_FERR_MALFORMED_FILE; unsigned triCount = tokens[1].toUInt(&ok); if (!ok) return CC_FERR_MALFORMED_FILE; //create cloud and reserve some memory ccPointCloud* vertices = new ccPointCloud("vertices"); if (!vertices->reserve(vertCount)) { delete vertices; return CC_FERR_NOT_ENOUGH_MEMORY; } //read vertices { CCVector3d Pshift(0,0,0); for (unsigned i=0; i<vertCount; ++i) { currentLine = GetNextLine(stream); tokens = currentLine.split(QRegExp("\\s+"),QString::SkipEmptyParts); if (tokens.size() < 3) { delete vertices; return CC_FERR_MALFORMED_FILE; } //read vertex CCVector3d Pd(0,0,0); { bool vertexIsOk = false; Pd.x = tokens[0].toDouble(&vertexIsOk); if (vertexIsOk) { Pd.y = tokens[1].toDouble(&vertexIsOk); if (vertexIsOk) Pd.z = tokens[2].toDouble(&vertexIsOk); } if (!vertexIsOk) { delete vertices; return CC_FERR_MALFORMED_FILE; } } //first point: check for 'big' coordinates if (i == 0) { if (HandleGlobalShift(Pd,Pshift,parameters)) { vertices->setGlobalShift(Pshift); ccLog::Warning("[OFF] Cloud has been recentered! Translation: (%.2f,%.2f,%.2f)",Pshift.x,Pshift.y,Pshift.z); } } CCVector3 P = CCVector3::fromArray((Pd + Pshift).u); vertices->addPoint(P); } } ccMesh* mesh = new ccMesh(vertices); mesh->addChild(vertices); if (!mesh->reserve(triCount)) { delete mesh; return CC_FERR_NOT_ENOUGH_MEMORY; } //load triangles { bool ignoredPolygons = false; for (unsigned i=0; i<triCount; ++i) { currentLine = GetNextLine(stream); tokens = currentLine.split(QRegExp("\\s+"),QString::SkipEmptyParts); if (tokens.size() < 3) { delete mesh; return CC_FERR_MALFORMED_FILE; } unsigned polyVertCount = tokens[0].toUInt(&ok); if (!ok || static_cast<int>(polyVertCount) >= tokens.size()) { delete mesh; return CC_FERR_MALFORMED_FILE; } if (polyVertCount == 3 || polyVertCount == 4) { //decode indexes unsigned indexes[4]; for (unsigned j=0; j<polyVertCount; ++j) { indexes[j] = tokens[j+1].toUInt(&ok); if (!ok) { delete mesh; return CC_FERR_MALFORMED_FILE; } } //reserve memory if necessary unsigned polyTriCount = polyVertCount-2; if (mesh->size() + polyTriCount > mesh->capacity()) { if (!mesh->reserve(mesh->size() + polyTriCount + 256)) //use some margin to avoid too many allocations { delete mesh; return CC_FERR_NOT_ENOUGH_MEMORY; } } //triangle or quad only mesh->addTriangle(indexes[0],indexes[1],indexes[2]); if (polyVertCount == 4) mesh->addTriangle(indexes[0],indexes[2],indexes[3]); } else { ignoredPolygons = true; } } if (ignoredPolygons) { ccLog::Warning("[OFF] Some polygons with an unhandled size (i.e. > 4) were ignored!"); } } if (mesh->size() == 0) { ccLog::Warning("[OFF] Failed to load any polygon!"); mesh->detachChild(vertices); delete mesh; mesh = 0; container.addChild(vertices); vertices->setEnabled(true); } else { mesh->shrinkToFit(); //DGM: normals can be per-vertex or per-triangle so it's better to let the user do it himself later //Moreover it's not always good idea if the user doesn't want normals (especially in ccViewer!) //if (mesh->computeNormals()) // mesh->showNormals(true); //else // ccLog::Warning("[OFF] Failed to compute per-vertex normals..."); ccLog::Warning("[OFF] Mesh has no normal! You can manually compute them (select it then call \"Edit > Normals > Compute\")"); vertices->setEnabled(false); //vertices->setLocked(true); //DGM: no need to lock it as it is only used by one mesh! container.addChild(mesh); } return CC_FERR_NO_ERROR; }
bool MythUITextEdit::keyPressEvent(QKeyEvent *event) { m_lastKeyPress.restart(); QStringList actions; bool handled = false; handled = GetMythMainWindow()->TranslateKeyPress("Global", event, actions, false); Qt::KeyboardModifiers modifiers = event->modifiers(); int keynum = event->key(); if (keynum >= Qt::Key_Shift && keynum <= Qt::Key_CapsLock) return false; QString character; // Compose key handling // Enter composition mode if ((modifiers & Qt::GroupSwitchModifier) && (keynum >= Qt::Key_Dead_Grave) && (keynum <= Qt::Key_Dead_Horn)) { m_composeKey = keynum; handled = true; } else if (m_composeKey > 0) // 'Compose' the key { if (gDeadKeyMap.isEmpty()) LoadDeadKeys(gDeadKeyMap); LOG(VB_GUI, LOG_DEBUG, QString("Compose key: %1 Key: %2").arg(QString::number(m_composeKey, 16)).arg(QString::number(keynum, 16))); if (gDeadKeyMap.contains(keyCombo(m_composeKey, keynum))) { int keycode = gDeadKeyMap.value(keyCombo(m_composeKey, keynum)); //QKeyEvent key(QEvent::KeyPress, keycode, modifiers); character = QChar(keycode); if (modifiers & Qt::ShiftModifier) character = character.toUpper(); else character = character.toLower(); LOG(VB_GUI, LOG_DEBUG, QString("Found match for dead-key combo - %1").arg(character)); } m_composeKey = 0; } if (character.isEmpty()) character = event->text(); if (!handled && InsertCharacter(character)) handled = true; for (int i = 0; i < actions.size() && !handled; i++) { QString action = actions[i]; handled = true; if (action == "LEFT") { MoveCursor(MoveLeft); } else if (action == "RIGHT") { MoveCursor(MoveRight); } else if (action == "UP") { handled = MoveCursor(MoveUp); } else if (action == "DOWN") { handled = MoveCursor(MoveDown); } else if (action == "PAGEUP") { handled = MoveCursor(MovePageUp); } else if (action == "PAGEDOWN") { handled = MoveCursor(MovePageDown); } else if (action == "DELETE") { RemoveCharacter(m_Position + 1); } else if (action == "BACKSPACE") { RemoveCharacter(m_Position); } else if (action == "NEWLINE") { QString newmessage = m_Message; newmessage.insert(m_Position + 1, '\n'); SetText(newmessage, false); MoveCursor(MoveRight); } else if (action == "SELECT" && keynum != Qt::Key_Space && GetMythDB()->GetNumSetting("UseVirtualKeyboard", 1) == 1) { MythScreenStack *popupStack = GetMythMainWindow()->GetStack("popup stack"); MythUIVirtualKeyboard *kb = new MythUIVirtualKeyboard(popupStack, this); if (kb->Create()) { //connect(kb, SIGNAL(keyPress(QString)), SLOT(keyPress(QString))); popupStack->AddScreen(kb); } else delete kb; } else if (action == "CUT") { CutTextToClipboard(); } else if (action == "COPY") { CopyTextToClipboard(); } else if (action == "PASTE") { PasteTextFromClipboard(); } else handled = false; } return handled; }
//----------------------------------------------------------------------------- // Function: LocalMemoryMapHeaderWriter::writeMemoryMapHeader() //----------------------------------------------------------------------------- void LocalMemoryMapHeaderWriter::writeMemoryMapHeader(QList<LocalHeaderSaveModel::SaveFileOptions*> saveOptions) { saveOptions_ = saveOptions; QList<LocalHeaderSaveModel::SaveFileOptions*> options = saveOptions_; bool changed = false; LocalHeaderSaveModel model(utility_->getLibraryInterface(), parentObject_); model.setComponent(component_); if (options.isEmpty()) { FileSaveDialog dialog(utility_->getParentWidget()); dialog.setModel(&model); dialog.setItemDelegate(new LocalHeaderSaveDelegate(component_, parentObject_)); int result = dialog.exec(); // if user clicked cancel if (result == QDialog::Rejected) { informGenerationAbort(); return; } options = model.getHeaderOptions(); } informStartOfGeneration(); foreach (LocalHeaderSaveModel::SaveFileOptions* headerOpt, options) { QFile file(headerOpt->fileInfo_.absoluteFilePath()); checkDirectoryStructure(headerOpt->fileInfo_.dir()); if (!file.open(QFile::Truncate | QFile::WriteOnly)) { openFileErrorMessage(headerOpt->fileInfo_.absoluteFilePath()); break; } QTextStream stream(&file); QString description (" * Header file generated by Kactus2 from local memory map \"" + headerOpt->localMemMap_->getName() + "\".\n" + " * This file contains addresses of the memories and registers defined in the local memory map.\n" + " * Source component: " + component_->getVlnv()->toString() + ".\n" + "*/\n"); QString headerGuard ("__" + component_->getVlnv()->toString("_") + "_" + headerOpt->localMemMap_->getName() + "_H"); headerGuard = headerGuard.toUpper(); writeTopOfHeaderFile(stream, headerOpt->fileInfo_.fileName(), headerGuard, description); QSharedPointer<ComponentParameterFinder> finder (new ComponentParameterFinder(component_)); writeMemoryAddresses(finder, headerOpt->localMemMap_, stream, 0); // if the register names are unique then there is no need to add address block name QStringList regNames; if (headerOpt->localMemMap_->uniqueRegisterNames(regNames)) { writeRegisterFromMemoryMap(finder, headerOpt->localMemMap_, stream, false, 0); } else { writeRegisterFromMemoryMap(finder, headerOpt->localMemMap_, stream, true, 0); } stream << "#endif /* " << headerGuard << " */" << endl << endl; informWritingFinished(headerOpt->fileInfo_.fileName()); file.close(); QStringList swViewRefs; // where user selected to add a reference to the generated file set QString swViewRef = headerOpt->swView_; Q_ASSERT(!swViewRef.isEmpty()); // if user selected to add the reference to all SW views. if (swViewRef == QObject::tr("all")) { swViewRefs = component_->getSWViewNames(); } // if user selected only a single view else { swViewRefs.append(swViewRef); } // add the file to the component's file sets addHeaderFile(component_, headerOpt->fileInfo_, QString("%1_header").arg(headerOpt->localMemMap_->getName()), swViewRefs); // a header file was added changed = true; }
bool QHangulPlatformInputContext::filterEvent(const QEvent *event) { if (event->type() != QEvent::KeyPress) return false; const QKeyEvent *keyevent = static_cast<const QKeyEvent*>(event); if (m_candidateList != NULL && m_candidateList->isVisible()) { if (m_candidateList->filterEvent(keyevent)) { if (m_candidateList->isSelected()) { hangul_ic_reset(m_hic); QString candidate(m_candidateList->getCandidate()); commitText(candidate); } m_candidateList->close(); } return true; } if (keyevent->key() == Qt::Key_Shift) return false; if (keyevent->key() == Qt::Key_Backspace) return backspace(); if (isTriggerKey(keyevent)) { if (m_mode == MODE_DIRECT) { m_mode = MODE_HANGUL; } else { reset(); m_mode = MODE_DIRECT; } setModeInfo(m_mode); return true; } if (isCandidateKey(keyevent)) { return popupCandidateList(); } if (keyevent->modifiers() & Qt::ControlModifier || keyevent->modifiers() & Qt::AltModifier || keyevent->modifiers() & Qt::MetaModifier) { reset(); return false; } if (m_mode == MODE_HANGUL) { QString text = keyevent->text(); if (keyevent->modifiers() & Qt::ShiftModifier) text = text.toUpper(); else text = text.toLower(); int ascii = 0; if (!text.isEmpty()) ascii = text[0].unicode(); bool ret = hangul_ic_process(m_hic, ascii); QString commitString = getCommitString(); if (!commitString.isEmpty()) commitText(commitString); QString preeditString = getPreeditString(); if (!preeditString.isEmpty()) updatePreedit(preeditString); return ret; } return false; }
/**GUARDAR JUEGO*/ void sudoku::on_guardarJuego_clicked(){ timer->stop(); QString nomJugador = ui->textJugador->text(); QString nivel= ui->textNivel->text(); QString sMin = QString::number(ui->lcdmin->intValue()); QString sSeg = QString::number(ui->lcdseg->intValue()); QString sMiliseg = QString::number(ui->lcdmsg->intValue()); QString info = ""; int banderaGuardar=0; /**Actualizar la matriz*/ for(int i = 0;i < 9; i++){ for(int j = 0; j < 9; j++){ matrizGuardar[i][j] = numbertext[i][j]->toPlainText(); if(matrizGuardar[i][j] != ""){ banderaGuardar = 1;} } } if(banderaGuardar == 0){ QMessageBox::information(this, "Guardar-Sudoku", "No existen datos a GUARDAR ","ACEPTAR"); }else{ encriptarS(); for(int i=0; i<9; i++){ for(int j=0; j<9; j++){ info = info+matrizGuardar[i][j]+","; } } QString mFilemane = "guardar.txt"; QFile mFile(mFilemane); mFile.open(QIODevice::Text | QIODevice::Append); if(!mFile.isOpen()){return;} QTextStream txtstr(&mFile); txtstr << nomJugador+"/"+nivel+"/"+sMin+":"+sSeg+":"+sMiliseg+"/"+info+"\n"; mFile.flush(); mFile.close(); QMessageBox::information(this, "Guardar-Sudoku", "La partida ha sido guardada \nJUGADOR: "+nomJugador.toUpper(),"ACEPTAR"); this->close(); } }
void DeepSkyObject::setCatalog( const QString &cat ) { if ( cat.toUpper() == "M" ) Catalog = (unsigned char)CAT_MESSIER; else if ( cat.toUpper() == "NGC" ) Catalog = (unsigned char)CAT_NGC; else if ( cat.toUpper() == "IC" ) Catalog = (unsigned char)CAT_IC; else Catalog = (unsigned char)CAT_UNKNOWN; }
QSize RibbonButton::sizeHint() const { ensurePolished(); int w = 0, h = 0; QStyleOptionToolButton opt; initStyleOption(&opt); QString textButton = text(); if (!textButton.isEmpty() && (bool)style()->styleHint((QStyle::StyleHint)RibbonStyle::SH_RibbonItemUpperCase, 0, this)) textButton = textButton.toUpper(); QFontMetrics fm = fontMetrics(); if (opt.toolButtonStyle != Qt::ToolButtonTextOnly) { QSize icon = opt.iconSize; QAction* action = defaultAction(); if (action && !action->icon().isNull()) icon = action->icon().actualSize(QSize(32,32)); w = icon.width(); h = icon.height(); } bool indicatorCenter = false; QToolButton::ToolButtonPopupMode mode = QToolButton::popupMode(); if (opt.toolButtonStyle != Qt::ToolButtonIconOnly) { if (opt.toolButtonStyle == Qt::ToolButtonTextUnderIcon) { QString strFirstRow, strSecondRow; CommonStyle::splitString(textButton, strFirstRow, strSecondRow); QSize textFirstSize; if (!strFirstRow.isEmpty()) textFirstSize = fm.size(Qt::TextShowMnemonic, strFirstRow); if (!strSecondRow.isEmpty()) { QSize textSecondSize = fm.size(Qt::TextShowMnemonic, strSecondRow); textFirstSize.setWidth(qMax(textFirstSize.width(), textSecondSize.width())); } indicatorCenter = strSecondRow.isEmpty() && opt.features & QStyleOptionToolButton::HasMenu; h = style()->pixelMetric((QStyle::PixelMetric)RibbonStyle::PM_RibbonHeightGroup, 0, this); // if the text is more than icon if (textFirstSize.width() > w) w = textFirstSize.width(); // add pixel w += mode == MenuButtonPopup || mode == QToolButton::InstantPopup ? 4 : 10; } else { QSize textSize = fm.size(Qt::TextShowMnemonic, textButton); textSize.setWidth(textSize.width() + fm.width(QLatin1Char(' '))*2); h = style()->pixelMetric((QStyle::PixelMetric)RibbonStyle::PM_RibbonHeightGroup, 0, 0)/3; if (opt.toolButtonStyle == Qt::ToolButtonTextBesideIcon) { w += 3 + textSize.width(); if (mode != InstantPopup) w += 3; if (textSize.height() > h) h = textSize.height(); } else w = textSize.width() + 3; } } else { h = style()->pixelMetric((QStyle::PixelMetric)RibbonStyle::PM_RibbonHeightGroup, 0, 0)/3; w = h; } opt.rect.setSize(QSize(w, h)); // PM_MenuButtonIndicator depends on the height if ((mode== MenuButtonPopup || mode == QToolButton::InstantPopup) && !indicatorCenter) w += style()->pixelMetric(QStyle::PM_MenuButtonIndicator, &opt, this); return QSize(w, h).expandedTo(QApplication::globalStrut()); }
bool Win32MakefileGenerator::findLibraries(const QString &where) { QStringList &l = project->values(where); QList<QMakeLocalFileName> dirs; { QStringList &libpaths = project->values("QMAKE_LIBDIR"); for(QStringList::Iterator libpathit = libpaths.begin(); libpathit != libpaths.end(); ++libpathit) dirs.append(QMakeLocalFileName((*libpathit))); } for(QStringList::Iterator it = l.begin(); it != l.end();) { QChar quote; bool modified_opt = false, remove = false; QString opt = (*it).trimmed(); if((opt[0] == '\'' || opt[0] == '"') && opt[(int)opt.length()-1] == opt[0]) { quote = opt[0]; opt = opt.mid(1, opt.length()-2); } if(opt.startsWith("/LIBPATH:")) { dirs.append(QMakeLocalFileName(opt.mid(9))); } else if(opt.startsWith("-L") || opt.startsWith("/L")) { QString libpath = opt.mid(2); QMakeLocalFileName l(libpath); if(!dirs.contains(l)) { dirs.append(l); modified_opt = true; if (!quote.isNull()) { libpath = quote + libpath + quote; quote = QChar(); } (*it) = "/LIBPATH:" + libpath; } else { remove = true; } } else if(opt.startsWith("-l") || opt.startsWith("/l")) { QString lib = opt.right(opt.length() - 2), out; if(!lib.isEmpty()) { QString suffix; if(!project->isEmpty("QMAKE_" + lib.toUpper() + "_SUFFIX")) suffix = project->first("QMAKE_" + lib.toUpper() + "_SUFFIX"); for(QList<QMakeLocalFileName>::Iterator it = dirs.begin(); it != dirs.end(); ++it) { QString extension; int ver = findHighestVersion((*it).local(), lib); if(ver > 0) extension += QString::number(ver); extension += suffix; extension += ".lib"; if(QMakeMetaInfo::libExists((*it).local() + Option::dir_sep + lib) || exists((*it).local() + Option::dir_sep + lib + extension)) { out = (*it).real() + Option::dir_sep + lib + extension; break; } } } if(out.isEmpty()) out = lib + ".lib"; modified_opt = true; (*it) = out; } else if(!exists(Option::fixPathToLocalOS(opt))) { QList<QMakeLocalFileName> lib_dirs; QString file = opt; int slsh = file.lastIndexOf(Option::dir_sep); if(slsh != -1) { lib_dirs.append(QMakeLocalFileName(file.left(slsh+1))); file = file.right(file.length() - slsh - 1); } else { lib_dirs = dirs; } if(file.endsWith(".lib")) { file = file.left(file.length() - 4); if(!file.at(file.length()-1).isNumber()) { QString suffix; if(!project->isEmpty("QMAKE_" + file.section(Option::dir_sep, -1).toUpper() + "_SUFFIX")) suffix = project->first("QMAKE_" + file.section(Option::dir_sep, -1).toUpper() + "_SUFFIX"); for(QList<QMakeLocalFileName>::Iterator dep_it = lib_dirs.begin(); dep_it != lib_dirs.end(); ++dep_it) { QString lib_tmpl(file + "%1" + suffix + ".lib"); int ver = findHighestVersion((*dep_it).local(), file); if(ver != -1) { if(ver) lib_tmpl = lib_tmpl.arg(ver); else lib_tmpl = lib_tmpl.arg(""); if(slsh != -1) { QString dir = (*dep_it).real(); if(!dir.endsWith(Option::dir_sep)) dir += Option::dir_sep; lib_tmpl.prepend(dir); } modified_opt = true; (*it) = lib_tmpl; break; } } } } } if(remove) { it = l.erase(it); } else { if(!quote.isNull() && modified_opt) (*it) = quote + (*it) + quote; ++it; } } return true; }
ccHObject* FileIOFilter::LoadFromFile(const QString& filename, CC_FILE_TYPES fType, bool alwaysDisplayLoadDialog/*=true*/, bool* coordinatesShiftEnabled/*=0*/, CCVector3d* coordinatesShift/*=0*/) { //check file existence QFileInfo fi(filename); if (!fi.exists()) { ccLog::Error(QString("[Load] File '%1' doesn't exist!").arg(filename)); return 0; } //do we need to guess file format? if (fType == UNKNOWN_FILE) { //look for file extension (we trust Qt on this task) QString extension = QFileInfo(filename).suffix(); if (extension.isEmpty()) { ccLog::Error("[Load] Can't guess file format: no file extension"); return 0; } //convert extension to file format fType = GuessFileFormatFromExtension(qPrintable(extension.toUpper())); //unknown extension? if (fType == UNKNOWN_FILE) { ccLog::Error(QString("[Load] Can't guess file format: unknown file extension '%1'").arg(extension)); return 0; } } //get corresponding loader FileIOFilter* fio = CreateFilter(fType); if (!fio) return 0; //load file ccHObject* container = new ccHObject(); CC_FILE_ERROR result = CC_FERR_NO_ERROR; try { result = fio->loadFile( qPrintable(filename), *container, alwaysDisplayLoadDialog, coordinatesShiftEnabled, coordinatesShift); } catch(...) { ccLog::Warning("[I/O] Exception caught during file opening!"); if (container) container->removeAllChildren(); result = CC_FERR_CONSOLE_ERROR; } //we can release the loader instance delete fio; fio = 0; if (result != CC_FERR_NO_ERROR) DisplayErrorMessage(result,"loading",fi.baseName()); else ccLog::Print(QString("[I/O] File '%1' loaded successfully").arg(fi.baseName())); unsigned childrenCount = container->getChildrenNumber(); if (childrenCount != 0) { //we set the main container name as the full filename (with path) container->setName(QString("%1 (%2)").arg(fi.fileName()).arg(fi.absolutePath())); for (unsigned i=0;i<childrenCount;++i) { ccHObject* child = container->getChild(i); QString newName = child->getName(); if (newName.startsWith("unnamed")) { //we automatically replace occurences of 'unnamed' in entities names by the base filename (no path, no extension) newName.replace(QString("unnamed"),fi.baseName()); child->setName(newName); } } } else { delete container; container = 0; } return container; }
int main(int argc, char *argv[]) { //See http://doc.qt.io/qt-5/qopenglwidget.html#opengl-function-calls-headers-and-qopenglfunctions /** Calling QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance is mandatory on some platforms (for example, OS X) when an OpenGL core profile context is requested. This is to ensure that resource sharing between contexts stays functional as all internal contexts are created using the correct version and profile. **/ { QSurfaceFormat format = QSurfaceFormat::defaultFormat(); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); format.setStencilBufferSize(0); #ifdef CC_GL_WINDOW_USE_QWINDOW format.setStereo(true); #endif #ifdef Q_OS_MAC format.setStereo(false); format.setVersion( 2, 1 ); format.setProfile( QSurfaceFormat::CoreProfile ); #endif #ifdef QT_DEBUG format.setOption(QSurfaceFormat::DebugContext); #endif QSurfaceFormat::setDefaultFormat(format); } ccApplication a(argc, argv); //Locale management { //Force 'english' locale so as to get a consistent behavior everywhere QLocale locale = QLocale(QLocale::English); locale.setNumberOptions(QLocale::c().numberOptions()); QLocale::setDefault(locale); #ifdef Q_OS_UNIX //We reset the numeric locale for POSIX functions //See http://qt-project.org/doc/qt-5/qcoreapplication.html#locale-settings setlocale(LC_NUMERIC, "C"); #endif } #ifdef USE_VLD VLDEnable(); #endif #ifdef Q_OS_MAC // This makes sure that our "working directory" is not within the application bundle QDir appDir = QCoreApplication::applicationDirPath(); if ( appDir.dirName() == "MacOS" ) { appDir.cdUp(); appDir.cdUp(); appDir.cdUp(); QDir::setCurrent( appDir.absolutePath() ); } #endif if (!QGLFormat::hasOpenGL()) { QMessageBox::critical(0, "Error", "This application needs OpenGL to run!"); return EXIT_FAILURE; } if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_1) == 0) { QMessageBox::critical(0, "Error", "This application needs OpenGL 2.1 at least to run!"); return EXIT_FAILURE; } //common data initialization FileIOFilter::InitInternalFilters(); //load all known I/O filters (plugins will come later!) ccNormalVectors::GetUniqueInstance(); //force pre-computed normals array initialization ccColorScalesManager::GetUniqueInstance(); //force pre-computed color tables initialization ccViewer w/*(0,Qt::Window|Qt::CustomizeWindowHint)*/; #ifdef Q_OS_MAC a.setViewer( &w ); #endif //register minimal logger to display errors ccViewerLog logger(&w); ccLog::RegisterInstance(&logger); w.show(); //files to open are passed as argument if (argc > 1) { //parse arguments QStringList filenames; int i = 1; while ( i < argc) { QString argument = QString(argv[i++]).toUpper(); //Argument '-WIN X Y W H' (to set window size and position) if (argument.toUpper() == "-WIN") { bool ok = true; if (i+3 < argc) { bool converionOk; int x = QString(argv[i ]).toInt(&converionOk); ok &= converionOk; int y = QString(argv[i+1]).toInt(&converionOk); ok &= converionOk; int width = QString(argv[i+2]).toInt(&converionOk); ok &= converionOk; int height = QString(argv[i+3]).toInt(&converionOk); ok &= converionOk; i += 4; if (ok) { //change window position and size w.move(x,y); w.resize(width,height); } } if (!ok) { ccLog::Warning("Invalid arguments! 4 integer values are expected after '-win' (X Y W H)"); break; } } else if (argument == "-TOP") { w.setWindowFlags(w.windowFlags() | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint); w.show(); } else //any other argument is assumed to be a filename (that will we try to load) { filenames << argument; } } if (!filenames.empty()) w.addToDB(filenames); } #ifdef Q_OS_MAC // process events to load any files on the command line QCoreApplication::processEvents(); #endif w.checkForLoadedEntities(); int result = a.exec(); //release global structures FileIOFilter::UnregisterAll(); return result; }
QT_BEGIN_NAMESPACE /*! \class QUuid \brief The QUuid class stores a Universally Unique Identifier (UUID). \reentrant \ingroup misc Using \e{U}niversally \e{U}nique \e{ID}entifiers (UUID) is a standard way to uniquely identify entities in a distributed computing environment. A UUID is a 16-byte (128-bit) number generated by some algorithm that is meant to guarantee that the UUID will be unique in the distributed computing environment where it is used. The acronym GUID is often used instead, \e{G}lobally \e{U}nique \e{ID}entifiers, but it refers to the same thing. \target Variant field Actually, the GUID is one \e{variant} of UUID. Multiple variants are in use. Each UUID contains a bit field that specifies which type (variant) of UUID it is. Call variant() to discover which type of UUID an instance of QUuid contains. It extracts the three most signifcant bits of byte 8 of the 16 bytes. In QUuid, byte 8 is \c{QUuid::data4[0]}. If you create instances of QUuid using the constructor that accepts all the numeric values as parameters, use the following table to set the three most significant bits of parameter \c{b1}, which becomes \c{QUuid::data4[0]} and contains the variant field in its three most significant bits. In the table, 'x' means \e {don't care}. \table \header \o msb0 \o msb1 \o msb2 \o Variant \row \o 0 \o x \o x \o NCS (Network Computing System) \row \o 1 \o 0 \o x \o DCE (Distributed Computing Environment) \row \o 1 \o 1 \o 0 \o Microsoft (GUID) \row \o 1 \o 1 \o 1 \o Reserved for future expansion \endtable \target Version field If variant() returns QUuid::DCE, the UUID also contains a \e{version} field in the four most significant bits of \c{QUuid::data3}, and you can call version() to discover which version your QUuid contains. If you create instances of QUuid using the constructor that accepts all the numeric values as parameters, use the following table to set the four most significant bits of parameter \c{w2}, which becomes \c{QUuid::data3} and contains the version field in its four most significant bits. \table \header \o msb0 \o msb1 \o msb2 \o msb3 \o Version \row \o 0 \o 0 \o 0 \o 1 \o Time \row \o 0 \o 0 \o 1 \o 0 \o Embedded POSIX \row \o 0 \o 0 \o 1 \o 1 \o Name \row \o 0 \o 1 \o 0 \o 0 \o Random \endtable The field layouts for the DCE versions listed in the table above are specified in the \l{http://www.ietf.org/rfc/rfc4122.txt} {Network Working Group UUID Specification}. Most platforms provide a tool for generating new UUIDs, e.g. \c uuidgen and \c guidgen. You can also use createUuid(). UUIDs generated by createUuid() are of the random type. Their QUuid::Version bits are set to QUuid::Random, and their QUuid::Variant bits are set to QUuid::DCE. The rest of the UUID is composed of random numbers. Theoretically, this means there is a small chance that a UUID generated by createUuid() will not be unique. But it is \l{http://en.wikipedia.org/wiki/Universally_Unique_Identifier#Random_UUID_probability_of_duplicates} {a \e{very} small chance}. UUIDs can be constructed from numeric values or from strings, or using the static createUuid() function. They can be converted to a string with toString(). UUIDs have a variant() and a version(), and null UUIDs return true from isNull(). */ /*! \fn QUuid::QUuid(const GUID &guid) Casts a Windows \a guid to a Qt QUuid. \warning This function is only for Windows platforms. */ /*! \fn QUuid &QUuid::operator=(const GUID &guid) Assigns a Windows \a guid to a Qt QUuid. \warning This function is only for Windows platforms. */ /*! \fn QUuid::operator GUID() const Returns a Windows GUID from a QUuid. \warning This function is only for Windows platforms. */ /*! \fn QUuid::QUuid() Creates the null UUID. toString() will output the null UUID as "{00000000-0000-0000-0000-000000000000}". */ /*! \fn QUuid::QUuid(uint l, ushort w1, ushort w2, uchar b1, uchar b2, uchar b3, uchar b4, uchar b5, uchar b6, uchar b7, uchar b8) Creates a UUID with the value specified by the parameters, \a l, \a w1, \a w2, \a b1, \a b2, \a b3, \a b4, \a b5, \a b6, \a b7, \a b8. Example: \snippet doc/src/snippets/code/src_corelib_plugin_quuid.cpp 0 */ #ifndef QT_NO_QUUID_STRING /*! Creates a QUuid object from the string \a text, which must be formatted as five hex fields separated by '-', e.g., "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" where 'x' is a hex digit. The curly braces shown here are optional, but it is normal to include them. If the conversion fails, a null UUID is created. See toString() for an explanation of how the five hex fields map to the public data members in QUuid. \sa toString(), QUuid() */ QUuid::QUuid(const QString &text) { bool ok; if (text.isEmpty()) { *this = QUuid(); return; } QString temp = text.toUpper(); if (temp[0] != QLatin1Char('{')) temp = QLatin1Char('{') + text; if (text[(int)text.length()-1] != QLatin1Char('}')) temp += QLatin1Char('}'); data1 = temp.mid(1, 8).toULongLong(&ok, 16); if (!ok) { *this = QUuid(); return; } data2 = temp.mid(10, 4).toUInt(&ok, 16); if (!ok) { *this = QUuid(); return; } data3 = temp.mid(15, 4).toUInt(&ok, 16); if (!ok) { *this = QUuid(); return; } data4[0] = temp.mid(20, 2).toUInt(&ok, 16); if (!ok) { *this = QUuid(); return; } data4[1] = temp.mid(22, 2).toUInt(&ok, 16); if (!ok) { *this = QUuid(); return; } for (int i = 2; i<8; i++) { data4[i] = temp.mid(25 + (i-2)*2, 2).toUShort(&ok, 16); if (!ok) { *this = QUuid(); return; } } }
zigbus::ZigbusSubType zigbus::convertStrToSubType(const QString &str) { if(str.toUpper() == "DHT11") return zigbus::stype_DHT11; else if(str.toUpper() == "LM35DZ") return zigbus::stype_LM35DZ; else return zigbus::stype_UNDEF; }
QString UnixMakefileGenerator::defaultInstall(const QString &t) { if(t != "target" || project->first("TEMPLATE") == "subdirs") return QString(); bool bundle = false; const QString root = "$(INSTALL_ROOT)"; QStringList &uninst = project->values(t + ".uninstall"); QString ret, destdir=project->first("DESTDIR"); QString targetdir = Option::fixPathToTargetOS(project->first("target.path"), false); if(!destdir.isEmpty() && destdir.right(1) != Option::dir_sep) destdir += Option::dir_sep; targetdir = fileFixify(targetdir, FileFixifyAbsolute); if(targetdir.right(1) != Option::dir_sep) targetdir += Option::dir_sep; QStringList links; QString target="$(TARGET)"; QStringList &targets = project->values(t + ".targets"); if(!project->isEmpty("QMAKE_BUNDLE")) { target = project->first("QMAKE_BUNDLE"); bundle = true; } else if(project->first("TEMPLATE") == "app") { target = "$(QMAKE_TARGET)"; if(!project->isEmpty("QMAKE_CYGWIN_EXE") && !target.endsWith(".exe")) target += ".exe"; } else if(project->first("TEMPLATE") == "lib") { if(!project->isActiveConfig("staticlib") && !project->isActiveConfig("plugin")) { if(project->isEmpty("QMAKE_HPUX_SHLIB") && project->isEmpty("QMAKE_CYGWIN_SHLIB")) { links << "$(TARGET0)" << "$(TARGET1)" << "$(TARGET2)"; } else { links << "$(TARGET0)"; } } } for(int i = 0; i < targets.size(); ++i) { QString src = targets.at(i), dst = filePrefixRoot(root, targetdir + src.section('/', -1)); if(!ret.isEmpty()) ret += "\n\t"; ret += "-$(INSTALL_FILE) \"" + src + "\" \"" + dst + "\""; if(!uninst.isEmpty()) uninst.append("\n\t"); uninst.append("-$(DEL_FILE) \"" + dst + "\""); } if(!bundle && project->isActiveConfig("compile_libtool")) { QString src_targ = target; if(src_targ == "$(TARGET)") src_targ = "$(TARGETL)"; QString dst_dir = fileFixify(targetdir, FileFixifyAbsolute); if(QDir::isRelativePath(dst_dir)) dst_dir = Option::fixPathToTargetOS(Option::output_dir + Option::dir_sep + dst_dir); ret = "-$(LIBTOOL) --mode=install cp \"" + src_targ + "\" \"" + filePrefixRoot(root, dst_dir) + "\""; uninst.append("-$(LIBTOOL) --mode=uninstall \"" + src_targ + "\""); } else { QString src_targ = target; if(!destdir.isEmpty()) src_targ = Option::fixPathToTargetOS(destdir + target, false); QString dst_targ = filePrefixRoot(root, fileFixify(targetdir + target, FileFixifyAbsolute)); if(bundle) { if(!ret.isEmpty()) ret += "\n\t"; ret += "$(DEL_FILE) -r \"" + dst_targ + "\"\n\t"; } if(!ret.isEmpty()) ret += "\n\t"; QString copy_cmd("-"); if (bundle) copy_cmd += "$(INSTALL_DIR)"; else if (project->first("TEMPLATE") == "lib" && project->isActiveConfig("staticlib")) copy_cmd += "$(INSTALL_FILE)"; else copy_cmd += "$(INSTALL_PROGRAM)"; copy_cmd += " \"" + src_targ + "\" \"" + dst_targ + "\""; if(project->first("TEMPLATE") == "lib" && !project->isActiveConfig("staticlib") && project->values(t + ".CONFIG").indexOf("fix_rpath") != -1) { if(!project->isEmpty("QMAKE_FIX_RPATH")) { ret += copy_cmd; ret += "\n\t-" + var("QMAKE_FIX_RPATH") + " \"" + dst_targ + "\" \"" + dst_targ + "\""; } else if(!project->isEmpty("QMAKE_LFLAGS_RPATH")) { ret += "-$(LINK) $(LFLAGS) " + var("QMAKE_LFLAGS_RPATH") + targetdir + " -o \"" + dst_targ + "\" $(OBJECTS) $(LIBS) $(OBJCOMP)"; } else { ret += copy_cmd; } } else { ret += copy_cmd; } if(project->first("TEMPLATE") == "lib" && project->isActiveConfig("staticlib")) { if(!project->isEmpty("QMAKE_RANLIB")) ret += QString("\n\t$(RANLIB) \"") + dst_targ + "\""; } else if(!project->isActiveConfig("debug") && !project->isActiveConfig("nostrip") && !project->isEmpty("QMAKE_STRIP")) { ret += "\n\t-$(STRIP)"; if(project->first("TEMPLATE") == "lib" && !project->isEmpty("QMAKE_STRIPFLAGS_LIB")) ret += " " + var("QMAKE_STRIPFLAGS_LIB"); else if(project->first("TEMPLATE") == "app" && !project->isEmpty("QMAKE_STRIPFLAGS_APP")) ret += " " + var("QMAKE_STRIPFLAGS_APP"); if(bundle) ret = " \"" + dst_targ + "/Contents/MacOS/$(QMAKE_TARGET)\""; else ret += " \"" + dst_targ + "\""; } if(!uninst.isEmpty()) uninst.append("\n\t"); if(bundle) uninst.append("-$(DEL_FILE) -r \"" + dst_targ + "\""); else uninst.append("-$(DEL_FILE) \"" + dst_targ + "\""); if(!links.isEmpty()) { for(int i = 0; i < links.size(); ++i) { if(Option::target_mode == Option::TARG_UNIX_MODE || Option::target_mode == Option::TARG_MACX_MODE) { QString link = Option::fixPathToTargetOS(destdir + links[i], false); int lslash = link.lastIndexOf(Option::dir_sep); if(lslash != -1) link = link.right(link.length() - (lslash + 1)); QString dst_link = filePrefixRoot(root, fileFixify(targetdir + link, FileFixifyAbsolute)); if(project->isEmpty("QMAKE_CYGWIN_SHLIB")) ret += "\n\t-$(SYMLINK) \"$(TARGET)\" \"" + dst_link + "\""; else ret += "\n\t-$(INSTALL_FILE) \"" + destdir + "$(TARGET0)\" \"" + dst_link + "\""; if(!uninst.isEmpty()) uninst.append("\n\t"); uninst.append("-$(DEL_FILE) \"" + dst_link + "\""); } } } } if(project->first("TEMPLATE") == "lib") { QStringList types; types << "prl" << "libtool" << "pkgconfig"; for(int i = 0; i < types.size(); ++i) { const QString type = types.at(i); QString meta; if(type == "prl" && project->isActiveConfig("create_prl") && !project->isActiveConfig("no_install_prl") && !project->isEmpty("QMAKE_INTERNAL_PRL_FILE")) meta = prlFileName(false); if(type == "libtool" && project->isActiveConfig("create_libtool") && !project->isActiveConfig("compile_libtool")) meta = libtoolFileName(false); if(type == "pkgconfig" && project->isActiveConfig("create_pc")) meta = pkgConfigFileName(false); if(!meta.isEmpty()) { QString src_meta = meta; if(!destdir.isEmpty()) src_meta = Option::fixPathToTargetOS(destdir + meta, false); QString dst_meta = filePrefixRoot(root, fileFixify(targetdir + meta, FileFixifyAbsolute)); if(!uninst.isEmpty()) uninst.append("\n\t"); uninst.append("-$(DEL_FILE) \"" + dst_meta + "\""); const QString replace_rule("QMAKE_" + type.toUpper() + "_INSTALL_REPLACE"); const QString dst_meta_dir = fileInfo(dst_meta).path(); if(!dst_meta_dir.isEmpty()) { if(!ret.isEmpty()) ret += "\n\t"; ret += mkdir_p_asstring(dst_meta_dir, true); } QString install_meta = "$(INSTALL_FILE) \"" + src_meta + "\" \"" + dst_meta + "\""; if(project->isEmpty(replace_rule) || project->isActiveConfig("no_sed_meta_install")) { if(!ret.isEmpty()) ret += "\n\t"; ret += "-" + install_meta; } else { if(!ret.isEmpty()) ret += "\n\t"; ret += "-$(SED)"; QStringList replace_rules = project->values(replace_rule); for(int r = 0; r < replace_rules.size(); ++r) { const QString match = project->first(replace_rules.at(r) + ".match"), replace = project->first(replace_rules.at(r) + ".replace"); if(!match.isEmpty() /*&& match != replace*/) ret += " -e \"s," + match + "," + replace + ",g\""; } ret += " \"" + src_meta + "\" >\"" + dst_meta + "\""; //ret += " || " + install_meta; } } } } return ret; }
void UnixMakefileGenerator::processPrlFiles() { QList<QMakeLocalFileName> libdirs, frameworkdirs; frameworkdirs.append(QMakeLocalFileName("/System/Library/Frameworks")); const QString lflags[] = { "QMAKE_LIBDIR_FLAGS", "QMAKE_FRAMEWORKPATH_FLAGS", "QMAKE_LFLAGS", "QMAKE_LIBS", QString() }; for(int i = 0; !lflags[i].isNull(); i++) { QStringList &l = project->values(lflags[i]); for(int lit = 0; lit < l.size(); ++lit) { QString opt = l.at(lit).trimmed(); if(opt.startsWith("-")) { if(opt.startsWith("-L")) { QMakeLocalFileName l(opt.right(opt.length()-2)); if(!libdirs.contains(l)) libdirs.append(l); } else if(opt.startsWith("-l")) { QString lib = opt.right(opt.length() - 2); for(int dep_i = 0; dep_i < libdirs.size(); ++dep_i) { const QMakeLocalFileName &lfn = libdirs[dep_i]; if(!project->isActiveConfig("compile_libtool")) { //give them the .libs.. QString la = lfn.local() + Option::dir_sep + project->values("QMAKE_PREFIX_SHLIB").first() + lib + Option::libtool_ext; if(exists(la) && QFile::exists(lfn.local() + Option::dir_sep + ".libs")) { QString dot_libs = lfn.real() + Option::dir_sep + ".libs"; l.append("-L" + dot_libs); libdirs.append(QMakeLocalFileName(dot_libs)); } } QString prl = lfn.local() + Option::dir_sep + project->values("QMAKE_PREFIX_SHLIB").first() + lib; if(!project->isEmpty("QMAKE_" + lib.toUpper() + "_SUFFIX")) prl += project->first("QMAKE_" + lib.toUpper() + "_SUFFIX"); if(processPrlFile(prl)) { if(prl.startsWith(lfn.local())) prl.replace(0, lfn.local().length(), lfn.real()); opt = linkLib(prl, lib); break; } } } else if(Option::target_mode == Option::TARG_MACX_MODE && opt.startsWith("-F")) { QMakeLocalFileName f(opt.right(opt.length()-2)); if(!frameworkdirs.contains(f)) frameworkdirs.append(f); } else if(Option::target_mode == Option::TARG_MACX_MODE && opt.startsWith("-framework")) { if(opt.length() > 11) opt = opt.mid(11); else opt = l.at(++lit); opt = opt.trimmed(); const QList<QMakeLocalFileName> dirs = frameworkdirs + libdirs; for(int dep_i = 0; dep_i < dirs.size(); ++dep_i) { QString prl = dirs[dep_i].local() + "/" + opt + ".framework/" + opt + Option::prl_ext; if(processPrlFile(prl)) break; } } } else if(!opt.isNull()) { QString lib = opt; processPrlFile(lib); #if 0 if(ret) opt = linkLib(lib, ""); #endif if(!opt.isEmpty()) l.replaceInStrings(lib, opt); } QStringList &prl_libs = project->values("QMAKE_CURRENT_PRL_LIBS"); if(!prl_libs.isEmpty()) { for(int prl = 0; prl < prl_libs.size(); ++prl) l.insert(lit+prl+1, prl_libs.at(prl)); prl_libs.clear(); } } //merge them into a logical order if(!project->isActiveConfig("no_smart_library_merge") && !project->isActiveConfig("no_lflags_merge")) { QHash<QString, QStringList> lflags; for(int lit = 0; lit < l.size(); ++lit) { QString arch("default"); QString opt = l.at(lit).trimmed(); if(opt.startsWith("-")) { if (Option::target_mode == Option::TARG_MACX_MODE && opt.startsWith("-Xarch")) { if (opt.length() > 7) { arch = opt.mid(7); opt = l.at(++lit); } } if(opt.startsWith("-L") || (Option::target_mode == Option::TARG_MACX_MODE && opt.startsWith("-F"))) { if(!lflags[arch].contains(opt)) lflags[arch].append(opt); } else if(opt.startsWith("-l") || opt == "-pthread") { // Make sure we keep the dependency-order of libraries if (lflags[arch].contains(opt)) lflags[arch].removeAll(opt); lflags[arch].append(opt); } else if(Option::target_mode == Option::TARG_MACX_MODE && opt.startsWith("-framework")) { if(opt.length() > 11) opt = opt.mid(11); else { opt = l.at(++lit); if (Option::target_mode == Option::TARG_MACX_MODE && opt.startsWith("-Xarch")) opt = l.at(++lit); // The user has done the right thing and prefixed each part } bool found = false; for(int x = 0; x < lflags[arch].size(); ++x) { QString xf = lflags[arch].at(x); if(xf.startsWith("-framework")) { QString framework; if(xf.length() > 11) framework = xf.mid(11); else framework = lflags[arch].at(++x); if(framework == opt) { found = true; break; } } } if(!found) { lflags[arch].append("-framework"); lflags[arch].append(opt); } } else { lflags[arch].append(opt); } } else if(!opt.isNull()) { if(!lflags[arch].contains(opt)) lflags[arch].append(opt); } } l = lflags.take("default"); // Process architecture specific options (Xarch) QHash<QString, QStringList>::const_iterator archIterator = lflags.constBegin(); while (archIterator != lflags.constEnd()) { const QStringList archOptions = archIterator.value(); for (int i = 0; i < archOptions.size(); ++i) { l.append(QLatin1String("-Xarch_") + archIterator.key()); l.append(archOptions.at(i)); } ++archIterator; } } } }
//----------------------------------------------------------------------------- bool Server::getService(IBPP::Service& svc, ProgressIndicator* progressind, bool sysdba) { if (progressind) { progressind->initProgress(_("Connecting..."), databasesM.size() + 2, 0, 1); } // check if we already had some successful connections if (!serviceSysdbaPasswordM.isEmpty()) // we have sysdba pass { if (progressind) { progressind->setProgressMessage(_("Using current SYSDBA password")); progressind->stepProgress(); } try { svc = IBPP::ServiceFactory(wx2std(getConnectionString()), "SYSDBA", wx2std(serviceSysdbaPasswordM)); svc->Connect(); return true; } catch(IBPP::Exception&) // keep going if connect fails { serviceSysdbaPasswordM.clear(); } } if (progressind && progressind->isCanceled()) return false; // check if we have non-sysdba connection if (!sysdba && !serviceUserM.isEmpty()) { if (progressind) { progressind->setProgressMessage(QString::fromLatin1("Using current %1 password") .arg(serviceUserM)); progressind->stepProgress(); } try { svc = IBPP::ServiceFactory(wx2std(getConnectionString()), wx2std(serviceUserM), wx2std(servicePasswordM)); svc->Connect(); return true; } catch(IBPP::Exception&) // keep going if connect fails { serviceUserM.clear(); servicePasswordM.clear(); } } // first try connected databases for (DatabasePtrs::iterator ci = databasesM.begin(); ci != databasesM.end(); ++ci) { if (progressind && progressind->isCanceled()) return false; if (!(*ci)->isConnected()) continue; // Use the user name and password of the connected user // instead of the stored ones. IBPP::Database& db = (*ci)->getIBPPDatabase(); if (sysdba && std2wx(db->Username()).toUpper() != QString::fromLatin1("SYSDBA")) continue; if (progressind) { progressind->setProgressMessage(_("Using password of: ") + std2wx(db->Username()) + QString::fromLatin1("@") + (*ci)->getName_()); progressind->stepProgress(); } try { svc = IBPP::ServiceFactory(wx2std(getConnectionString()), db->Username(), db->UserPassword()); svc->Connect(); if (sysdba) serviceSysdbaPasswordM = std2wx(db->UserPassword()); else { serviceUserM = std2wx(db->Username()); servicePasswordM = std2wx(db->UserPassword()); } return true; } catch(IBPP::Exception&) // keep going if connect fails { } } // when the operation is not canceled try to user/pass of disconnected DBs for (DatabasePtrs::const_iterator ci = databasesM.begin(); ci != databasesM.end(); ++ci) { if (progressind && progressind->isCanceled()) return false; if ((*ci)->isConnected()) continue; QString user = (*ci)->getUsername(); QString pwd = (*ci)->getDecryptedPassword(); if (pwd.isEmpty() || sysdba && user.toUpper() != QString::fromLatin1("SYSDBA")) continue; if (progressind) { progressind->setProgressMessage(_("Using password of: ") + user + QString::fromLatin1("@") + (*ci)->getName_()); progressind->stepProgress(); } try { svc = IBPP::ServiceFactory(wx2std(getConnectionString()), wx2std(user), wx2std(pwd)); svc->Connect(); if (sysdba) serviceSysdbaPasswordM = pwd; else { serviceUserM = user; servicePasswordM = pwd; } return true; } catch(IBPP::Exception&) // keep going if connect fails { } } return false; }
int file_transform::dotransform_marker(V3DPluginCallback2 &callback, QWidget *parent) { //input file name QString fileOpenName; fileOpenName = QFileDialog::getOpenFileName(0, QObject::tr("Open marker File"), "", QObject::tr("Supported file (*.marker)" ";;Marker file (*.marker)" )); if(fileOpenName.isEmpty()) return 0; QList <ImageMarker> inmarker; if (fileOpenName.toUpper().endsWith(".MARKER")) { inmarker = readMarker_file(fileOpenName); } QString fileMatName = QFileDialog::getOpenFileName(0, QObject::tr("Open Affine Matrix File"), "", QObject::tr("Supported file (*.txt)" ";;Affine Matrix (*.txt)" )); if(fileMatName.isEmpty()) return 0; double afmatrix[16]={0}; if (!readAmat(fileMatName.toStdString().c_str(),afmatrix)) { v3d_msg("error read affine transform matrix."); return 0; } //marker affine double x,y,z; for(V3DLONG i=0; i<inmarker.size() ; i++) { ImageMarker* tp = &(inmarker[i]); x = afmatrix[0] * tp->x + afmatrix[1] * tp->y + afmatrix[2] * tp->z + afmatrix[3]; y = afmatrix[4] * tp->x + afmatrix[5] * tp->y + afmatrix[6] * tp->z + afmatrix[7]; z = afmatrix[8] * tp->x + afmatrix[9] * tp->y + afmatrix[10] * tp->z + afmatrix[11]; //now update tp->x = x; tp->y = y; tp->z = z; } QString fileDefaultName = fileOpenName+QString("_affine.marker"); //write new marker to file QString fileSaveName = QFileDialog::getSaveFileName(0, QObject::tr("Save File"), fileDefaultName, QObject::tr("Supported file (*.marker)" ";;Marker (*.marker)" )); if(fileSaveName.isEmpty()) return 0; if (!writeMarker_file(fileSaveName, inmarker)) { v3d_msg("fail to write the output marker file."); return 0; } return 1; }
/*! Creates a declaration (header file) for the form given in \a e \sa createFormImpl() */ void Ui3Reader::createFormDecl(const QDomElement &e) { QDomElement body = e; QDomElement n; QDomNodeList nl; int i; QString objClass = getClassName(e); if (objClass.isEmpty()) return; QString objName = getObjectName(e); QStringList typeDefs; QMap<QString, CustomInclude> customWidgetIncludes; /* We are generating a few QImage members that are not strictly necessary in some cases. Ideally, we would use requiredImage, which is computed elsewhere, to keep the generated .h and .cpp files synchronized. */ // at first the images QMap<QString, int> customWidgets; QStringList forwardDecl; QStringList forwardDecl2; for (n = e; !n.isNull(); n = n.nextSibling().toElement()) { if (n.tagName().toLower() == QLatin1String("customwidgets")) { QDomElement n2 = n.firstChild().toElement(); while (!n2.isNull()) { if (n2.tagName().toLower() == QLatin1String("customwidget")) { QDomElement n3 = n2.firstChild().toElement(); QString cl; while (!n3.isNull()) { QString tagName = n3.tagName().toLower(); if (tagName == QLatin1String("class")) { cl = n3.firstChild().toText().data(); if (m_options & CustomWidgetForwardDeclarations) forwardDecl << cl; customWidgets.insert(cl, 0); } else if (tagName == QLatin1String("header")) { CustomInclude ci; ci.header = n3.firstChild().toText().data(); ci.location = n3.attribute(QLatin1String("location"), QLatin1String("global")); if (!ci.header.isEmpty()) forwardDecl.removeAll(cl); customWidgetIncludes.insert(cl, ci); } n3 = n3.nextSibling().toElement(); } } n2 = n2.nextSibling().toElement(); } } } // register the object and unify its name objName = registerObject(objName); QString protector = objName.toUpper() + QLatin1String("_H"); protector.replace(QLatin1String("::"), QLatin1String("_")); out << "#ifndef " << protector << endl; out << "#define " << protector << endl; out << endl; out << "#include <qvariant.h>" << endl; // for broken HP-UX compilers QStringList globalIncludes, localIncludes; { QMap<QString, CustomInclude>::Iterator it = customWidgetIncludes.find(objClass); if (it != customWidgetIncludes.end()) { if ((*it).location == QLatin1String("global")) globalIncludes += (*it).header; else localIncludes += (*it).header; } } QStringList::ConstIterator it; globalIncludes = unique(globalIncludes); for (it = globalIncludes.constBegin(); it != globalIncludes.constEnd(); ++it) { if (!(*it).isEmpty()) { QString header = fixHeaderName(*it); out << "#include <" << header << '>' << endl; } } localIncludes = unique(localIncludes); for (it = localIncludes.constBegin(); it != localIncludes.constEnd(); ++it) { if (!(*it).isEmpty()) { QString header = fixHeaderName(*it); out << "#include \"" << header << '\"' << endl; } } out << endl; bool dbForm = false; registerDatabases(e); dbConnections = unique(dbConnections); if (dbForms[QLatin1String("(default)")].count()) dbForm = true; bool subDbForms = false; for (it = dbConnections.constBegin(); it != dbConnections.constEnd(); ++it) { if (!(*it).isEmpty() && (*it) != QLatin1String("(default)")) { if (dbForms[(*it)].count()) { subDbForms = true; break; } } } // some typedefs, maybe typeDefs = unique(typeDefs); for (it = typeDefs.constBegin(); it != typeDefs.constEnd(); ++it) { if (!(*it).isEmpty()) out << "typedef " << *it << ';' << endl; } nl = e.parentNode().toElement().elementsByTagName(QLatin1String("forward")); for (i = 0; i < (int) nl.length(); i++) forwardDecl2 << fixDeclaration(nl.item(i).toElement().firstChild().toText().data()); forwardDecl = unique(forwardDecl); for (it = forwardDecl.constBegin(); it != forwardDecl.constEnd(); ++it) { if (!(*it).isEmpty() && (*it) != objClass) { QString forwardName = *it; QStringList forwardNamespaces = forwardName.split(QLatin1String("::")); forwardName = forwardNamespaces.last(); forwardNamespaces.removeAt(forwardNamespaces.size()-1); QStringList::ConstIterator ns = forwardNamespaces.constBegin(); while (ns != forwardNamespaces.constEnd()) { out << "namespace " << *ns << " {" << endl; ++ns; } out << "class " << forwardName << ';' << endl; for (int i = 0; i < (int) forwardNamespaces.count(); i++) out << '}' << endl; } } for (it = forwardDecl2.constBegin(); it != forwardDecl2.constEnd(); ++it) { QString fd = *it; fd = fd.trimmed(); if (!fd.endsWith(QLatin1Char(';'))) fd += QLatin1Char(';'); out << fd << endl; } out << endl; Driver d; d.option().headerProtection = false; d.option().copyrightHeader = false; d.option().extractImages = m_extractImages; d.option().limitXPM_LineLength = (m_options & LimitXPM_LineLength) ? 1 : 0; d.option().qrcOutputFile = m_qrcOutputFile; d.option().implicitIncludes = (m_options & ImplicitIncludes) ? 1 : 0; if (trmacro.size()) d.option().translateFunction = trmacro; DomUI *ui = generateUi4(e); d.uic(fileName, ui, &out); delete ui; createWrapperDeclContents(e); out << "#endif // " << protector << endl; }
void QvvMainWindow::loadDir( QString path ) { QString last_path = cdir.absolutePath(); cdir.cd( path ); QString new_path = cdir.absolutePath(); setWindowTitle( QString() + " QVV " + QVV_VERSION + ": " + new_path ); QString save_item_name; if( tree->topLevelItemCount() > 0 ) save_item_name = tree->currentItem()->text( 1 ); QStringList filters; filters.append( QString( "*" ) ); QFileInfoList info_list = cdir.entryInfoList( filters ); QTreeWidgetItem *current = NULL; tree->clear(); for( int i = 0; i < info_list.count(); i++ ) { QFileInfo fi = info_list.at( i ); if( opt_dirs_only && ! fi.isDir() ) continue; if( fi.fileName() == "." ) continue; if( fi.fileName() == ".." ) continue; QString ext = "." + fi.suffix() + "."; if( ! fi.isDir() && extensions_filter.indexOf( ext.toUpper() ) < 0 ) continue; QString file_name = fi.fileName(); QTreeWidgetItem *item = new QTreeWidgetItem(); item->setText( 0, fi.isDir() ? ITEM_TYPE_DIR : "" ); item->setText( 1, file_name ); item->setText( 2, QVariant( fi.size() ).toString() ); item->setText( 3, fi.lastModified().toString( "yyyy-MM-dd hh:mm:ss" ) ); item->setTextAlignment( 2, Qt::AlignRight ); if( last_path == new_path + "/" + file_name ) current = item; tree->addTopLevelItem( item ); } if( current ) tree->setCurrentItem( current ); else { tree->setCurrentItem( tree->topLevelItem( 0 ) ); if( save_item_name != "" ) tree->findNext( save_item_name ); } statusBar()->showMessage( QString( tr( "Loaded items" ) ) + ": " + QVariant( tree->topLevelItemCount() ).toString() ); if( opt_thumbs ) loadThumbs(); tree->resizeColumnToContents( 2 ); tree->resizeColumnToContents( 3 ); };
void IsisMain() { // We will be processing by line ProcessByBrick p; UserInterface &ui = Application::GetUserInterface(); // Use the def file for filter constants Pvl uvvisDef("$clementine1/calibration/uvvis/uvvis.def"); // Setup the input and output cubes Cube *icube = p.SetInputCube("FROM"); Cube *dccube; if(ui.WasEntered("DCFILE")) { dccube = p.SetInputCube("DCFILE"); } else { QString dcfileloc = "$clementine1/calibration/uvvis/"; dcfileloc += "dark_5_15_96.cub"; CubeAttributeInput cubeAtt; dccube = p.SetInputCube(dcfileloc, cubeAtt); } QString filter = (QString)(icube->group("BandBin"))["FilterName"]; filter = filter.toLower(); Cube *ffcube; if(ui.WasEntered("FFFILE")) { ffcube = p.SetInputCube("FFFILE"); } else { // compute default fffile double compressRatio = (icube->group("Instrument"))["EncodingCompressionRatio"]; // check to see if cube is compressed or uncompressed if(compressRatio == 1.0) { QString fffileLoc = "$clementine1/calibration/uvvis/"; fffileLoc += "lu" + filter + "_uncomp_flat_long.cub"; CubeAttributeInput cubeAtt; ffcube = p.SetInputCube(fffileLoc, cubeAtt); } else { QString fffileLoc = "$clementine1/calibration/uvvis/"; fffileLoc += "lu" + filter + "_comp_flat_long.cub"; CubeAttributeInput cubeAtt; ffcube = p.SetInputCube(fffileLoc, cubeAtt); } } Cube *ocube = p.SetOutputCube("TO"); avgFF = uvvisDef.findGroup("Filter" + filter.toUpper())["AVGFF"]; cr = uvvisDef.findGroup("Filter" + filter.toUpper())["CO"]; gain = uvvisDef.findGroup(QString("GainModeID") + QString(icube->group("Instrument")["GainModeID"][0]))["GAIN"]; useDcconst = ui.WasEntered("DCCONST"); if(useDcconst) { dcconst = ui.GetDouble("DCCONST"); } else { dcconst = 0.0; } conv = ui.GetBoolean("CONV"); exposureDuration = icube->group("Instrument")["ExposureDuration"]; offsetModeID = icube->group("Instrument")["OffsetModeID"]; if(((QString)icube->group("Instrument")["FocalPlaneTemperature"]).compare("UNK") == 0) { //if FocalPlaneTemp is unknown set it to zero focalPlaneTemp = 0.0; } else { focalPlaneTemp = icube->group("Instrument")["FocalPlaneTemperature"]; } Camera *cam = icube->camera(); bool camSuccess = cam->SetImage(icube->sampleCount() / 2, icube->lineCount() / 2); if(!camSuccess) { throw IException(IException::Unknown, "Unable to calculate the Solar Distance for this cube.", _FILEINFO_); } dist = cam->SolarDistance(); // If temp. correction set to true, or focal plane temp is zero then use temperature correction if(ui.GetBoolean("TCOR") || abs(focalPlaneTemp) <= DBL_EPSILON) { // Temperature correction requires the use of the mission phase // (PRELAUNCH, EARTH, LUNAR) and the product ID. QString productID = (QString)(icube->group("Archive")["ProductID"]); QChar missionPhase = ((QString)((icube->group("Archive"))["MissionPhase"])).at(0); QString n1subQString(productID.mid(productID.indexOf('.') + 1, productID.length() - 1)); QString n2subQString(productID.mid(4, productID.indexOf('.') - 5)); int n1 = toInt(n1subQString); int n2 = toInt(n2subQString); int phase = 0; if(missionPhase == 'L') { phase = 0; } else if(missionPhase == 'E') { phase = 1; } else if(missionPhase == 'P') { phase = 2; } else { throw IException(IException::Unknown, "Invalid Mission Phase", _FILEINFO_); } // This formula makes the primary search critera the original product ID's extension, // the secondary search criteria the mission phase and finally the numerical part of the // original product ID. int imageID = (100000 * n1) + (10000 * phase) + n2; FixTemp(imageID); } if(focalPlaneTemp <= 0.0) { focalPlaneTemp = 272.5; } // Start the processing p.SetBrickSize(icube->sampleCount(), icube->lineCount(), 1); p.StartProcess(UvVisCal); // Add the radiometry group PvlGroup calgrp("Radiometry"); calgrp += PvlKeyword("FlatFieldFile", ffcube->fileName()); if(ui.GetString("DARKCURRENT").compare("DCFILE") == 0) { calgrp += PvlKeyword("DarkCurrentFile", dccube->fileName()); } else { calgrp += PvlKeyword("DarkCurrentConstant", toString(dcconst)); } calgrp += PvlKeyword("CorrectedFocalPlaneTemp", toString(focalPlaneTemp)); calgrp += PvlKeyword("C1", toString(avgFF)); calgrp += PvlKeyword("C2", toString(C2)); calgrp += PvlKeyword("C3", toString(C3)); calgrp += PvlKeyword("C4", toString(C4)); calgrp += PvlKeyword("C5", toString(C5)); calgrp += PvlKeyword("CR", toString(cr)); calgrp += PvlKeyword("FrameTransferTimePerRow", toString(cr)); calgrp += PvlKeyword("Gain", toString(gain)); calgrp += PvlKeyword("CorrectedExposureDuration", toString(correctedExposureDuration)); calgrp += PvlKeyword("ConvertToRadiance", toString(conv)); calgrp += PvlKeyword("ACO", toString(ACO)); calgrp += PvlKeyword("BCO", toString(BCO)); calgrp += PvlKeyword("CCO", toString(CCO)); calgrp += PvlKeyword("DCO", toString(DCO)); ocube->putGroup(calgrp); p.EndProcess(); }
/*#define TOPARSE_DEBUG #include <QtDebug>*/ toSQLParse::statement toSQLParse::parseStatement(tokenizer &tokens, bool declare, bool lst) { statement ret(statement::Statement); // toSyntaxAnalyzer &syntax = tokens.analyzer(); QString first; QString realfirst; bool nokey = false; bool block = false; for (QString token = tokens.getToken(true, true); !token.isNull(); token = tokens.getToken(true, true)) { QString upp = token.toUpper(); if (first.isNull() && !token.startsWith(("/*")) && !token.startsWith("--") && !token.startsWith("//")) realfirst = first = upp; #ifdef TOPARSE_DEBUG printf("%s (%d)\n", (const char*)token.toUtf8(), tokens.line()); printf(" %s - %s\n", (const char*)first.toUtf8(), (const char*)realfirst.toUtf8()); #endif // SQLITEMAN if (upp == ("PROCEDURE") || upp == ("FUNCTION") || upp == ("PACKAGE")) { // qDebug() << "PROCEDURE"; block = true; } if (upp == ("SELF")) { // qDebug() << "SELF"; block = false; } if (upp == "BEGIN" && (first.isNull() || first == "BEGIN")) { // qDebug() << "plain BEGIN"; ret.subTokens().insert(ret.subTokens().end(), statement(statement::Keyword, token, tokens.line())); nokey = false; } else if (first != ("END") && ((first == ("IF") && upp == ("THEN")) || upp == ("LOOP") || upp == ("DO") || (/*syntax.declareBlock()*/true && upp == ("DECLARE")) || (block && upp == ("AS")) || (block && upp == ("IS")) || ((!declare || block) && upp == ("BEGIN")))) { // qDebug() << "first != (\"END\") "; block = false; statement blk(statement::Block); ret.subTokens().insert(ret.subTokens().end(), statement(statement::Keyword, token, tokens.line())); blk.subTokens().insert(blk.subTokens().end(), ret); statement cur(statement::Statement); bool dcl = (upp == ("DECLARE") || upp == ("IS") || upp == ("AS")); do { cur = parseStatement(tokens, dcl, false); if (cur.Type == statement::List) { QMessageBox::warning(QApplication::activeWindow(), "Sqliteman", "toSQLparse: Unbalanced parenthesis (Too many ')')"); } blk.subTokens().insert(blk.subTokens().end(), cur); if (cur.subTokens().begin() != cur.subTokens().end() && (*(cur.subTokens().begin())).String.toUpper() == ("BEGIN")) dcl = false; } while (cur.subTokens().begin() != cur.subTokens().end() && (*cur.subTokens().begin()).String.toUpper() != ("END")); return blk; } else if (((first == "IF" && upp == "THEN") || (first == "WHEN" && upp == "THEN") || (first == "ELSIF" && upp == "THEN") || upp == ("BEGIN") || upp == ("EXCEPTION") || first == ("ELSE")) && !lst) { // qDebug() << "else if first==IF"; ret.subTokens().insert(ret.subTokens().end(), statement(statement::Keyword, token, tokens.line())); return ret; } else if (first == ("ASSIGN") || first == ("SET") || first == ("PROMPT") || first == ("COLUMN") || first == ("SPOOL") || first == ("STORE") || first == ("REMARK") || first == ("REM")) { // qDebug() << "ASSIGN"; ret.subTokens().insert(ret.subTokens().end(), statement(statement::Keyword, token, tokens.line())); int line = tokens.line(); int offset = tokens.offset(); for (QString tmp = tokens.getToken(true, true);line == tokens.line();tmp = tokens.getToken(true, true)) ret.subTokens().insert(ret.subTokens().end(), statement(statement::Token, tmp, line)); tokens.setLine(line); tokens.setOffset(offset); tokens.remaining(true); return ret; } else if (upp == (",") || // if (upp == (",") || // (syntax.reservedWord(upp) && (isKeyword(upp) && upp != ("NOT") && upp != ("IS") && upp != ("LIKE") && upp != ("IN") && upp != ("ELSE") && upp != ("ELSIF") && upp != ("END") && upp != ("BETWEEN") && upp != ("ASC") && upp != ("DESC") && upp != ("NULL")) && !nokey) { } else if (upp == ("(")) { // qDebug() << "start ("; ret.subTokens().insert(ret.subTokens().end(), statement(statement::Token, token, tokens.line())); statement lst = parseStatement(tokens, false, true); statement t = toPop(lst.subTokens()); if (lst.Type != statement::List) { QMessageBox::warning(QApplication::activeWindow(), "Sqliteman", "toSQLparse: Unbalanced parenthesis (Too many '(')"); } nokey = false; if (first == ("CREATE") && !block) { statement end = parseStatement(tokens, false, true); statement blk(statement::Block); blk.subTokens().insert(blk.subTokens().end(), ret); blk.subTokens().insert(blk.subTokens().end(), lst); end.subTokens().insert(end.subTokens().begin(), t); blk.subTokens().insert(blk.subTokens().end(), end); return blk; } else { ret.subTokens().insert(ret.subTokens().end(), lst); ret.subTokens().insert(ret.subTokens().end(), t); } } else if (upp == (")")) { // qDebug() << "end )"; ret.Type = statement::List; ret.subTokens().insert(ret.subTokens().end(), statement(statement::Token, token, tokens.line())); return ret; } else if (upp == (";")) { // qDebug() << "bodkociarka"; ret.subTokens().insert(ret.subTokens().end(), statement(statement::Token, token, tokens.line())); return ret; } else if (upp.startsWith(("/*+")) || upp.startsWith(("--+"))) { // qDebug() << "hint --+"; QString com = token; if (com.startsWith(("--+"))) com = ("/*+ ") + com.mid(3) + (" */"); ret.subTokens().insert(ret.subTokens().end(), statement(statement::Token, com.simplified(), tokens.line())); } else if (upp.startsWith(("/*")) || upp.startsWith(("--")) || upp.startsWith("//")) { // qDebug() << "comment"; if ( ret.subTokens().empty() ) { if (ret.Comment.isNull()) ret.Comment = token; else ret.Comment += ("\n") + token; } else { QString &com = (*ret.subTokens().rbegin()).Comment; if (com.isEmpty()) com = token; else com += ("\n") + token; } } else { // qDebug() << "plain else" <<token<< tokens.line(); ret.subTokens().insert(ret.subTokens().end(), statement(statement::Token, token, tokens.line())); nokey = (token == (".")); } if (upp == ("AS") || upp == ("IS")) { // qDebug() << "setting first: " << upp; first = upp; } else if (first == ("IS") && upp == ("NULL")) { // qDebug() << "setting first (real): " << realfirst; first = realfirst; } } return ret; }
QString Manage::upper(const QString &string) { return string.toUpper(); }
AVPixelFormat RasterRenderPrivate::getFormat(QString &chroma) { static QHash<QString, AVPixelFormat> f; if (f.isEmpty()){ f.insert("RV32", AV_PIX_FMT_RGB32); f.insert("RV24", AV_PIX_FMT_RGB24); f.insert("RGB8", AV_PIX_FMT_RGB8); f.insert("RV12", AV_PIX_FMT_RGB444); f.insert("RV15", AV_PIX_FMT_RGB555); f.insert("RV16", AV_PIX_FMT_RGB565); f.insert("RGBA", AV_PIX_FMT_RGBA); f.insert("ARGB", AV_PIX_FMT_ARGB); f.insert("BGRA", AV_PIX_FMT_BGRA); f.insert("I410", AV_PIX_FMT_YUV410P); f.insert("I411", AV_PIX_FMT_YUV411P); f.insert("I420", AV_PIX_FMT_YUV420P); f.insert("IYUV", AV_PIX_FMT_YUV420P); f.insert("I422", AV_PIX_FMT_YUV422P); f.insert("I440", AV_PIX_FMT_YUV440P); f.insert("I444", AV_PIX_FMT_YUV444P); f.insert("J420", AV_PIX_FMT_YUVJ420P); f.insert("J422", AV_PIX_FMT_YUVJ422P); f.insert("J440", AV_PIX_FMT_YUVJ440P); f.insert("J444", AV_PIX_FMT_YUVJ444P); f.insert("I40A", AV_PIX_FMT_YUVA420P); f.insert("I42A", AV_PIX_FMT_YUVA422P); f.insert("YUVA", AV_PIX_FMT_YUVA444P); f.insert("YA0L", AV_PIX_FMT_YUVA444P10LE); f.insert("YA0B", AV_PIX_FMT_YUVA444P10BE); f.insert("NV12", AV_PIX_FMT_NV12); f.insert("NV21", AV_PIX_FMT_NV21); f.insert("I09L", AV_PIX_FMT_YUV420P9LE); f.insert("I09B", AV_PIX_FMT_YUV420P9BE); f.insert("I29L", AV_PIX_FMT_YUV422P9LE); f.insert("I29B", AV_PIX_FMT_YUV422P9BE); f.insert("I49L", AV_PIX_FMT_YUV444P9LE); f.insert("I49B", AV_PIX_FMT_YUV444P9BE); f.insert("I0AL", AV_PIX_FMT_YUV420P10LE); f.insert("I0AB", AV_PIX_FMT_YUV420P10BE); f.insert("I2AL", AV_PIX_FMT_YUV422P10LE); f.insert("I2AB", AV_PIX_FMT_YUV422P10BE); f.insert("I4AL", AV_PIX_FMT_YUV444P10LE); f.insert("I4AB", AV_PIX_FMT_YUV444P10BE); f.insert("UYVY", AV_PIX_FMT_UYVY422); f.insert("YUYV", AV_PIX_FMT_YUYV422); f.insert("YUY2", AV_PIX_FMT_YUYV422); } chroma = chroma.toUpper(); if (f.contains(chroma)){ } else if (chroma == "YV12"){ chroma = "I420"; } else if (chroma == "NV16"){ chroma = "NV12"; } else if (chroma == "NV61"){ chroma = "NV21"; } else if (chroma == "VYUY" || chroma == "YVYU" || chroma == "V422" || chroma == "CYUV"){ chroma = "UYVY"; } else if (chroma == "V210"){ chroma = "I0AL"; } else{ chroma = "I420"; } return f[chroma]; }
void EditPrimerDialog::sl_onPrimerChanged(const QString &primerSequence) { int curPos = primerEdit->cursorPosition(); primerEdit->setText(primerSequence.toUpper()); primerEdit->setCursorPosition(curPos); }
void EditDialog::exportData() { QStringList filters; switch (dataType) { case Image: { // Images get special treatment. // Determine the likely filename extension. QByteArray cellData = hexEdit->data(); QBuffer imageBuffer(&cellData); QImageReader imageReader(&imageBuffer); QString imageFormat = imageReader.format(); filters << tr("%1 Image").arg(imageFormat.toUpper()) % " (*." % imageFormat.toLower() % ")"; break; } case Binary: filters << tr("Binary files (*.bin)"); break; case Text: // Base the XML case on the mode, not the data type since XML detection is currently not implemented. if (ui->comboMode->currentIndex() == XmlEditor) filters << tr("XML files (*.xml)") << tr("Text files (*.txt)"); else filters << tr("Text files (*.txt)") << tr("XML files (*.xml)"); break; case JSON: filters << tr("JSON files (*.json)"); break; case SVG: filters << tr("SVG files (*.svg)"); break; case Null: return; } if (dataSource == HexBuffer) filters << tr("Hex dump files (*.txt)"); filters << tr("All files (*)"); QString selectedFilter = filters.first(); QString fileName = FileDialog::getSaveFileName( CreateDataFile, this, tr("Choose a filename to export data"), filters.join(";;"), /* defaultFileName */ QString(), &selectedFilter); if(fileName.size() > 0) { QFile file(fileName); if(file.open(QIODevice::WriteOnly)) { switch (dataSource) { case HexBuffer: // Data source is the hex buffer // If text option has been selected, the readable representation of the content is saved to file. if (selectedFilter == tr("Hex dump files (*.txt)")) file.write(hexEdit->toReadableString().toUtf8()); else file.write(hexEdit->data()); break; case TextBuffer: // Data source is the text buffer file.write(ui->editorText->toPlainText().toUtf8()); break; case SciBuffer: // Data source is the Scintilla buffer file.write(sciEdit->text().toUtf8()); break; } file.close(); } } }
bool CETDongle::IsAdminHID( QString &strHID ) { strHID = strHID.toUpper( ); return hashAdminHID.contains( strHID ); }
// Update the information labels in the bottom left corner of the dialog // and switches the editor mode, if required, according to the detected data type. void EditDialog::updateCellInfoAndMode(const QByteArray& data) { QByteArray cellData = data; switchEditorMode(ui->buttonAutoSwitchMode->isChecked()); // Image data needs special treatment if (dataType == Image || dataType == SVG) { QBuffer imageBuffer(&cellData); QImageReader imageReader(&imageBuffer); // Display the image format QString imageFormat = imageReader.format(); ui->labelType->setText(tr("Type of data currently in cell: %1 Image").arg(imageFormat.toUpper())); // Display the image dimensions and size QSize imageDimensions = imageReader.size(); int imageSize = cellData.size(); QString labelSizeText = tr("%1x%2 pixel(s)").arg(imageDimensions.width()).arg(imageDimensions.height()) + ", " + humanReadableSize(imageSize); ui->labelSize->setText(labelSizeText); return; } // Use a switch statement for the other data types to keep things neat :) switch (dataType) { case Null: // NULL data type ui->labelType->setText(tr("Type of data currently in cell: NULL")); ui->labelSize->setText(tr("%n byte(s)", "", 0)); ui->editorText->setStyleSheet("QTextEdit{ font-style: italic; }"); ui->editorText->setPlaceholderText(Settings::getValue("databrowser", "null_text").toString()); break; case Text: { // Text only // Determine the length of the cell text in characters (possibly different to number of bytes). int textLength = QString(cellData).length(); ui->labelType->setText(tr("Type of data currently in cell: Text / Numeric")); ui->labelSize->setText(tr("%n char(s)", "", textLength)); break; } case JSON: { // Valid JSON // Determine the length of the cell text in characters (possibly different to number of bytes). int jsonLength = QString(cellData).length(); ui->labelType->setText(tr("Type of data currently in cell: Valid JSON")); ui->labelSize->setText(tr("%n char(s)", "", jsonLength)); break; } default: // Determine the length of the cell data int dataLength = cellData.length(); // If none of the above data types, consider it general binary data ui->labelType->setText(tr("Type of data currently in cell: Binary")); ui->labelSize->setText(tr("%n byte(s)", "", dataLength)); break; } }
QString mkvar(const QString &s) { return s.toUpper().replace('-', '_').replace(':', '_'); }
void NObjBroadcastReceiver::setMac(QString mac) { m_mac = CCompareMacInLower ? mac.toLower() : mac.toUpper(); }
void QHexEditPrivate::paintEvent(QPaintEvent *event) { QPainter painter(this); // draw some patterns if needed painter.fillRect(event->rect(), this->palette().color(QPalette::Base)); if (_addressArea) painter.fillRect(QRect(_xPosAdr, event->rect().top(), _xPosHex - GAP_ADR_HEX + 2, height()), _addressAreaColor); if (_asciiArea) { int linePos = _xPosAscii - (GAP_HEX_ASCII / 2); painter.setPen(Qt::gray); painter.drawLine(linePos, event->rect().top(), linePos, height()); } painter.setPen(this->palette().color(QPalette::WindowText)); // calc position int firstLineIdx = ((event->rect().top()/ _charHeight) - _charHeight) * BYTES_PER_LINE; if (firstLineIdx < 0) firstLineIdx = 0; int lastLineIdx = ((event->rect().bottom() / _charHeight) + _charHeight) * BYTES_PER_LINE; if (lastLineIdx > _data.size()) lastLineIdx = _data.size(); int yPosStart = ((firstLineIdx) / BYTES_PER_LINE) * _charHeight + _charHeight; // paint address area if (_addressArea) { for (int lineIdx = firstLineIdx, yPos = yPosStart; lineIdx < lastLineIdx; lineIdx += BYTES_PER_LINE, yPos +=_charHeight) { QString address = QString("%1") .arg(lineIdx + _addressOffset, _realAddressNumbers, 16, QChar('0')); // address.insert(address.length()-4,':'); painter.drawText(_xPosAdr, yPos, address.toUpper()); } } // paint hex area QByteArray hexBa(_data.mid(firstLineIdx, lastLineIdx - firstLineIdx + 1).toHex()); QBrush highLighted = QBrush(_highlightingColor); QPen colHighlighted = QPen(this->palette().color(QPalette::WindowText)); QBrush selected = QBrush(_selectionColor); QPen colSelected = QPen(Qt::white); QPen colStandard = QPen(this->palette().color(QPalette::WindowText)); painter.setBackgroundMode(Qt::TransparentMode); for (int lineIdx = firstLineIdx, yPos = yPosStart; lineIdx < lastLineIdx; lineIdx += BYTES_PER_LINE, yPos +=_charHeight) { QByteArray hex; int xPos = _xPosHex; QString hl_block; int hl_block_i; if (_highlighting) { painter.setPen(Qt::yellow); hl_block_i=0; hl_block="██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██"; for (int colIdx = 0; ((lineIdx + colIdx) < _data.size() and (colIdx < BYTES_PER_LINE)); colIdx++) { int posBa = lineIdx + colIdx; if (_changedData[posBa]) { hl_block[hl_block_i] = QChar(' '); hl_block[hl_block_i+1] = QChar(' '); } hl_block_i=hl_block_i+3; } if(hl_block_i!=0) { while(hl_block_i<hl_block.size()) { hl_block[hl_block_i] = QChar(' '); hl_block_i++; } painter.drawText(xPos, yPos, hl_block); } } if (_exteralHl.size()!=0) { painter.setPen(Qt::green); hl_block_i=0; hl_block="██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██"; for (int colIdx = 0; ((lineIdx + colIdx) < _data.size() and (colIdx < BYTES_PER_LINE)); colIdx++) { int posBa = lineIdx + colIdx; if (_exteralHl[posBa]=='\0') { hl_block[hl_block_i] = QChar(' '); hl_block[hl_block_i+1] = QChar(' '); } hl_block_i=hl_block_i+3; } if(hl_block_i!=0) { while(hl_block_i<hl_block.size()) { hl_block[hl_block_i] = QChar(' '); hl_block_i++; } painter.drawText(xPos, yPos, hl_block); } } // if (_selected) painter.setPen(Qt::cyan); hl_block_i=0; hl_block="██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██"; for (int colIdx = 0; ((lineIdx + colIdx) < _data.size() and (colIdx < BYTES_PER_LINE)); colIdx++) { int posBa = lineIdx + colIdx; if (!((getSelectionBegin() <= posBa) && (getSelectionEnd() > posBa))) { hl_block[hl_block_i] = QChar(' '); hl_block[hl_block_i+1] = QChar(' '); } hl_block_i=hl_block_i+3; } if(hl_block_i!=0) { while(hl_block_i<hl_block.size()) { hl_block[hl_block_i] = QChar(' '); hl_block_i++; } painter.drawText(xPos, yPos, hl_block); } painter.setPen(this->palette().color(QPalette::WindowText)); hex = hexBa.mid((lineIdx - firstLineIdx) * 2, BYTES_PER_LINE * 2); QString new_hex=" "; //BYTES_PER_LINE*3 int i_new_hex = 0; for(int i_hex=0;i_hex<hex.size();i_hex++,i_new_hex++) { new_hex[i_new_hex] = hex[i_hex]; if((i_hex+1)%2 == 0)i_new_hex++; } painter.drawText(xPos, yPos, new_hex.toUpper()); } painter.setBackgroundMode(Qt::TransparentMode); painter.setPen(this->palette().color(QPalette::WindowText)); // paint ascii area if (_asciiArea) { for (int lineIdx = firstLineIdx, yPos = yPosStart; lineIdx < lastLineIdx; lineIdx += BYTES_PER_LINE, yPos +=_charHeight) { QByteArray ascii = _data.mid(lineIdx, BYTES_PER_LINE); for (int idx=0; idx < ascii.size(); idx++) if (((char)ascii[idx] < 0x20) or ((char)ascii[idx] > 0x7e)) ascii[idx] = '.'; painter.drawText(_xPosAscii, yPos, ascii); } } // paint cursor if (_blink) { if (_overwriteMode) painter.fillRect(_cursorX, _cursorY + _charHeight - 2, _charWidth, 2, this->palette().color(QPalette::WindowText)); else painter.fillRect(_cursorX, _cursorY, 2, _charHeight, this->palette().color(QPalette::WindowText)); } if (_size != _data.size()) { _size = _data.size(); emit currentSizeChanged(_size); } QString adr; adr.setNum(_cursorPosition/2,16); adr = adr.toUpper(); while(adr.length()<8) { adr.prepend("0"); } QString val; val.setNum(_data[_cursorPosition/2],16); val = val.toUpper(); if(val.length()<2)val.prepend("0"); val = val.mid(val.length()-2,2); QString bval; bval.setNum(_data[_cursorPosition/2],2); while(bval.length()<8)bval.prepend("0"); if(bval.length()>8) { bval = bval.mid(bval.length()-8,8); } emit updateText("Address: "+adr+" Value: "+val+" Binary: "+bval); }
QgsSqlExpressionCompiler::Result QgsDb2ExpressionCompiler::compileNode( const QgsExpressionNode *node, QString &result ) { QgsDebugMsg( QStringLiteral( "nodeType: %1" ).arg( nodeType( node ) ) ); if ( node->nodeType() == QgsExpressionNode::ntColumnRef ) { const QgsExpressionNodeColumnRef *n( static_cast<const QgsExpressionNodeColumnRef *>( node ) ); QgsDebugMsg( QStringLiteral( "column ref node: " ) + n->dump() ); // TODO - consider escaped names - not sure how to handle QString upperName = n->name().toUpper(); int idx = mFields.indexFromName( upperName ); QgsDebugMsg( QStringLiteral( "%1 - %2" ).arg( idx ).arg( upperName ) ); if ( idx > -1 ) { result = upperName; QgsDebugMsg( QStringLiteral( "return Complete" ) ); return Complete; } QgsDebugMsg( QStringLiteral( "return Fail" ) ); return Fail; } // Seemed necessary in initial Python testing but can't identify failing case now #if 0 if ( node->nodeType() == QgsExpressionNode::ntLiteral ) { const QgsExpression::NodeLiteral *n = static_cast<const QgsExpression::NodeLiteral *>( node ); bool ok = false; if ( n->dump().toUpper() == "NULL" ) // expression compiler doesn't handle this correctly { result = "NULL"; ok = true; } else { result = quotedValue( n->value(), ok ); } QgsDebugMsg( QStringLiteral( "ok: %1; literal node: " ).arg( ok ) + n->value().toString() + "; result: " + result ); QgsDebugMsg( QStringLiteral( "n->dump: " ) + n->dump() ); QgsDebugMsg( QStringLiteral( "type: %1; typeName: %2" ).arg( n->value().type() ).arg( n->value().typeName() ) ); if ( ok ) { QgsDebugMsg( QStringLiteral( "return Complete" ) ); return Complete; } else { QgsDebugMsg( QStringLiteral( "return Fail" ) ); return Fail; } } #endif if ( node->nodeType() == QgsExpressionNode::ntUnaryOperator ) { const QgsExpressionNodeUnaryOperator *n = static_cast<const QgsExpressionNodeUnaryOperator *>( node ); Result rr = Fail; switch ( n->op() ) { case QgsExpressionNodeUnaryOperator::uoNot: rr = compileNode( n->operand(), result ); if ( "NULL" == result.toUpper() ) { result.clear(); return Fail; } result = "NOT " + result; QgsDebugMsg( QStringLiteral( "NOT; result: %1; right: %2" ).arg( resultType( rr ), result ) ); return rr; case QgsExpressionNodeUnaryOperator::uoMinus: break; } } if ( node->nodeType() == QgsExpressionNode::ntBinaryOperator ) { const QgsExpressionNodeBinaryOperator *bin( static_cast<const QgsExpressionNodeBinaryOperator *>( node ) ); QString left, right; Result lr = compileNode( bin->opLeft(), left ); Result rr = compileNode( bin->opRight(), right ); Result compileResult; QgsDebugMsg( "left: '" + left + "'; right: '" + right + QString( "'; op: %1; lr: %2; rr: %3" ).arg( bin->op() ).arg( lr ).arg( rr ) ); if ( lr == Fail || rr == Fail ) return Fail; // NULL can not appear on the left, only as part of IS NULL or IS NOT NULL if ( "NULL" == left.toUpper() ) return Fail; // NULL can only be on the right for IS and IS NOT if ( "NULL" == right.toUpper() && ( bin->op() != QgsExpressionNodeBinaryOperator::boIs && bin->op() != QgsExpressionNodeBinaryOperator::boIsNot ) ) return Fail; switch ( bin->op() ) { case QgsExpressionNodeBinaryOperator::boMod: result = QStringLiteral( "MOD(%1,%2)" ).arg( left, right ); compileResult = ( lr == Partial || rr == Partial ) ? Partial : Complete; QgsDebugMsg( QStringLiteral( "MOD compile status: %1" ).arg( compileResult ) + "; " + result ); return compileResult; case QgsExpressionNodeBinaryOperator::boPow: result = QStringLiteral( "power(%1,%2)" ).arg( left, right ); compileResult = ( lr == Partial || rr == Partial ) ? Partial : Complete; QgsDebugMsg( QStringLiteral( "POWER compile status: %1" ).arg( compileResult ) + "; " + result ); return compileResult; case QgsExpressionNodeBinaryOperator::boRegexp: return Fail; //not supported, regexp syntax is too different to Qt case QgsExpressionNodeBinaryOperator::boConcat: result = QStringLiteral( "%1 || %2" ).arg( left, right ); compileResult = ( lr == Partial || rr == Partial ) ? Partial : Complete; QgsDebugMsg( QStringLiteral( "CONCAT compile status: %1" ).arg( compileResult ) + "; " + result ); return compileResult; case QgsExpressionNodeBinaryOperator::boILike: QgsDebugMsg( QStringLiteral( "ILIKE is not supported by DB2" ) ); return Fail; /* result = QString( "%1 LIKE %2" ).arg( left, right ); compileResult = (lr == Partial || rr == Partial) ? Partial : Complete; QgsDebugMsg(QString("ILIKE compile status: %1").arg(compileResult) + "; " + result); return compileResult; */ case QgsExpressionNodeBinaryOperator::boNotILike: QgsDebugMsg( QStringLiteral( "NOT ILIKE is not supported by DB2" ) ); return Fail; /* result = QString( "%1 NOT LIKE %2" ).arg( left, right ); compileResult = (lr == Partial || rr == Partial) ? Partial : Complete; QgsDebugMsg(QString("NOT ILIKE compile status: %1").arg(compileResult) + "; " + result); return compileResult; */ // We only support IS NULL if the operand on the left is a column case QgsExpressionNodeBinaryOperator::boIs: if ( "NULL" == right.toUpper() ) { if ( bin->opLeft()->nodeType() != QgsExpressionNode::ntColumnRef ) { QgsDebugMsg( "Failing IS NULL with non-column on left: " + left ); return Fail; } } break; // We only support IS NULL if the operand on the left is a column case QgsExpressionNodeBinaryOperator::boIsNot: if ( "NULL" == right.toUpper() ) { if ( bin->opLeft()->nodeType() != QgsExpressionNode::ntColumnRef ) { QgsDebugMsg( "Failing IS NOT NULL with non-column on left: " + left ); return Fail; } } break; default: break; } } //fallback to default handling QgsDebugMsg( QStringLiteral( "fallback: %1 - " ).arg( nodeType( node ) ) ); QgsSqlExpressionCompiler::Result rc = QgsSqlExpressionCompiler::compileNode( node, result ); QgsDebugMsg( QStringLiteral( "fallback: %1 - " ).arg( resultType( rc ) ) + result ); return rc; }