Beispiel #1
0
void FileEnvProcess::start(const QString& program, const QStringList& arguments, OpenMode mode)
{
    QByteArray programBa = program.toLatin1();
    const char* programCharPtr = programBa.data();
    
    QString* tmpFileNameStrPtr = new QString("/tmp/tmpRideFile.bash");
    QFile* tmpRideFilePtr = new QFile(*tmpFileNameStrPtr);
    tmpRideFilePtr->open(QIODevice::WriteOnly);
    
    addHeader(tmpRideFilePtr);
    tmpRideFilePtr->write(programCharPtr);
    tmpRideFilePtr->write(" ");
    
    QByteArray tmpByteArray;
    for(size_t i = 0; i < arguments.size(); i++)
    {
        tmpByteArray.append(arguments.at(i) + " ");
        tmpRideFilePtr->write(tmpByteArray);
        tmpByteArray.clear();
    }
    
    tmpRideFilePtr->write("\nrm /tmp/tmpRideFile.bash");
    tmpRideFilePtr->write("\necho \"Finished execution.\"");
    tmpRideFilePtr->close();
    
    QStringList stringlst; stringlst.push_back("+x"); stringlst.push_back("/tmp/tmpRideFile.bash");

    testProcess.execute("chmod", stringlst);
    
    testProcess.start(*tmpFileNameStrPtr, mode); //don't run this->execute; this would result in infinate recursion!!!
    testProcess.waitForFinished(-1);
    QByteArray output = testProcess.readAllStandardOutput();
    cout << cct::bold("\nOutput: ") << output.data() << ":End" << endl;
    outputLocTePtr->append(output.data());
    cout << "exiting FileEnvProcess::start(...)" << endl;
}
Beispiel #2
0
/**
 * @brief Article::save
 */
void Article::save(){
    //1er cas si le fichier a déjà été sauvegardé, on ne le sauvegarde pas une nouvelle fois
    if (!modified)
        return;
    //2e cas
    else {
         QFile fichier (NotesManager::getInstance()->getFilename(id));
        //Si le fichier n'est pas encore crée, il le crée
        if (fichier.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QTextStream flux(&fichier);
            flux.setCodec("UTF-8");
            //Type de la note
            flux << "article" << endl;
            //Informations sur la note
            flux << title << endl;
            flux << content << endl;
            modified = false;
            fichier.close();
        }
        else {
            throw NoteException(QObject::tr("Unable to load the file ") + fichier.fileName() + QObject::tr(" for saving"));
        }
    }
}
Beispiel #3
0
bool QMacPasteboardMimeQt3Any::loadMimeRegistry()
{
    if(!library_file.isOpen()) {
        if(!qt_mac_openMimeRegistry(true, QIODevice::ReadWrite, library_file)) {
            QFile global;
            if(qt_mac_openMimeRegistry(true, QIODevice::ReadOnly, global)) {
                qt_mac_loadMimeRegistry(global, mime_registry, current_max);
                global.close();
            }
            if(!qt_mac_openMimeRegistry(false, QIODevice::ReadWrite, library_file)) {
                qWarning("QMacPasteboardMimeAnyQt3Mime: Failure to open mime resources %s -- %s", library_file.fileName().toLatin1().constData(),
                         library_file.errorString().toLatin1().constData());
                return false;
            }
        }
    }

    QFileInfo fi(library_file);
    if(!mime_registry_loaded.isNull() && mime_registry_loaded == fi.lastModified())
        return true;
    mime_registry_loaded = fi.lastModified();
    qt_mac_loadMimeRegistry(library_file, mime_registry, current_max);
    return true;
}
Beispiel #4
0
void Session::init() {
    qDebug() << "Loading sessions...";
    QFile* configFile = new QFile ( Core::configurationPath().absolutePath() +"/sessions.xml" );
    s_elems.clear();

    if ( s_dom ) {
        s_dom->clear();
        delete s_dom;
    }

    s_dom = new QDomDocument ( "Sessions" );

    if ( configFile->exists() ) {
        configFile->open ( QIODevice::ReadOnly );
        s_dom->setContent ( configFile );

        const QDomElement documentElem = s_dom->documentElement();
        const QDomNodeList l_domList = documentElem.elementsByTagName ( "Session" );

        for ( int i = 0; i < l_domList.count(); i++ ) {
            QDomElement l_node = l_domList.at ( i ).toElement();
            const QUuid l_uuid ( l_node.attribute ( "uuid" ) );
            s_elems.insert ( l_uuid, new QDomElement ( l_domList.at ( i ).toElement() ) );
        }

        qDebug() << l_domList.count() << "sessions loaded.";
    } else {
        configFile->open ( QIODevice::WriteOnly | QIODevice::Truncate );
        QDomElement l_elem = s_dom->createElement ( "Sessions" );
        s_dom->appendChild ( l_elem );
        configFile->write ( s_dom->toString ( 4 ).toLocal8Bit() );
        qDebug() << "Created session listing.";
    }

    configFile->close();
}
Beispiel #5
0
void AutoMateUi::save() {
	std::vector<Version> vers = applications_model->getSelected();
	QDomDocument doc("export");
	QDomElement root = doc.createElement("template");
	doc.appendChild(root);
	for(std::vector<Version>::iterator itr = vers.begin(); itr != vers.end(); ++itr)
	{
		QDomElement inst = doc.createElement("install");
		if (! itr->is_last)
			inst.setAttribute("version",itr->version().c_str());
		QDomText name = doc.createTextNode(itr->name().c_str());
		inst.appendChild(name);
		root.appendChild(inst);
	}
	QString flname = QFileDialog::getSaveFileName(this,"Select file to save", "", "XML files(*.xml)");
	QFile *fl = new QFile(flname);
	if (!fl->open(QIODevice::WriteOnly | QIODevice::Text)) {
		statusBar()->showMessage("Writing to file failed", status_message_delay);
		return;
	}
	fl->write(doc.toString().toLocal8Bit());
	fl->close();
	statusBar()->showMessage("Selection saved", status_message_delay);
}
Beispiel #6
0
void Widget::Btn_onclicked()
{
    // 创建文件操作对象
    QFile *fp = new QFile("test.txt");

    // 检查文件是否存在
    if (!fp->exists()) {
        QMessageBox::critical(this, "Error", fp->errorString());
        return;
    }

    // 打开文件
    if (!fp->open(QIODevice::ReadWrite|QIODevice::Text)) {
        QMessageBox::critical(this, "Error", fp->errorString());
        return;
    }

    // 使用文本流对文件进行操作
    QTextStream out(fp);
    //out.setCodec("UTF-8");    // 设置编码
    QString text = out.readAll();
    ui->textEdit->setText(text);

    // 移动指针到末端并写入
    //fp->seek(fp->size());
    //out << "\r\n" << QString("321TEST");

    // 关闭文件
    fp->close();
    delete fp;

    // 设置textedit滚动到末端
    QTextCursor cursor = ui->textEdit->textCursor();
    cursor.movePosition(QTextCursor::End);
    ui->textEdit->setTextCursor(cursor);
}
void MainWindow::SetOuputDefaultDir()
{
    QString path = "configure.conf";
    QByteArray byteArrayData = 0;
    QFile* defaultPathFile = new QFile(path);

    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"), QDir::homePath(),
                                                QFileDialog::ShowDirsOnly
                                                | QFileDialog::DontResolveSymlinks);
    int x = QString::compare(dir, _defaultOutputPath, Qt::CaseInsensitive);
    if (x != 0)
    {
        defaultPathFile->remove(path);
        defaultPathFile->setFileName(path);
        if (defaultPathFile->open(QIODevice::WriteOnly | QIODevice::Text) == true)
        {
            byteArrayData = dir.toLatin1();
            defaultPathFile->write(byteArrayData);
        }
        _defaultOutputPath = dir;
        ui->_leDefaultDirPath->setText(dir);
    }
    defaultPathFile->close();
}
void form_UserRegistration::loadCfgFile()
{
    QFile cfgFile;
    QTextStream rStream(&cfgFile);
    QString line;
    vector <QString> str;
    
    //QTextCodec::setCodecForCStrings(QTextCodec::codecForName("cp1251"));
    
    cfgFile.setFileName("ovd.cfg");
    cfgFile.open(QIODevice::ReadOnly | QIODevice::Text);
    
    do // загружаем названия частоиспользуемых ОВД
    {
        line = rStream.readLine();
        if (line.contains("len_ovd"))
        {
            len_ovd.ovd = line.remove(QRegExp("(.*=)"));
//            cout << len_ovd.toAscii().data() << endl;
        }
        else
        if (line.contains("okt_ovd"))
        {
            okt_ovd.ovd = line.remove(QRegExp("(.*=)"));
//            cout << okt_ovd.toAscii().data() << endl;
        }
        else
        if (line.contains("perv_ovd"))
        {
            perv_ovd.ovd = line.remove(QRegExp("(.*=)"));
//            cout << perv_ovd.toAscii().data() << endl;   
        }
        else
        if (line.contains("len_oufms"))
        {
            len_oufms.ovd = line.remove(QRegExp("(.*=)"));
//            cout << len_oufms.toAscii().data() << endl;   
        }                
        else
        if (line.contains("okt_oufms"))
        {
            okt_oufms.ovd = line.remove(QRegExp("(.*=)"));
//            cout << okt_oufms.toAscii().data() << endl;   
        }                
        else
        if (line.contains("perv_oufms"))
        {
            perv_oufms.ovd = line.remove(QRegExp("(.*=)"));
//            cout << perv_oufms.toAscii().data() << endl;   
        }                
    }
    while (!line.isNull());
    cfgFile.close();
    
    cfgFile.setFileName("streets.cfg");
    cfgFile.open(QIODevice::ReadOnly | QIODevice::Text);
     
    do // загружаем списки улиц и распределяем их по овд
    { // так в лень было переписывать все в одну функцию... поэтому пока что так =)
        str.clear();
        line = rStream.readLine();
        if (line.contains("len_ovd="))
        {
            int amount = line.remove(QRegExp("(.*=)")).toInt() - 1;
            for (int i = 0; i <= amount; i++) // пока не указанное количество улиц 
            {
                line = rStream.readLine();
                str.push_back(line);
            }
            len_ovd.streets = str;
        }
        else
        if (line.contains("okt_ovd="))
        {
            int amount = line.remove(QRegExp("(.*=)")).toInt() - 1;
            for (int i = 0; i <= amount; i++) // пока не указанное количество улиц 
            {
                line = rStream.readLine();
                str.push_back(line);
            }
            okt_ovd.streets = str; 
        }
        else
        if (line.contains("perv_ovd="))
        {
            int amount = line.remove(QRegExp("(.*=)")).toInt() - 1;
            for (int i = 0; i <= amount; i++) // пока не указанное количество улиц 
            {
                line = rStream.readLine();
                str.push_back(line);
            }
            perv_ovd.streets = str; 
        }
            
    } while (!line.isNull()); 
    
    //QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
}
Beispiel #9
0
CC_FILE_ERROR BinFilter::SaveFileV2(QFile& out, ccHObject* object)
{
	if (!object)
		return CC_FERR_BAD_ARGUMENT;

	//About BIN versions:
	//- 'original' version (file starts by the number of clouds - no header)
	//- 'new' evolutive version, starts by 4 bytes ("CCB2") + save the current ccObject version

	//header
	//Since ver 2.5.2, the 4th character of the header corresponds to
	//'deserialization flags' (see ccSerializableObject::DeserializationFlags)
	char firstBytes[5] = "CCB2";
	{
		char flags = 0;
		if (sizeof(PointCoordinateType) == 8)
			flags |= static_cast<char>(ccSerializableObject::DF_POINT_COORDS_64_BITS);
		if (sizeof(ScalarType) == 4)
			flags |= static_cast<char>(ccSerializableObject::DF_SCALAR_VAL_32_BITS);
		assert(flags <= 8);
		firstBytes[3] = 48+flags; //48 = ASCII("0")
	}

	if (out.write(firstBytes,4) < 0)
		return CC_FERR_WRITING;

	// Current BIN file version
	uint32_t binVersion_u32 = static_cast<uint32_t>(ccObject::GetCurrentDBVersion());
	if (out.write((char*)&binVersion_u32,4) < 0)
		return CC_FERR_WRITING;

	CC_FILE_ERROR result = CC_FERR_NO_ERROR;

	//we check if all linked entities are in the sub tree we are going to save
	//(such as vertices for a mesh!)
	ccHObject::Container toCheck;
	toCheck.push_back(object);
	while (!toCheck.empty())
	{
		ccHObject* currentObject = toCheck.back();
		assert(currentObject);
		toCheck.pop_back();

		//we check objects that have links to other entities (meshes, polylines, etc.)
		std::unordered_set<const ccHObject*> dependencies;
		if (currentObject->isA(CC_TYPES::MESH) || currentObject->isKindOf(CC_TYPES::PRIMITIVE))
		{
			ccMesh* mesh = ccHObjectCaster::ToMesh(currentObject);
			if (mesh->getAssociatedCloud())
				dependencies.insert(mesh->getAssociatedCloud());
			if (mesh->getMaterialSet())
				dependencies.insert(mesh->getMaterialSet());
			if (mesh->getTexCoordinatesTable())
				dependencies.insert(mesh->getTexCoordinatesTable());
			if (mesh->getTexCoordinatesTable())
				dependencies.insert(mesh->getTexCoordinatesTable());
		}
		else if (currentObject->isA(CC_TYPES::SUB_MESH))
		{
			dependencies.insert(currentObject->getParent());
		}
		else if (currentObject->isKindOf(CC_TYPES::POLY_LINE))
		{
			CCLib::GenericIndexedCloudPersist* cloud = static_cast<ccPolyline*>(currentObject)->getAssociatedCloud();
			ccPointCloud* pc = dynamic_cast<ccPointCloud*>(cloud);
			if (pc)
				dependencies.insert(pc);
			else
				ccLog::Warning(QString("[BIN] Poyline '%1' is associated to an unhandled vertices structure?!").arg(currentObject->getName()));
		}
		else if (currentObject->isKindOf(CC_TYPES::SENSOR))
		{
			ccIndexedTransformationBuffer* buffer = static_cast<ccSensor*>(currentObject)->getPositions();
			if (buffer)
				dependencies.insert(buffer);
		}
		else if (currentObject->isA(CC_TYPES::LABEL_2D))
		{
			cc2DLabel* label = static_cast<cc2DLabel*>(currentObject);
			for (unsigned i=0;i<label->size();++i)
			{
				const cc2DLabel::PickedPoint& pp = label->getPoint(i);
				dependencies.insert(pp.cloud);
			}
		}
		else if (currentObject->isA(CC_TYPES::FACET))
		{
			ccFacet* facet = static_cast<ccFacet*>(currentObject);
			if (facet->getOriginPoints())
				dependencies.insert(facet->getOriginPoints());
			if (facet->getContourVertices())
				dependencies.insert(facet->getContourVertices());
			if (facet->getPolygon())
				dependencies.insert(facet->getPolygon());
			if (facet->getContour())
				dependencies.insert(facet->getContour());
		}
		else if (currentObject->isKindOf(CC_TYPES::IMAGE))
		{
			ccImage* image = static_cast<ccImage*>(currentObject);
			if (image->getAssociatedSensor())
				dependencies.insert(image->getAssociatedSensor());
		}

		for (std::unordered_set<const ccHObject*>::const_iterator it = dependencies.begin(); it != dependencies.end(); ++it)
		{
			if (!object->find((*it)->getUniqueID()))
			{
				ccLog::Warning(QString("[BIN] Dependency broken: entity '%1' must also be in selection in order to save '%2'").arg((*it)->getName()).arg(currentObject->getName()));
				result = CC_FERR_BROKEN_DEPENDENCY_ERROR;
			}
		}
		//release some memory...
		dependencies.clear();

		for (unsigned i=0; i<currentObject->getChildrenNumber(); ++i)
			toCheck.push_back(currentObject->getChild(i));
	}

	if (result == CC_FERR_NO_ERROR)
		if (!object->toFile(out))
			result = CC_FERR_CONSOLE_ERROR;

	out.close();

	return result;
}
Beispiel #10
0
bool XMLTVParser::parseFile(
    QString filename, QList<ChanInfo> *chanlist,
    QMap<QString, QList<ProgInfo> > *proglist)
{
    QDomDocument doc;
    QFile f;

    if (!dash_open(f, filename, QIODevice::ReadOnly))
    {
        VERBOSE(VB_IMPORTANT, QString("Error unable to open '%1' for reading.")
                .arg(filename));
        return false;
    }

    QString errorMsg = "unknown";
    int errorLine = 0;
    int errorColumn = 0;

    if (!doc.setContent(&f, &errorMsg, &errorLine, &errorColumn))
    {
        VERBOSE(VB_IMPORTANT, QString("Error in %1:%2: %3")
            .arg(errorLine).arg(errorColumn).arg(errorMsg));

        f.close();
        return true;
    }

    f.close();

    // now we calculate the localTimezoneOffset, so that we can fix
    // the programdata if needed
    QString config_offset = gCoreContext->GetSetting("TimeOffset", "None");
    // we disable this feature by setting it invalid (> 840min = 14hr)
    int localTimezoneOffset = 841;

    if (config_offset == "Auto")
    {
        // we mark auto with the -ve of the disable magic number
        localTimezoneOffset = -841;
    }
    else if (config_offset != "None")
    {
        localTimezoneOffset = TimezoneToInt(config_offset);
        if (abs(localTimezoneOffset) > 840)
        {
            VERBOSE(VB_XMLTV, QString("Ignoring invalid TimeOffset %1")
                .arg(config_offset));
            localTimezoneOffset = 841;
        }
    }

    QDomElement docElem = doc.documentElement();

    QUrl baseUrl(docElem.attribute("source-data-url", ""));

    QUrl sourceUrl(docElem.attribute("source-info-url", ""));
    if (sourceUrl.toString() == "http://labs.zap2it.com/")
    {
        VERBOSE(VB_IMPORTANT, "Don't use tv_grab_na_dd, use the"
            "internal datadirect grabber.");
        exit(GENERIC_EXIT_SETUP_ERROR);
    }

    QString aggregatedTitle;
    QString aggregatedDesc;
    QString groupingTitle;
    QString groupingDesc;

    QDomNode n = docElem.firstChild();
    while (!n.isNull())
    {
        QDomElement e = n.toElement();
        if (!e.isNull())
        {
            if (e.tagName() == "channel")
            {
                ChanInfo *chinfo = parseChannel(e, baseUrl);
                chanlist->push_back(*chinfo);
                delete chinfo;
            }
            else if (e.tagName() == "programme")
            {
                ProgInfo *pginfo = parseProgram(e, localTimezoneOffset);

                if (pginfo->startts == pginfo->endts)
                {
                    /* Not a real program : just a grouping marker */
                    if (!pginfo->title.isEmpty())
                        groupingTitle = pginfo->title + " : ";

                    if (!pginfo->description.isEmpty())
                        groupingDesc = pginfo->description + " : ";
                }
                else
                {
                    if (pginfo->clumpidx.isEmpty())
                    {
                        if (!groupingTitle.isEmpty())
                        {
                            pginfo->title.prepend(groupingTitle);
                            groupingTitle.clear();
                        }

                        if (!groupingDesc.isEmpty())
                        {
                            pginfo->description.prepend(groupingDesc);
                            groupingDesc.clear();
                        }

                        (*proglist)[pginfo->channel].push_back(*pginfo);
                    }
                    else
                    {
                        /* append all titles/descriptions from one clump */
                        if (pginfo->clumpidx.toInt() == 0)
                        {
                            aggregatedTitle.clear();
                            aggregatedDesc.clear();
                        }

                        if (!pginfo->title.isEmpty())
                        {
                            if (!aggregatedTitle.isEmpty())
                                aggregatedTitle.append(" | ");
                            aggregatedTitle.append(pginfo->title);
                        }

                        if (!pginfo->description.isEmpty())
                        {
                            if (!aggregatedDesc.isEmpty())
                                aggregatedDesc.append(" | ");
                            aggregatedDesc.append(pginfo->description);
                        }
                        if (pginfo->clumpidx.toInt() ==
                            pginfo->clumpmax.toInt() - 1)
                        {
                            pginfo->title = aggregatedTitle;
                            pginfo->description = aggregatedDesc;
                            (*proglist)[pginfo->channel].push_back(*pginfo);
                        }
                    }
                }
                delete pginfo;
            }
        }
        n = n.nextSibling();
    }

    return true;
}
const KstTimezones::ZoneMap KstTimezones::allZones()
{
    // Have we already done all the hard work? If not, create the cache.
    if (m_zones)
        return *m_zones;
    m_zones = new ZoneMap();

    // Go read the database.
    //
    // On Windows, HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones
    // is the place to look. The TZI binary value is the TIME_ZONE_INFORMATION structure.
    //
    // For Unix its all easy except knowing where to look. Try the LSB location first.
    QFile f;
    m_zoneinfoDir = "/usr/share/zoneinfo";
    f.setName(m_zoneinfoDir + "/zone.tab");
    if (!f.open(IO_ReadOnly))
    {
        m_zoneinfoDir = "/usr/lib/zoneinfo";
        f.setName(m_zoneinfoDir + "/zone.tab");
        if (!f.open(IO_ReadOnly))
        {
            m_zoneinfoDir = ::getenv("TZDIR");
            f.setName(m_zoneinfoDir + "/zone.tab");
            if (m_zoneinfoDir.isEmpty() || !f.open(IO_ReadOnly))
            {
                // Solaris support. Synthesise something that looks like a zone.tab.
                //
                // /bin/grep -h ^Zone /usr/share/lib/zoneinfo/src/* | /bin/awk '{print "??\t+9999+99999\t" $2}'
                //
                // where the country code is set to "??" and the lattitude/longitude
                // values are dummies.
                m_zoneinfoDir = "/usr/share/lib/zoneinfo";
                KTempFile temp;
                KShellProcess reader;
                reader << "/bin/grep" << "-h" << "^Zone" << m_zoneinfoDir << "/src/*" << temp.name() << "|" <<
                    "/bin/awk" << "'{print \"??\\t+9999+99999\\t\" $2}'";
                // Note the use of blocking here...it is a trivial amount of data!
                temp.close();
                reader.start(KProcess::Block);
                f.setName(temp.name());
                if (!temp.status() || !f.open(IO_ReadOnly))
                {
                    return *m_zones;
                }
            }
        }
    }

    // Parse the zone.tab.
    QTextStream str(&f);
    QRegExp lineSeparator("[ \t]");
    QRegExp ordinateSeparator("[+-]");
    KSharedPtr<KstTimezoneSource> db(new KstTimezoneSource(m_zoneinfoDir));
    while (!str.atEnd())
    {
        QString line = str.readLine();
        if (line.isEmpty() || '#' == line[0])
            continue;
        QStringList tokens = KStringHandler::perlSplit(lineSeparator, line, 4);
        if (tokens.count() < 3)
        {
            continue;
        }

        // Got three tokens. Now check for two ordinates plus first one is "".
        QStringList ordinates = KStringHandler::perlSplit(ordinateSeparator, tokens[1], 2);
        if (ordinates.count() < 2)
        {
            continue;
        }

        float latitude = convertCoordinate(ordinates[1]);
        float longitude = convertCoordinate(ordinates[2]);

        // Add entry to list.
        if (tokens[0] == "??")
            tokens[0] = "";
        KstTimezone *timezone = new KstTimezone(db, tokens[2], tokens[0], latitude, longitude, tokens[3]);
        add(timezone);
    }
    f.close();
    return *m_zones;
}
void ConfigStation::genButtonClicked()
{
    QDir dir;
    dir.setPath( c.PARAMSDIR + "/staInfo");
    QStringList files;
    QString fileName = "*.sta";
    files = dir.entryList(QStringList(fileName), QDir::Files | QDir::NoSymLinks);

    for(int i=0;i<files.count();i++)
    {
        if(files[i] == filenameLE->text() + ".sta")
        {
            if(!korean) QMessageBox::warning( this, "Information", "Duplicate Station file name.\nPlease use other name.");
            else QMessageBox::warning( this, codec->toUnicode("정보"), codec->toUnicode("중복되는 파일명을 가진 파일이 존재합니다.\n다른 파일명을 사용하십시오."));
            return;
        }
    }

    if(filenameLE->text() == "")
    {
        if(!korean) QMessageBox::warning( this, "Information", "Please Input a file name.");
        else QMessageBox::warning( this, codec->toUnicode("정보"), codec->toUnicode("파일명을 입력하십시오.(영문, 숫자만 사용)") );
        return;
    }

    if(descLE->text() == "")
    {
        QMessageBox::warning( this, "Information", "Please Input a description.");

        if(!korean) QMessageBox::warning( this, "Information", "Please Input a description.");
        else QMessageBox::warning( this, codec->toUnicode("정보"), codec->toUnicode("관측소 설명란을 입력하십시오.(영문, 숫자만 사용)") );
        return;
    }

    int count = 0;

    for(int i=0;i<sta.size();i++)
    {
        if(sta[count] == "")
            break;
        count++;
    }

    QFile file;
    /* generate station file. */
    QString staFileName = c.PARAMSDIR + "/staInfo/" + filenameLE->text() + ".sta";
    file.setFileName( staFileName );

    if( file.open( QIODevice::WriteOnly ) )
    {
        QTextStream stream( &file ) ;
        stream <<  "Filename:" << filenameLE->text() << "\n";
        stream <<  "Description:" << descLE->text() << "\n" ;

        for(int i=0;i<count;i++)
        {
            if(comp[i] == "Z/N/E")
            {
                stream << sta[i] << " " << chan[i] << "Z" << " " << loc[i] << " " << net[i] << " " << lat[i] << " " << lon[i] << " " << elev[i] << "\n";
                stream << sta[i] << " " << chan[i] << "N" << " " << loc[i] << " " << net[i] << " " << lat[i] << " " << lon[i] << " " << elev[i] << "\n";
                stream << sta[i] << " " << chan[i] << "E" << " " << loc[i] << " " << net[i] << " " << lat[i] << " " << lon[i] << " " << elev[i] << "\n";
            }
            else if(comp[i] == "Z")
                stream << sta[i] << " " << chan[i] << "Z" << " " << loc[i] << " " << net[i] << " " << lat[i] << " " << lon[i] << " " << elev[i] << "\n";
            else if(comp[i] == "N")
                stream << sta[i] << " " << chan[i] << "N" << " " << loc[i] << " " << net[i] << " " << lat[i] << " " << lon[i] << " " << elev[i] << "\n";
            else if(comp[i] == "E")
                stream << sta[i] << " " << chan[i] << "E" << " " << loc[i] << " " << net[i] << " " << lat[i] << " " << lon[i] << " " << elev[i] << "\n";
            else if(comp[i] == "N/E")
            {
                stream << sta[i] << " " << chan[i] << "N" << " " << loc[i] << " " << net[i] << " " << lat[i] << " " << lon[i] << " " << elev[i] << "\n";
                stream << sta[i] << " " << chan[i] << "E" << " " << loc[i] << " " << net[i] << " " << lat[i] << " " << lon[i] << " " << elev[i] << "\n";
            }
        }
        file.close() ;
    }

    QString cmd = "cp " + staFileName + " " + c.PARAMSDIR + "/sta.info";
    system(cmd.toLatin1().data());

    STAFILE stafile;

    FileGenerator *gen = new FileGenerator;
    stafile = gen->makeSTAFILE(c, false);
    gen->pick_ew_gen(c, stafile);
    gen->pick_FP_gen(c, stafile);
    gen->hinv_gen(c, stafile);
    gen->tanklist_gen(c, stafile);
    gen->binder_gen(c, stafile);
    gen->ew2mseed_gen(c, stafile);
    gen->nlloc_gen(false, c, stafile);

    QMessageBox msgBox;
    if(!korean) msgBox.setText("Staions Info. file generated and loaded.");
    else msgBox.setText(codec->toUnicode("관측소 정보 파일 생성 완료."));
    msgBox.exec();
    accept();
}
Beispiel #13
0
/*!
 * \brief Converts a spice netlist into Qucs format and outputs it.
 */
void SimMessage::nextSPICE()
{
  QString Line;
  for(;;) {  // search for next SPICE component
    Line = *(Collect.begin());
    Collect.erase(Collect.begin());
    if(Line == "*") {  // worked on all components ?
      startSimulator(); // <<<<<================== go on ===
      return;
    }
// FIXME #warning SPICE section below not being covered?
    qDebug() << "goin thru SPICE branch on simmmessage.cpp";
    if(Line.left(5) == "SPICE") {
      if(Line.at(5) != 'o') insertSim = true;
      else insertSim = false;
      break;
    }
    Collect.append(Line);
  }


  QString FileName = Line.section('"', 1,1);
  Line = Line.section('"', 2);  // port nodes
  if(Line.isEmpty())  makeSubcircuit = false;
  else  makeSubcircuit = true;

  QString prog;
  QStringList com;
  prog = QucsSettings.BinDir + "qucsconv" + executableSuffix;
  if(makeSubcircuit)
    com << "-g" << "_ref";
  com << "-if" << "spice" << "-of" << "qucs";

  QFile SpiceFile;
  if(FileName.indexOf(QDir::separator()) < 0)  // add path ?
    SpiceFile.setFileName(QucsSettings.QucsWorkDir.path() + QDir::separator() + FileName);
  else
    SpiceFile.setFileName(FileName);
  if(!SpiceFile.open(QIODevice::ReadOnly)) {
    ErrText->appendPlainText(tr("ERROR: Cannot open SPICE file \"%1\".").arg(FileName));
    FinishSimulation(-1);
    return;
  }

  if(makeSubcircuit) {
    Stream << "\n.Def:" << misc::properName(FileName) << " ";

    Line.replace(',', ' ');
    Stream << Line;
    if(!Line.isEmpty()) Stream << " _ref";
  }
  Stream << "\n";

  ProgressText = "";

  qDebug() << "start QucsConv" << prog << com.join(" ");
  SimProcess.start(prog, com);

  if(!SimProcess.Running) {
    ErrText->appendPlainText(tr("SIM ERROR: Cannot start QucsConv!"));
    FinishSimulation(-1);
    return;
  }

  QByteArray SpiceContent = SpiceFile.readAll();
  SpiceFile.close();
  QString command(SpiceContent); //to convert byte array to string
  SimProcess.setStandardInputFile(command);  //? FIXME works?
  qDebug() << command;
  connect(&SimProcess, SIGNAL(wroteToStdin()), SLOT(slotCloseStdin()));
}
Beispiel #14
0
MainWindow::MainWindow(const QUrl& url)
{
    progress = 0;

    QFile file;
    file.setFileName(":/jquery.min.js");
    file.open(QIODevice::ReadOnly);
    jQuery = file.readAll();
    jQuery.append("\nvar qt = { 'jQuery': jQuery.noConflict(true) };");
    file.close();
//! [1]

    QNetworkProxyFactory::setUseSystemConfiguration(true);

//! [2]
    view = new QWebView(this);
    view->load(url);
    connect(view, SIGNAL(loadFinished(bool)), SLOT(adjustLocation()));
    connect(view, SIGNAL(titleChanged(QString)), SLOT(adjustTitle()));
    connect(view, SIGNAL(loadProgress(int)), SLOT(setProgress(int)));
    connect(view, SIGNAL(loadFinished(bool)), SLOT(finishLoading(bool)));

    locationEdit = new QLineEdit(this);
    locationEdit->setSizePolicy(QSizePolicy::Expanding, locationEdit->sizePolicy().verticalPolicy());
    connect(locationEdit, SIGNAL(returnPressed()), SLOT(changeLocation()));

    QToolBar *toolBar = addToolBar(tr("导航"));
    toolBar->addAction(view->pageAction(QWebPage::Back));
    toolBar->addAction(view->pageAction(QWebPage::Forward));
    toolBar->addAction(view->pageAction(QWebPage::Reload));
    toolBar->addAction(view->pageAction(QWebPage::Stop));
    toolBar->addWidget(locationEdit);
//! [2]
    QMenu *fileMenu = menuBar()->addMenu(tr("文件(&F)"));
    QAction *newWindowAction = new QAction(tr("新建窗口"),this);
    connect(newWindowAction, SIGNAL(triggered()),SLOT(newWindow()));
    fileMenu->addAction(newWindowAction);
    QAction *closeWindowAction = new QAction(tr("关闭窗口"),this);
    connect(closeWindowAction, SIGNAL(triggered()),SLOT(closeWindow()));
    fileMenu->addAction(closeWindowAction);

    QMenu *viewMenu = menuBar()->addMenu(tr("查看(&V)"));
    QAction* viewSourceAction = new QAction(tr("页面源代码"), this);
    connect(viewSourceAction, SIGNAL(triggered()), SLOT(viewSource()));
    viewMenu->addAction(view->pageAction(QWebPage::Stop));
    viewMenu->addAction(view->pageAction(QWebPage::Reload));
    viewMenu->addSeparator();
    viewMenu->addAction(viewSourceAction);

//! [3]

    QMenu *historyMenu = menuBar()->addMenu(tr("历史(&H)"));
    historyMenu->addAction(view->pageAction(QWebPage::Back));
    historyMenu->addAction(view->pageAction(QWebPage::Forward));

    QMenu *effectMenu = menuBar()->addMenu(tr("效果(&E)"));
    effectMenu->addAction(tr("高亮所有链接"), this, SLOT(highlightAllLinks()));
    rotateAction = new QAction(this);
    rotateAction->setIcon(style()->standardIcon(QStyle::SP_FileDialogDetailedView));
    rotateAction->setCheckable(true);
    rotateAction->setText(tr("倒转图像"));
    connect(rotateAction, SIGNAL(toggled(bool)), this, SLOT(rotateImages(bool)));
    effectMenu->addAction(rotateAction);

    QMenu *toolsMenu = menuBar()->addMenu(tr("工具(&T)"));
    toolsMenu->addAction(tr("移除 GIF 动画"), this, SLOT(removeGifImages()));
    toolsMenu->addAction(tr("移除所有内联框架"), this, SLOT(removeInlineFrames()));
    toolsMenu->addAction(tr("移除所有对象元素"), this, SLOT(removeObjectElements()));
    toolsMenu->addAction(tr("移除所有嵌入元素"), this, SLOT(removeEmbeddedElements()));

	QMenu *helpMenu = menuBar()->addMenu(tr("帮助(&H)"));
	helpMenu->addAction(tr("关于 Looplorer"), this, SLOT(aboutLooplorer()));

	setCentralWidget(view);
    setUnifiedTitleAndToolBarOnMac(true);

	view->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
	clickLink();

    windowNum++;

}
Beispiel #15
0
void Parser::parseToFile()
{
    dirFilters();

#ifdef Q_OS_LINUX
    if(!itsDir->exists(itsArgv[1]))
#else
    if(!itsDir->exists(QString::fromLocal8Bit(itsArgv[1])))
#endif
    {
        qCritical() << "EROR: path to list don't exist\n";
        return;
    }

#ifdef Q_OS_LINUX
    itsDir->cd(itsArgv[1]);
#else
    itsDir->cd(QString::fromLocal8Bit(itsArgv[1]));
#endif
    QFile file;
    QFileInfo info;

#ifdef Q_OS_LINUX
    file.setFileName(itsArgv[2]);
#else
    file.setFileName(QString::fromLocal8Bit(itsArgv[2]));
#endif
    info.setFile(file);

    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        qCritical() << "ERROR opening file:" << file.fileName();
        return;
    }

    QTextStream out(&file);
#ifdef Q_OS_LINUX
    out << "ROOT DIR:\n" << QDir::toNativeSeparators(itsArgv[1]) << ":" << "\n";
#else
    out << "ROOT DIR:\n" << QDir::toNativeSeparators(QString::fromLocal8Bit(itsArgv[1])) << ":" << "\n";
#endif

    QString filePath = info.absoluteFilePath();

    if(itsOptions.testFlag(RECURSIVE))
    {
        recursive(filePath, out);
    }
    else
    {
        notRecursive(filePath, out);
    }

    QString p = info.filePath();
    QString n = info.fileName();

    QTextStream itsOut(stdout);

    itsOut << "\nSaving file: " << info.fileName()
           << " into "
           << QDir::toNativeSeparators(p.remove(p.size() - n.size(), p.size() - 1))
           << "\n";

    file.close();
}
Beispiel #16
0
void
MainWindow::makeUI()
{
    setObjectName(QString::fromUtf8("MainWindow"));

#if 0
    action_Print = new QAction(this);
    action_Print->setObjectName(QString::fromUtf8("action_Print"));
#endif

#if 1
    action_Exit = new QAction(this);
    action_Exit->setObjectName(QString::fromUtf8("action_Exit"));
	//connect(action_Exit, SIGNAL(triggered()), qApp, SLOT(quit()));
	connect(action_Exit, SIGNAL(triggered()), this, SLOT(close()));
#endif

    action_Multiplot = new QAction(this);
    action_Multiplot->setObjectName(QString::fromUtf8("action_Multiplot"));
	connect(action_Multiplot, SIGNAL(triggered()), this, SLOT(showMultiplot()));

    action_Archivesheet = new QAction(this);
    action_Archivesheet->setObjectName(QString::fromUtf8("action_Archivesheet"));
	connect(action_Archivesheet, SIGNAL(triggered()), this, SLOT(showArchivesheet()));

    action_Archiverviewer = new QAction(this);
    action_Archiverviewer->setObjectName(QString::fromUtf8("action_Archiverviewer"));
	connect(action_Archiverviewer, SIGNAL(triggered()), this, SLOT(showArchiverviewer()));

    action_SignalDB = new QAction(this);
    action_SignalDB->setObjectName(QString::fromUtf8("action_SignalDB"));
	connect(action_SignalDB, SIGNAL(triggered()), this, SLOT(showSignalDB()));

    action_PVListV = new QAction(this);
    action_PVListV->setObjectName(QString::fromUtf8("action_PVListV"));
	connect(action_PVListV, SIGNAL(triggered()), this, SLOT(showPVListViewer()));

	action_Manual = new QAction(this);
	action_Manual->setObjectName(QString::fromUtf8("action_Manual"));
	connect(action_Manual, SIGNAL(triggered()), this, SLOT(showManual()));

	action_AboutECH = new QAction(this);
	action_AboutECH->setObjectName(QString::fromUtf8("action_AboutECH"));
	connect(action_AboutECH, SIGNAL(triggered()), this, SLOT(showAboutECH()));

    centralwidget = new QWidget(this);
    centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
    //centralwidget->setGeometry(QRect(0, 0, 1280, 821));
	
    widget = new QWidget(centralwidget);
    widget->setObjectName(QString::fromUtf8("widget"));
    widget->setGeometry(QRect(200, 0, 1080, 821));
    widget->setMinimumSize(QSize(400, 0));
    vboxLayout = new QVBoxLayout(widget);
    vboxLayout->setSpacing(0);
    vboxLayout->setMargin(0);
    vboxLayout->setObjectName(QString::fromUtf8("vboxLayout"));
    dockWidget = new QDockWidget(widget);
    dockWidget->setObjectName(QString::fromUtf8("dockWidget"));
    QSizePolicy sizePolicy(static_cast<QSizePolicy::Policy>(7), static_cast<QSizePolicy::Policy>(7));
    sizePolicy.setHorizontalStretch(0);
    sizePolicy.setVerticalStretch(0);
    sizePolicy.setHeightForWidth(dockWidget->sizePolicy().hasHeightForWidth());
    dockWidget->setSizePolicy(sizePolicy);
    //dockWidget->setFeatures(QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable|QDockWidget::NoDockWidgetFeatures);
    //dockWidget->setFeatures(QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable);
    //dockWidget->setAllowedAreas(Qt::AllDockWidgetAreas);
    dockWidgetContents = new QWidget(dockWidget);
    dockWidgetContents->setObjectName(QString::fromUtf8("dockWidgetContents"));

    vdockLayout = new QVBoxLayout(widget);
    vdockLayout->setSpacing(0);
    vdockLayout->setMargin(0);
    vdockLayout->setObjectName(QString::fromUtf8("vdockLayout"));

    stackedWidget = new QStackedWidget(dockWidgetContents);
    stackedWidget->setObjectName(QString::fromUtf8("stackedWidget"));
    stackedWidget->setGeometry(QRect(0, 0, 1080, 821));
    dockWidget->setWidget(dockWidgetContents);

    vboxLayout->addWidget(dockWidget);

	dockWidgetContents->setLayout(vdockLayout);
	vdockLayout->addWidget(stackedWidget);

    tabWidget = new QTabWidget(centralwidget);
    tabWidget->setObjectName(QString::fromUtf8("tabWidget"));
    tabWidget->setGeometry(QRect(0, 0, 200, 821));
    QSizePolicy sizePolicy1(static_cast<QSizePolicy::Policy>(5), static_cast<QSizePolicy::Policy>(5));
    sizePolicy1.setHorizontalStretch(0);
    sizePolicy1.setVerticalStretch(0);
    sizePolicy1.setHeightForWidth(tabWidget->sizePolicy().hasHeightForWidth());

#if 1
	/* TabWidget color setting */
    QPalette palettetw;

    QBrush brushtw1(QColor(60, 76, 100, 255));
    brushtw1.setStyle(Qt::SolidPattern);
    palettetw.setBrush(QPalette::Active, QPalette::Window, brushtw1);
    //palettetw.setBrush(QPalette::Inactive, QPalette::Window, brushtw1);
    //palettetw.setBrush(QPalette::Disabled, QPalette::Window, brushtw1);

    QBrush brushtw2(QColor(60, 76, 100, 255));
    brushtw2.setStyle(Qt::SolidPattern);
    palettetw.setBrush(QPalette::Active, QPalette::Base, brushtw2);
    //palettetw.setBrush(QPalette::Inactive, QPalette::Base, brushtw2);
    //palettetw.setBrush(QPalette::Disabled, QPalette::Base, brushtw2);

    palettetw.setBrush(QPalette::Active, QPalette::Button, brushtw1);
    //palettetw.setBrush(QPalette::Inactive, QPalette::Button, brushtw1);
    //palettetw.setBrush(QPalette::Disabled, QPalette::Button, brushtw1);

    QBrush brushtw3(QColor(255, 255, 255, 255));
    brushtw3.setStyle(Qt::SolidPattern);
    palettetw.setBrush(QPalette::Active, QPalette::ButtonText, brushtw3);
    //palettetw.setBrush(QPalette::Inactive, QPalette::ButtonText, brushtw3);
    //palettetw.setBrush(QPalette::Disabled, QPalette::ButtonText, brushtw3);

    palettetw.setBrush(QPalette::Active, QPalette::WindowText, brushtw3);
    //palettetw.setBrush(QPalette::Inactive, QPalette::WindowText, brushtw3);
    //palettetw.setBrush(QPalette::Disabled, QPalette::WindowText, brushtw3);

    tabWidget->setPalette(palettetw);

#endif

#if 0
    QPalette palettetw;
    QBrush brushtw1(QColor(0, 0, 55, 200));
    brushtw1.setStyle(Qt::SolidPattern);
    palettetw.setBrush(QPalette::Active, QPalette::Window, brushtw1);
    QBrush brushtw2(QColor(96, 96, 129, 200));
    brushtw2.setStyle(Qt::SolidPattern);
    palettetw.setBrush(QPalette::Active, QPalette::Base, brushtw2);
    QBrush brushtw3(QColor(100, 100, 100, 255));
    brushtw3.setStyle(Qt::SolidPattern);
    palettetw.setBrush(QPalette::Active, QPalette::WindowText, brushtw3);
    //QBrush brushtw4(QColor(255, 255, 255, 50));
    QBrush brushtw4(QColor(55, 55, 55, 100));
    brushtw4.setStyle(Qt::SolidPattern);
    palettetw.setBrush(QPalette::Active, QPalette::Button, brushtw4);
    tabWidget->setPalette(palettetw);
#endif

    tabWidget->setSizePolicy(sizePolicy1);
    tabWidget->setMaximumSize(QSize(16777215, 16777215));
    tabWidget->setTabPosition(QTabWidget::West);
    tabWidget->setTabShape(QTabWidget::Triangular);
    tabWidget->setElideMode(Qt::ElideNone);

    tab_0 = new QWidget();
    tab_0->setObjectName(QString::fromUtf8("tab_0"));
    QFont font;
    font.setPointSize(14);
    vboxLayout0 = new QVBoxLayout(tab_0);
    vboxLayout0->setSpacing(6);
    vboxLayout0->setMargin(4);
    vboxLayout0->setAlignment(Qt::AlignTop);
    vboxLayout0->setObjectName(QString::fromUtf8("vboxLayout0"));

    QPalette paletteb;
    QBrush brushb(QColor(211, 197, 179, 255));
    brushb.setStyle(Qt::SolidPattern);
    paletteb.setBrush(QPalette::Active, QPalette::Button, brushb);
    //paletteb.setBrush(QPalette::Inactive, QPalette::Button, brushb);
    //paletteb.setBrush(QPalette::Disabled, QPalette::Button, brushb);

    QBrush brushbt(QColor(106, 88, 62, 255));
    brushbt.setStyle(Qt::SolidPattern);
    paletteb.setBrush(QPalette::Active, QPalette::ButtonText, brushbt);
    //paletteb.setBrush(QPalette::Inactive, QPalette::ButtonText, brushbt);
    //paletteb.setBrush(QPalette::Disabled, QPalette::ButtonText, brushbt);

    pushButton[0] = new QPushButton(tab_0);
    pushButton[0]->setObjectName(QString::fromUtf8("pushButton_0"));
    pushButton[0]->setFont(font);
    pushButton[0]->setText(QApplication::translate("MainWindow", "Operation", 0, QApplication::UnicodeUTF8));
    pushButton[0]->setPalette(paletteb);
    vboxLayout0->addWidget(pushButton[0]);

    pushButton[1] = new QPushButton(tab_0);
    pushButton[1]->setObjectName(QString::fromUtf8("pushButton_1"));
    pushButton[1]->setFont(font);
    pushButton[1]->setText(QApplication::translate("MainWindow", "Interlock", 0, QApplication::UnicodeUTF8));
    pushButton[1]->setPalette(paletteb);
    vboxLayout0->addWidget(pushButton[1]);

    pushButton[2] = new QPushButton(tab_0);
    pushButton[2]->setObjectName(QString::fromUtf8("pushButton_2"));
    pushButton[2]->setFont(font);
    pushButton[2]->setText(QApplication::translate("MainWindow", "DAQ", 0, QApplication::UnicodeUTF8));
    pushButton[2]->setPalette(paletteb);
    vboxLayout0->addWidget(pushButton[2]);

#if 0
    pushButton[3] = new QPushButton(tab_0);
    pushButton[3]->setObjectName(QString::fromUtf8("pushButton_3"));
    pushButton[3]->setFont(font);
    pushButton[3]->setText(QApplication::translate("MainWindow", "Waveform Graph2", 0, QApplication::UnicodeUTF8));
    pushButton[3]->setPalette(paletteb);
    vboxLayout0->addWidget(pushButton[3]);
#endif

#if 0
    spacerItem0 = new QSpacerItem(20, 1, QSizePolicy::Minimum, QSizePolicy::Expanding);
    vboxLayout0->addItem(spacerItem0);
#endif
    frame = new QFrame(tab_0);
    frame->setObjectName(QString::fromUtf8("frame"));
    QSizePolicy sizePolicy2(static_cast<QSizePolicy::Policy>(5), static_cast<QSizePolicy::Policy>(5));
    sizePolicy2.setHorizontalStretch(1);
    sizePolicy2.setVerticalStretch(0);
    sizePolicy2.setHeightForWidth(frame->sizePolicy().hasHeightForWidth());
    frame->setSizePolicy(sizePolicy2);
    frame->setMinimumSize(QSize(16, 704));
    frame->setFrameShape(QFrame::StyledPanel);
    frame->setFrameShadow(QFrame::Raised);

    vboxLayout0->addWidget(frame);
	QVBoxLayout *vfboxLayout = new QVBoxLayout(frame);
	vfboxLayout->setSpacing(0);
	vfboxLayout->setMargin(0);
	vfboxLayout->setObjectName(QString::fromUtf8("vfboxLayout"));

	QUiLoader m_loader;
	QFile *file = new QFile("/usr/local/opi/ui/ECH_Menu_Area.ui");
	file->open(QFile::ReadOnly);
	QWidget *m_widget = m_loader.load(file);
	file->close();
	vfboxLayout->addWidget(m_widget);

	AttachChannelAccess *pattachECHMenu = new AttachChannelAccess(frame);

/* TG remove 20130704
    tab_1 = new QWidget();
    tab_1->setObjectName(QString::fromUtf8("tab_1"));
    vboxLayout1 = new QVBoxLayout(tab_1);
    vboxLayout1->setSpacing(6);
    vboxLayout1->setMargin(4);
    vboxLayout1->setObjectName(QString::fromUtf8("vboxLayout1"));

    pushButton[3] = new QPushButton(tab_1);
    pushButton[3]->setObjectName(QString::fromUtf8("pushButton_3"));
    pushButton[3]->setFont(font);
    pushButton[3]->setText(QApplication::translate("MainWindow", "DAQ WavePattern", 0, QApplication::UnicodeUTF8));
    pushButton[3]->setPalette(paletteb);
    vboxLayout1->addWidget(pushButton[3]);

	spacerItem1 = new QSpacerItem(20, 1, QSizePolicy::Minimum, QSizePolicy::Expanding);
	vboxLayout1->addItem(spacerItem1);


    frame2 = new QFrame(tab_1);
    frame2->setObjectName(QString::fromUtf8("frame2"));
    QSizePolicy sizePolicy3(static_cast<QSizePolicy::Policy>(5), static_cast<QSizePolicy::Policy>(5));
    sizePolicy3.setHorizontalStretch(1);
    sizePolicy3.setVerticalStretch(0);
    sizePolicy3.setHeightForWidth(frame2->sizePolicy().hasHeightForWidth());
    frame2->setSizePolicy(sizePolicy3);
    frame2->setMinimumSize(QSize(16, 704));
    frame2->setFrameShape(QFrame::StyledPanel);
    frame2->setFrameShadow(QFrame::Raised);

    vboxLayout1->addWidget(frame2);
	QVBoxLayout *vfboxLayout1 = new QVBoxLayout(frame2);
	vfboxLayout1->setSpacing(0);
	vfboxLayout1->setMargin(0);
	vfboxLayout1->setObjectName(QString::fromUtf8("vfboxLayout1"));
	QUiLoader m_loader1;
	QFile *file1 = new QFile("/usr/local/opi/ui/ECH_Menu_Area.ui");
	file1->open(QFile::ReadOnly);
	QWidget *m_widget1 = m_loader1.load(file1);
	file1->close();
	vfboxLayout1->addWidget(m_widget1);

	AttachChannelAccess *pattachECHSubMenu = new AttachChannelAccess(frame2);

*/

	/*
    spacerItem1 = new QSpacerItem(20, 20, QSizePolicy::Fixed, QSizePolicy::Fixed);
    vfboxLayout->addItem(spacerItem1);

	QUiLoader m_loader2;
	QFile *file2 = new QFile("/usr/local/opi/ui/ECH_Menu_Area2.ui");
	file2->open(QFile::ReadOnly);
	QWidget *m_widget2 = m_loader2.load(file2);
	file2->close();
	vfboxLayout->addWidget(m_widget2);
	*/




    tabWidget->addTab(tab_0, QApplication::translate("MainWindow", "ECH Main panels", 0, QApplication::UnicodeUTF8));
//    tabWidget->addTab(tab_1, QApplication::translate("MainWindow", "ECH Sub panels", 0, QApplication::UnicodeUTF8));

    menubar = new QMenuBar(this);
    menubar->setObjectName(QString::fromUtf8("menubar"));
    menubar->setGeometry(QRect(0, 0, 1280, 30));
    menu_File = new QMenu(menubar);
    menu_File->setObjectName(QString::fromUtf8("menu_File"));
    menu_Util = new QMenu(menubar);
    menu_Util->setObjectName(QString::fromUtf8("menu_Util"));
	menu_Help = new QMenu(menubar);
	menu_Help->setObjectName(QString::fromUtf8("menu_Help"));
    setMenuBar(menubar);

    QLabel *slabel1 = new QLabel("Set your mouse on the dynamic value to read PVNAME.");
    slabel1->setAlignment(Qt::AlignHCenter);
    slabel1->setMinimumSize(slabel1->sizeHint());
    slabel1->setFrameStyle(QFrame::Panel | QFrame::Plain);

    QFrame *sframe = new QFrame();
    QVBoxLayout *svlayout = new QVBoxLayout(sframe);
    svlayout->setSpacing(1);
    svlayout->setMargin(2);

    statusBar()->addWidget(sframe,1);
    
    toolBar = new QToolBar(this);
    toolBar->setObjectName(QString::fromUtf8("toolBar"));

    QPalette palette;
    QBrush brush(QColor(108, 147, 255, 100));
    brush.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::Base, brush);
    palette.setBrush(QPalette::Active, QPalette::AlternateBase, brush);
    QBrush brush1(QColor(44, 51, 91, 100));
    brush1.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Active, QPalette::Window, brush1);
    QBrush brush2(QColor(108, 147, 255, 100));
    brush2.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Inactive, QPalette::Base, brush2);
    QBrush brush3(QColor(44, 51, 91, 100));
    brush3.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Inactive, QPalette::Window, brush3);
    QBrush brush4(QColor(44, 51, 91, 100));
    brush4.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Disabled, QPalette::Base, brush4);
    QBrush brush5(QColor(44, 51, 91, 100));
    brush5.setStyle(Qt::SolidPattern);
    palette.setBrush(QPalette::Disabled, QPalette::Window, brush5);
    toolBar->setPalette(palette);
    toolBar->setOrientation(Qt::Horizontal);
    addToolBar(static_cast<Qt::ToolBarArea>(4), toolBar);

    menubar->addAction(menu_File->menuAction());
    menubar->addAction(menu_Util->menuAction());
    //menubar->addAction(menu_View->menuAction());
	menubar->addSeparator();
    menubar->addAction(menu_Help->menuAction());
#if 0
    menu_File->addAction(action_Print);
#endif
    menu_File->addAction(action_Exit);

    menu_Util->addAction(action_Multiplot);
    menu_Util->addAction(action_Archivesheet);
    menu_Util->addAction(action_Archiverviewer);
    menu_Util->addAction(action_SignalDB);
    menu_Util->addAction(action_PVListV);

#if 0
	menu_Help->addAction(action_Manual);
#endif
	menu_Help->addAction(action_AboutECH);

#if 1
    QFrame *tbframe = new QFrame();
    toolBar->addWidget(tbframe);

    QHBoxLayout *tblayout = new QHBoxLayout(tbframe);
    tblayout->QLayout::setAlignment(Qt::AlignRight|Qt::AlignVCenter);
    tblayout->setSpacing(0);
    tblayout->setMargin(0);
    tblayout->setObjectName(QString::fromUtf8("toolBarLayout"));

    QSpacerItem *tbspacer = new QSpacerItem(1000, 10, QSizePolicy::Fixed, QSizePolicy::Fixed);
    QSpacerItem *tbspacer2 = new QSpacerItem(5, 5, QSizePolicy::Fixed, QSizePolicy::Fixed);

	//CAGraphic *ioc1HB = new CAGraphic();
	ioc1HB = new CAGraphic();
	ioc1HB->setLineWidth(2);
	ioc1HB->setMinimumSize(QSize(20,20));
	ioc1HB->setMaximumSize(QSize(20,20));
	ioc1HB->setFillColor(QColor("white"));
	ioc1HB->setLineColor(QColor("black"));
	ioc1HB->setFillMode(StaticGraphic::Solid);
	ioc1HB->setPvname("ECH_HEARTBEAT");
	ioc1HB->setFillDisplayMode(CAGraphic::ActInact);
	ioc1HB->setObjectName("CAGraphic_ioc1HB");
	ioc1HB->setToolTip("ECH IOC HEART BEAT");

	//CAGraphic *ioc2HB = new CAGraphic();
/*
	ioc2HB = new CAGraphic();
	ioc2HB->setLineWidth(2);
	ioc2HB->setMinimumSize(QSize(20,20));
	ioc2HB->setMaximumSize(QSize(20,20));
	ioc2HB->setFillColor(QColor("white"));
	ioc2HB->setLineColor(QColor("black"));
	ioc2HB->setFillMode(StaticGraphic::Solid);
	ioc2HB->setPvname("ECH_LTU_HEARTBEAT");
	ioc2HB->setFillDisplayMode(CAGraphic::ActInact);
	ioc2HB->setObjectName("CAGraphic_ioc2HB");
	ioc2HB->setToolTip("ECH LTU HEART BEAT");
*/

    font.setPointSize(12);
    //CAWclock *wclock1 = new CAWclock();
    wclock1 = new CAWclock();
	wclock1->setMinimumSize(QSize(160,20));
	wclock1->setMaximumSize(QSize(160,20));
	wclock1->setPvname("ECH_IOC_WCLOCK.RVAL");
	wclock1->setFont(font);
	wclock1->setObjectName("CAWclock_wclock1");
	
    //QLabel *logo = new QLabel("KSTAR logo");
    logo = new QLabel("KSTAR logo");
    logo->setPixmap(QPixmap::fromImage(QImage(":/images/kstar.png")));

    tblayout->addItem(tbspacer);
    tblayout->addWidget(wclock1);
    tblayout->addItem(tbspacer2);
	tblayout->addWidget(ioc1HB);
//	tblayout->addWidget(ioc2HB);
    tblayout->addItem(tbspacer2);
    tblayout->addWidget(logo);
	AttachChannelAccess *pattachTB = new AttachChannelAccess(tbframe);
#endif

    QSize size(1280, 1024);
    size = size.expandedTo(minimumSizeHint());
    resize(size);
    tabWidget->setCurrentIndex(0);
    QMetaObject::connectSlotsByName(this);

    msgframe = new QFrame(centralwidget);
    msgframe->setObjectName(QString::fromUtf8("msgframe"));
    QSizePolicy sizePolicy4(static_cast<QSizePolicy::Policy>(5), static_cast<QSizePolicy::Policy>(5));
    sizePolicy4.setHorizontalStretch(0);
    sizePolicy4.setVerticalStretch(0);
    sizePolicy4.setHeightForWidth(frame->sizePolicy().hasHeightForWidth());
//TG    msgframe->setGeometry(QRect(19, 820, 1255, 90));
    //msgframe->setSizePolicy(sizePolicy4);
    msgframe->setGeometry(QRect(10, 880, 1254, 70));
    //msgframe->setMinimumSize(QSize(1164, 90));
    //msgframe->setFrameShape(QFrame::StyledPanel);
    //msgframe->setFrameShadow(QFrame::Raised);

	vboxLayout2 = new QVBoxLayout(msgframe);
	vboxLayout2->setSpacing(0);
	vboxLayout2->setMargin(0);


/*
	QUiLoader m_loader2;
	QFile *file2 = new QFile("/usr/local/opi/ui/ECH_message.ui");
	file2->open(QFile::ReadOnly);
	QWidget *m_widget2 = m_loader2.load(file2);
	file2->close();
	vboxLayout2->addWidget(m_widget2);
*/

	QHBoxLayout *vhLayout = new QHBoxLayout();
	vhLayout->setSpacing(0);
	vhLayout->setMargin(0);

	CADisplayer *ioc1_interlock = new CADisplayer();
	ioc1_interlock->setMinimumSize(QSize(160,20));
	ioc1_interlock->setMaximumSize(QSize(160,20));
	ioc1_interlock->setPvname("ECH_IOC1_INTERLOCK");
	ioc1_interlock->setObjectName("CADisplayer_ioc1_interlock");
	ioc1_interlock->setVisible(false);
	vhLayout->addWidget(ioc1_interlock);

	CADisplayer *ioc2_interlock = new CADisplayer();
	ioc2_interlock->setMinimumSize(QSize(160,20));
	ioc2_interlock->setMaximumSize(QSize(160,20));
	ioc2_interlock->setPvname("ECH_IOC2_INTERLOCK");
	ioc2_interlock->setObjectName("CADisplayer_ioc2_interlock");
	ioc2_interlock->setVisible(false);
	vhLayout->addWidget(ioc2_interlock);
	vboxLayout2->addLayout(vhLayout);

	textEdit = new QTextEdit(this);
	textEdit->setObjectName(QString::fromUtf8("textEdit"));
	//textEdit->setGeometry(QRect(0, 0, 1000, 50)); 
	//textEdit->setGeometry(QRect(16, 900, 1000, 70)); 
	textEdit->setFontPointSize(12);
	textEdit->setAutoFormatting(QTextEdit::AutoAll);
	textEdit->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

	vboxLayout2->addWidget(textEdit);

	//AttachChannelAccess *pattach_msg = new AttachChannelAccess(msgframe);
	setCentralWidget(centralwidget);

	QObject::connect(ioc1_interlock, SIGNAL(valueChanged(QString)), this,  SLOT(changeText(QString))); 

	QObject::connect(tabWidget, SIGNAL(currentChanged(int)), SLOT(setDefaultIndex(int))); 


	// Set Object Text.
	setWindowTitle(QApplication::translate("MainWindow", "ECH (KSTAR 84GHz ECH System)", 0, QApplication::UnicodeUTF8));
	setWindowIcon(QIcon(QString::fromUtf8("/usr/local/opi/images/ECH.xpm")));
#if 0
    action_Print->setText(QApplication::translate("MainWindow", "&Print", 0, QApplication::UnicodeUTF8));
#endif
    action_Exit->setText(QApplication::translate("MainWindow", "e&Xit", 0, QApplication::UnicodeUTF8));
    action_Multiplot->setText(QApplication::translate("MainWindow", "&Multiplot", 0, QApplication::UnicodeUTF8));
    action_Archivesheet->setText(QApplication::translate("MainWindow", "&Archivesheet", 0, QApplication::UnicodeUTF8));
    action_Archiverviewer->setText(QApplication::translate("MainWindow", "a&Rchiveviewer", 0, QApplication::UnicodeUTF8));
    action_SignalDB->setText(QApplication::translate("MainWindow", "&SignalDB", 0, QApplication::UnicodeUTF8));
    action_PVListV->setText(QApplication::translate("MainWindow", "&PVListviewer", 0, QApplication::UnicodeUTF8));
    action_Manual->setText(QApplication::translate("MainWindow", "ma&Nual", 0, QApplication::UnicodeUTF8));
    action_AboutECH->setText(QApplication::translate("MainWindow", "About &ECH", 0, QApplication::UnicodeUTF8));
    tabWidget->setTabText(tabWidget->indexOf(tab_0), QApplication::translate("MainWindow", "ECH main panels", 0, QApplication::UnicodeUTF8));
//    tabWidget->setTabText(tabWidget->indexOf(tab_1), QApplication::translate("MainWindow", "ECH sub panels", 0, QApplication::UnicodeUTF8));
    menu_File->setTitle(QApplication::translate("MainWindow", "&File", 0, QApplication::UnicodeUTF8));
    menu_Util->setTitle(QApplication::translate("MainWindow", "&Util", 0, QApplication::UnicodeUTF8));
    //menu_View->setTitle(QApplication::translate("MainWindow", "&View", 0, QApplication::UnicodeUTF8));
    menu_Help->setTitle(QApplication::translate("MainWindow", "&Help", 0, QApplication::UnicodeUTF8));

} // setupUi
Beispiel #17
0
int main(int argc, char *argv[])
{

    QDir dir;
    QString path=dir.absolutePath();

    QDate data = QDate::currentDate();
    int DaysInMonths = data.daysInMonth();
    int ActualDay = data.day();

    int currentExitCode = 0;

    do
    {
            QApplication a(argc, argv);
            a.setStyle("fusion");

            QFont font("Calibri Light", 12, QFont::Light ,false);
            QFont font_main("Calibri Light", 10, QFont::Light ,false);
            QFont splash_font("Calibri Light", 24, QFont::Bold);

            LoginDialog *logindialog = new LoginDialog;
            MainWindow w;

            logindialog->setWindowFlags(((logindialog->windowFlags() | Qt::CustomizeWindowHint) & Qt::WindowCloseButtonHint & ~Qt::WindowContextHelpButtonHint) );

            /* Ekran startowy*/
            if(currentExitCode != MainWindow::EXIT_CODE_REBOOT)
            {
                QSplashScreen * splash = new QSplashScreen;
                splash->setPixmap(QPixmap(path+"/obrazy/splash.png"));
                splash->setFont(splash_font);
                splash->show();
                splash->showMessage(QObject::tr("Uruchamianie programu "),
                                Qt::AlignLeft | Qt::AlignTop, Qt::black);  //This line represents the alignment of text, color and position

                qApp->processEvents();
                QTimer::singleShot(2000,splash,SLOT(close()));
                QString Splash_string = "Uruchamianie programu";
                QString Splash_string_add = "Uruchamianie programu";

                for(int i=0;i<12;i++)
                {
                    QThread::msleep(150);
                    Splash_string_add = Splash_string_add + ".";

                    if(i==3 || i==7 || i==11) Splash_string_add = Splash_string;

                    splash->showMessage(Splash_string_add,
                                    Qt::AlignLeft | Qt::AlignTop, Qt::black);  //This line represents the alignment of text, color and position
                }
            }



            /* signal-slot - connect login and password from logindialog with MainWindow */
            QObject::connect(logindialog, SIGNAL(sendAccess(QString,QString)),
                             &w, SLOT(receiveAccess(QString,QString)));



            logindialog->setWindowIcon(QIcon(path+"/obrazy/log_icon.png"));
            logindialog->setWindowTitle("SERWIS - Logowanie");
            logindialog->setFont(font);
            if (logindialog->exec() != QDialog::Accepted) {
                a.quit();
                return 0;
            } else {
                delete logindialog;
                w.showMaximized();
                w.setWindowTitle("SERWIS");
                w.setWindowIcon(QIcon(path+"/obrazy/services_icon.png"));
                w.setFont(font_main);
                w.show();

                QFile file;
                QString file_name="AUTO_BACKUP.txt";
                file.setFileName(file_name);
                if(!file.exists() && (DaysInMonths-ActualDay)==1){

                    QMessageBox::warning(&w,"Informacja","****************** Do końca miesiąca został 1 dzień! *******************\n"
                                                         "Wykonany zostanie automatyczny zapis kopii zapasowej bazy danych. \n"
                                                         "*************************************************************************");
                    QTimer::singleShot(500,&w,SLOT(create_backup()));

                    qDebug() << "Doesn't exists: "<<file_name;
                    file.open(QIODevice::ReadWrite | QIODevice::Text);
                    QTextStream stream(&file);
                    file.close();

                }else if (file.exists() && (DaysInMonths-ActualDay)!=1){
                    qDebug() << file_name <<" removing ...";
                    file.remove();
                }else if (file.exists() && (DaysInMonths-ActualDay)==1)
                {
                    qDebug() << file_name <<" already created ...";
                }

            }
             currentExitCode = a.exec();
     } while( currentExitCode == MainWindow::EXIT_CODE_REBOOT );

    return currentExitCode;
}
Beispiel #18
0
void ExtEdit::createAppList()
{	
#ifdef Q_WS_X11
	QByteArray globalMimeTypesList = _globalAppListPath_c + "mimeinfo.cache";
	QByteArray localMimeTypesPath = qgetenv("XDG_DATA_HOME");
	
	if (localMimeTypesPath.isEmpty() == true)
	{
		localMimeTypesPath = qgetenv("HOME") + "/.local/share";
	}
	localMimeTypesPath += "/applications/";
	QByteArray localMimeTypesList = localMimeTypesPath + "mimeinfo.cache";
	
	QVector<QByteArray> pathList;
	pathList << _globalAppListPath_c << localMimeTypesPath;
	
	QVector<QByteArray> fileList;
	fileList << globalMimeTypesList << localMimeTypesList;
	
	QFile file;
	
	for (int f = 0; f < fileList.count(); ++f)
	{		
		file.setFileName(fileList.value(f));
		if (file.open(QIODevice::ReadOnly) == true)
		{
			QString inLine;
			QString mimetype;
			QStringList desktopFiles;
			
			QTextStream in(&file);
			while(in.atEnd() == false)
			{
				inLine = in.readLine();
				if (inLine.split("=").count() > 1)
				{
					mimetype = inLine.split("=").at(0);
					if (mimetype == "image/png")
					{
						desktopFiles = inLine.split("=").at(1).split(";");
						if (desktopFiles.count() != 0)
						{
							for (int i = 0; i < desktopFiles.count(); ++i)
							{
								if (desktopFiles.at(i).isEmpty() == false)
								{
									_appList.append(readDesktopFile(desktopFiles.at(i), pathList.at(f)));
								}
							}
						}
					}
				}
			}
		}
		file.close();
	}
#endif
#ifdef Q_WS_WIN
	// TODO make read windows registry for get apps for image editing
	
	// WARNING this in dirty hack - hardcoded mspaint app
	ExtApp_t app;
	app.exec = "mspaint";
	app.name = "Paint";
	
	_appList.append(app);
#endif
}
Beispiel #19
0
/*!
 * \brief SimMessage::startSimulator simulates the document in view.
 */
void SimMessage::startSimulator()
{
  // Using the Doc pointer here is risky as the user may have closed
  // the schematic, but converting the SPICE netlists is (hopefully)
  // faster than the user (I have no other idea).

  QString SimTime;
  QStringList Arguments;
  QString SimPath = QDir::convertSeparators (QucsSettings.QucsHomeDir.absolutePath());
#ifdef __MINGW32__
  QString QucsDigiLib = "qucsdigilib.bat";
  QString QucsDigi = "qucsdigi.bat";
  QString QucsVeri = "qucsveri.bat";
#else
  QString QucsDigiLib = "qucsdigilib";
  QString QucsDigi = "qucsdigi";
  QString QucsVeri = "qucsveri";
#endif
  SimOpt = NULL;
  bool isVerilog = false;
  QProcessEnvironment env = QProcessEnvironment::systemEnvironment();

  // Simulate text window.
  if(DocWidget->inherits("QTextEdit")) {

    TextDoc * Doc = (TextDoc*)DocWidget;

    // Take VHDL file in memory as it could contain unsaved changes.
    Stream << Doc->toPlainText();
    NetlistFile.close();
    ProgText->insertPlainText(tr("done.\n"));  // of "creating netlist...

    // Simulation.
    if (Doc->simulation) {
      SimTime = Doc->SimTime;
      QString libs = Doc->Libraries.toLower();
      /// \todo \bug error: unrecognized command line option '-Wl'
#ifdef __MINGW32__
      if(libs.isEmpty()) {
        libs = "";
      }
      else {
        libs.replace(" ",",-l");
        libs = "-Wl,-l" + libs;
      }
#else
      if(libs.isEmpty()) {
        libs = "-c";
      }
      else {
        libs.replace(" ",",-l");
        libs = "-c,-l" + libs;
      }
#endif
      Program = pathName(QucsSettings.BinDir + QucsDigi);
      Arguments  << QucsSettings.QucsHomeDir.filePath("netlist.txt")
                 << DataSet << SimTime << pathName(SimPath)
                 << pathName(QucsSettings.BinDir) << libs;
    }
    // Module.
    else {
      QString text = Doc->toPlainText();
      VHDL_File_Info VInfo (text);
      QString entity = VInfo.EntityName.toLower();
      QString lib = Doc->Library.toLower();
      if (lib.isEmpty()) lib = "work";
      QString dir = QDir::convertSeparators (QucsSettings.QucsHomeDir.path());
      QDir vhdlDir(dir);
      if(!vhdlDir.exists("vhdl"))
	if(!vhdlDir.mkdir("vhdl")) {
	  ErrText->appendPlainText(tr("ERROR: Cannot create VHDL directory \"%1\"!")
			  .arg(vhdlDir.path()+"/vhdl"));
	  return;
	}
      vhdlDir.setPath(vhdlDir.path()+"/vhdl");
      if(!vhdlDir.exists(lib))
	if(!vhdlDir.mkdir(lib)) {
	  ErrText->appendPlainText(tr("ERROR: Cannot create VHDL directory \"%1\"!")
			  .arg(vhdlDir.path()+"/"+lib));
	  return;
	}
      vhdlDir.setPath(vhdlDir.path()+"/"+lib);
      QFile destFile;
      destFile.setFileName(vhdlDir.filePath(entity+".vhdl"));
      if(!destFile.open(QIODevice::WriteOnly)) {
	ErrText->appendPlainText(tr("ERROR: Cannot create \"%1\"!")
			.arg(destFile.fileName()));
	return;
      }
      destFile.write(text.toAscii(), text.length());
      destFile.close();
      Program = pathName(QucsSettings.BinDir + QucsDigiLib);
      Arguments << QucsSettings.QucsHomeDir.filePath("netlist.txt")
                << pathName(SimPath)
                << entity
                << lib;
    }
  }
  // Simulate schematic window.
  else {
    // output NodeSets, SPICE simulations etc.
    for(QStringList::Iterator it = Collect.begin();
	it != Collect.end(); ++it) {
      // don't put library includes into netlist...
      if ((*it).right(4) != ".lst" &&
	  (*it).right(5) != ".vhdl" &&
	  (*it).right(4) != ".vhd" &&
	  (*it).right(2) != ".v") {
	Stream << *it << '\n';
      }
    }
    Stream << '\n';

    isVerilog = ((Schematic*)DocWidget)->isVerilog;
    SimTime = ((Schematic*)DocWidget)->createNetlist(Stream, SimPorts);
    if(SimTime.length()>0&&SimTime.at(0) == '\xA7') {
      NetlistFile.close();
      ErrText->insertPlainText(SimTime.mid(1));
      FinishSimulation(-1);
      return;
    }
    if (isVerilog) {
      Stream << "\n"
	     << "  initial begin\n"
	     << "    $dumpfile(\"digi.vcd\");\n"
	     << "    $dumpvars();\n"
	     << "    #" << SimTime << " $finish;\n"
	     << "  end\n\n"
	     << "endmodule // TestBench\n";
    }
    NetlistFile.close();
    ProgText->insertPlainText(tr("done.\n"));  // of "creating netlist...

    if(SimPorts < 0) {

      // append command arguments
      // append netlist with same arguments
      if (! Module::vaComponents.isEmpty()) {

          /*! Only pass modules to Qucsator that are indeed used on
           * the schematic,it might be the case that the user loaded the icons,
           * but did not compiled the module. Qucsator will not find the library.
           *
           * Check if used symbols have corresponing lib before running
           * Qucsator? Need to search on the netlis.txt? Is there other data
           * structure containig the netlist?
           *
          */
          QStringList usedComponents;

          if (!NetlistFile.open(QIODevice::ReadOnly))
             QMessageBox::critical(this, tr("Error"), tr("Cannot read netlist!"));
          else {
             QString net = QString(NetlistFile.readAll());

             QMapIterator<QString, QString> i(Module::vaComponents);
             while (i.hasNext()) {
                 i.next();
                 if (net.contains(i.key()))
                     usedComponents << i.key();
             }
             NetlistFile.close();
          }

          if (! usedComponents.isEmpty()) {


            /// \todo remvoe the command line arguments? use only netlist annotation?
            //Arguments << "-p" << QucsSettings.QucsWorkDir.absolutePath()
            //          << "-m" << usedComponents;
            //qDebug() << "Command :" << Program << Arguments.join(" ");

            /// Anotate netlist with Verilog-A dynamic path and module names
            ///
            if (!NetlistFile.open(QFile::Append | QFile::Text))
               QMessageBox::critical(this, tr("Error"), tr("Cannot read netlist!"));
            else {
               QTextStream out(&NetlistFile);
               out << "\n";
               out << "# --path=" << QucsSettings.QucsWorkDir.absolutePath() << "\n";
               out << "# --module=" << usedComponents.join(" ") << "\n";

               NetlistFile.close();
            }
          }
      } // vaComponents not empty

      if((SimOpt = findOptimization((Schematic*)DocWidget))) {
	    ((Optimize_Sim*)SimOpt)->createASCOnetlist();

        Program = QucsSettings.AscoBinDir.canonicalPath();
        Program = QDir::toNativeSeparators(Program+"/"+"asco"+QString(executableSuffix));
        Arguments << "-qucs" << QucsSettings.QucsHomeDir.filePath("asco_netlist.txt")
                  << "-o" << "asco_out";
      }
      else {
        Program = QucsSettings.Qucsator;
        Arguments << "-b" << "-g" << "-i"
                  << QucsSettings.QucsHomeDir.filePath("netlist.txt")
                  << "-o" << DataSet;
      }
    }
    else {
      if (isVerilog) {
          Program = QDir::toNativeSeparators(QucsSettings.BinDir + QucsVeri);
          Arguments << QDir::toNativeSeparators(QucsSettings.QucsHomeDir.filePath("netlist.txt"))
                    << DataSet
                    << SimTime
                    << QDir::toNativeSeparators(SimPath)
                    << QDir::toNativeSeparators(QucsSettings.BinDir)
                    << "-c";
      } else {
/// \todo \bug error: unrecognized command line option '-Wl'
#ifdef __MINGW32__
    Program = QDir::toNativeSeparators(pathName(QucsSettings.BinDir + QucsDigi));
    Arguments << QDir::toNativeSeparators(QucsSettings.QucsHomeDir.filePath("netlist.txt"))
              << DataSet
              << SimTime
              << QDir::toNativeSeparators(SimPath)
              << QDir::toNativeSeparators(QucsSettings.BinDir) << "-Wall" << "-c";
#else
    Program = QDir::toNativeSeparators(pathName(QucsSettings.BinDir + QucsDigi));
    Arguments << QucsSettings.QucsHomeDir.filePath("netlist.txt")
              << DataSet << SimTime << pathName(SimPath)
		      << pathName(QucsSettings.BinDir) << "-Wall" << "-c";

#endif
      }
    }
  }

  disconnect(&SimProcess, 0, 0, 0);
  connect(&SimProcess, SIGNAL(readyReadStandardError()), SLOT(slotDisplayErr()));
  connect(&SimProcess, SIGNAL(readyReadStandardOutput()), SLOT(slotDisplayMsg()));
  connect(&SimProcess, SIGNAL(finished(int, QProcess::ExitStatus)),
                       SLOT(slotSimEnded(int, QProcess::ExitStatus)));
  connect(&SimProcess, SIGNAL(stateChanged(QProcess::ProcessState)),
                       SLOT(slotStateChanged(QProcess::ProcessState)));

#ifdef SPEEDUP_PROGRESSBAR
  waitForUpdate = false;
#endif
  wasLF = false;

  ProgressText = "";

#ifdef __MINGW32__
  QString sep(";"); // path separator
#else
  QString sep(":");
#endif

  // append process PATH
  // insert Qucs bin dir, so ASCO can find qucsator
  env.insert("PATH", env.value("PATH") + sep + QucsSettings.BinDir );
  SimProcess.setProcessEnvironment(env);

  qDebug() << "Command :" << Program << Arguments.join(" ");
  SimProcess.start(Program, Arguments); // launch the program

}
Beispiel #20
0
bool plotsDialog::loadXml(bool init)
{
    tabs->clear();
    QFile file;
#ifdef Q_OS_WIN32
    if(init)
    {
        QFile ofile(globalpara.caseName);
        file.setFileName("plotTemp.xml");
        if(file.exists())
            file.remove();
        if(!ofile.copy("plotTemp.xml"))
        {
            globalpara.reportError("Fail to generate temporary file for plots.",this);
            return false;
        }
        else file.setFileName("plotTemp.xml");
    }
    else file.setFileName("plotTemp.xml");
#endif
#ifdef Q_OS_MAC
    QDir dir = qApp->applicationDirPath();
    /*dir.cdUp();*/
    /*dir.cdUp();*/
    /*dir.cdUp();*/
    QString bundleDir(dir.absolutePath());
    if(init)
    {
        QFile ofile(globalpara.caseName);
        file.setFileName(bundleDir+"/plotTemp.xml");
        if(file.exists())
            file.remove();
        if(!ofile.copy(bundleDir+"/plotTemp.xml"))
        {
            globalpara.reportError("Fail to generate temporary file for plots.",this);
            return false;
        }
        else file.setFileName(bundleDir+"/plotTemp.xml");
    }
    else file.setFileName(bundleDir+"/plotTemp.xml");
#endif
    QDomDocument doc;
    QDomElement plotData, currentPlot;
    int plotCount=0;
    Plot*newPlot;

    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        globalpara.reportError("Fail to open the xml file for plots!",this);
        return false;
    }
    else
    {
        if(!doc.setContent(&file))
        {
            globalpara.reportError("Fail to set DomDoc to file content when loading xml file for plots!",this);
            file.close();
            return false;
        }
        else
        {
            if(doc.elementsByTagName("plotData").count()==0)
            {
                globalpara.reportError("Error! There is no <plotData> branch in the case xml file!",this);
                file.close();
                return false;
            }
            else
                plotData = doc.elementsByTagName("plotData").at(0).toElement();

            plotCount = plotData.childNodes().count();
            for(int i = 0; i < plotCount; i++)
            {
                currentPlot = plotData.childNodes().at(i).toElement();
                if(currentPlot.attribute("plotType")=="parametric")
                {
                    QDomElement currentRun,runInput,runOutput;
                    double currentInput;
                    int axis_info[8];
                    QStringList currentOutput, xValues, axis_name, info;
                    QMultiMap<double,double> allData;
                    axis_name.append(currentPlot.attribute("xAxisName"));
                    axis_name= axis_name + currentPlot.attribute("yAxisName").split(",");
                    info = currentPlot.attribute("scaleInfo").split(",");
                    for(int j = 0; j < 8; j++)
                        axis_info[j] = info.at(j).toInt();
                    int nRuns = currentPlot.elementsByTagName("Run").count(), nOutputs = currentPlot.attribute("outputs").toInt();
                    for(int j = 0; j < nRuns; j++)
                    {
                        currentOutput.clear();
                        currentRun = currentPlot.elementsByTagName("Run").at(j).toElement();
                        runInput = currentRun.elementsByTagName("Input").at(0).toElement();
                        currentInput = runInput.elementsByTagName("value").at(0).toElement().text().toDouble();
                        xValues.append(QString::number(currentInput));
                        for(int p = 0; p < nOutputs; p++)
                        {
                            runOutput = currentRun.elementsByTagName("Output").at(p).toElement();
                            currentOutput.append(runOutput.elementsByTagName("value").at(0).toElement().text());
                            allData.insert(currentInput,currentOutput.at(p).toDouble());
                        }
                    }


                    newPlot = new Plot(allData,xValues,nOutputs,axis_info,axis_name);


                }
                else if(currentPlot.attribute("plotType")=="property")
                {
                    QString fluid = currentPlot.attribute("fluid"),
                            subType = currentPlot.attribute("subType"),
                            unit = currentPlot.attribute("unitSystem");

                    newPlot = new Plot(fluid,subType,unit);
                    QDomElement currentCurve, currentPoint;

                    newPlot->curvePoints.clear();
                    for(int i = 0; i < currentPlot.childNodes().count(); i++)
                    {
                        if(currentPlot.childNodes().at(i).toElement().attribute("type")=="custom")
                        {
                            addvalue*value;
                            newPlot->addvaluelist.clear();
                            currentCurve = currentPlot.childNodes().at(i).toElement();
                            QString title = currentCurve.tagName();
                            for(int j = 0; j < currentCurve.childNodes().count(); j++)
                            {
                                if(currentCurve.childNodes().at(j).toElement().attribute("order")==QString::number(j))
                                {
                                    value = new addvalue;
                                    currentPoint = currentCurve.childNodes().at(j).toElement();
                                    value->index = currentPoint.attribute("index").toInt();
                                    value->add_temperature = currentPoint.attribute("t").toDouble();
                                    value->add_pressure = currentPoint.attribute("p").toDouble();
                                    value->add_concentration = currentPoint.attribute("c").toDouble();
                                    value->add_enthalpy = currentPoint.attribute("h").toDouble();
//                                    qDebug()<<"adding a new point"<<currentPoint.attribute("index")<<"t"<<currentPoint.attribute("t")<<"p"<<currentPoint.attribute("p")<<"c"<<currentPoint.attribute("c");
                                    newPlot->addvaluelist<<value;
                                }
                            }

                            if(subType == "Duhring")
                                newPlot->setupNewPropertyCurve(title,true);
                            else if(subType == "Clapeyron")
                                newPlot->setupNewPropertyCurve(title,false);
                        }
                    }


                }
                newPlot->setTitle(currentPlot.tagName());

                //load the plot settings
                QDomElement general, legend, grid, curve;

                //general
                if(currentPlot.elementsByTagName("general").count()>0)
                {
                    general = currentPlot.elementsByTagName("general").at(0).toElement();
                    QString bgColor, lMargin, rMargin, tMargin, bMargin, plotTitle, xTitle, yTitle;
                    bgColor = general.attribute("bgColor");
                    newPlot->setCanvasBackground(QColor(bgColor));
                    lMargin = general.attribute("lMargin");
                    rMargin = general.attribute("rMargin");
                    tMargin = general.attribute("tMargin");
                    bMargin = general.attribute("bMargin");
                    newPlot->setContentsMargins(lMargin.toInt(),tMargin.toInt(),rMargin.toInt(),bMargin.toInt());
                    plotTitle = general.attribute("plotTitle");
                    newPlot->setTitle(plotTitle);
                    xTitle = general.attribute("xTitle");
                    yTitle = general.attribute("yTitle");
                    newPlot->setAxisTitle(QwtPlot::xBottom,xTitle);
                    newPlot->setAxisTitle(QwtPlot::yLeft,yTitle);

                }

                //legend
                if(currentPlot.elementsByTagName("legend").count()>0)
                {
                    legend = currentPlot.elementsByTagName("legend").at(0).toElement();
                    QString plotLegend, extInt, extPos, nCol, legendSize;
                    plotLegend = legend.attribute("plotLegend");
                    if(plotLegend == "on")
                    {
                        QwtLegend* externalLegend=NULL;
                        LegendItem* internalLegend = new LegendItem();
                        newPlot->externalLegend = externalLegend;
                        newPlot->internalLegend = internalLegend;
                        internalLegend->attach(newPlot);
                        internalLegend->setBorderRadius( 4 );
                        internalLegend->setMargin( 0 );
                        internalLegend->setSpacing( 4 );
                        internalLegend->setItemMargin( 2 );
                        internalLegend->setMaxColumns(4);
                        internalLegend->setAlignment(Qt::AlignBottom|Qt::AlignRight);
                        extInt = legend.attribute("extInt");
                        if(extInt == "ext")
                        {
                            internalLegend->setVisible(false);
                            externalLegend = new QwtLegend();
                            extPos = legend.attribute("extPos");//0=L, 1=R, 2=B, 3=T
                            newPlot->insertLegend(externalLegend,QwtPlot::LegendPosition(extPos.toInt()));
                        }
                        else if(extInt == "int")
                        {
                            internalLegend->setVisible(true);
                            nCol = legend.attribute("nCol");
                            legendSize = legend.attribute("legendSize");

                            // other setting
                            newPlot->internalLegend->setMaxColumns(nCol.toInt());
                            QFont font = newPlot->internalLegend->font();
                            font.setPointSize( legendSize.toInt());
                            newPlot->internalLegend->setFont( font );
                        }
                    }
                }

                //grid
                if(currentPlot.elementsByTagName("grid").count()>0)
                {
                    grid = currentPlot.elementsByTagName("grid").at(0).toElement();
                    QString xMaj, yMaj, xMin, yMin, majColor, minColor, majSize, minSize, majStyle, minStyle;
                    xMaj = grid.attribute("xMaj");
                    yMaj = grid.attribute("yMaj");
                    xMin = grid.attribute("xMin");
                    yMin = grid.attribute("yMin");
                    majColor = grid.attribute("majColor");
                    minColor = grid.attribute("minColor");
                    majSize = grid.attribute("majSize");
                    minSize = grid.attribute("minSize");
                    majStyle = grid.attribute("majStyle");
                    minStyle = grid.attribute("minStyle");
                    newPlot->grid->enableX(xMaj=="on");
                    newPlot->grid->enableY(yMaj == "on");
                    newPlot->grid->enableXMin(xMin=="on");
                    newPlot->grid->enableYMin(yMin=="on");
                    if(newPlot->grid->xEnabled()||newPlot->grid->yEnabled())
                        newPlot->grid->setMajorPen(QColor(majColor),majSize.toInt(),Qt::PenStyle(majStyle.toInt()));
                    if(newPlot->grid->xMinEnabled()||newPlot->grid->yMinEnabled())
                        newPlot->grid->setMinorPen(QColor(minColor),minSize.toInt(),Qt::PenStyle(minStyle.toInt()));
                }

                //curve
                if(currentPlot.elementsByTagName("curve").count()>0)
                {
                    curve = currentPlot.elementsByTagName("curve").at(0).toElement();
                    if(curve.childNodes().count()==newPlot->curvelist.count())
                    {
                        QDomElement currentCurve;
                        QwtPlotCurve *thisCurve;
                        QString lineColor, lineSize, lineType, isVisible;
                        for(int i = 0; i < newPlot->curvelist.count(); i++)
                        {
                            currentCurve = curve.elementsByTagName(newPlot->curvelist[i]->title().text().replace(" ","")).at(0).toElement();
                            thisCurve = newPlot->curvelist[i];
                            lineColor = currentCurve.attribute("lineColor");
                            lineSize = currentCurve.attribute("lineSize");
                            lineType = currentCurve.attribute("lineType");
                            isVisible = currentCurve.attribute("isVisible");
                            thisCurve->setPen(QColor(lineColor),lineSize.toInt(),Qt::PenStyle(lineType.toInt()));
                            if(isVisible=="true")
                                thisCurve->setVisible(true);
                            else if(isVisible=="false")
                                thisCurve->setVisible(false);
                        }
                    }
                }


                tabs->insertTab(-1,newPlot,currentPlot.tagName());
                newPlot->replot();
            }
            file.close();
            return true;
        }
    }
}
Beispiel #21
0
void Task::run() {
    QTcpSocket socket;
    QString answerID,type,lang;
    socket.setSocketDescriptor(this->socketDescriptor);
    socket.waitForReadyRead();
    data=socket.readAll();
    dateTime = QDateTime::currentDateTime();
    QStringList params;
    QFile file;
    token=QUuid::createUuid().toString();
    token=token.left(token.size()-1);
    token=token.right(token.size()-1);
    conName=cdb.connectionName()+QString::number(id);
    {
        QSqlDatabase db=QSqlDatabase(QSqlDatabase::cloneDatabase(cdb,conName));
        db.open();
        QSqlQuery query(db);

        sc = engine.evaluate("(" + QString(data) + ")");
        QScriptValueIterator it(sc);
        while (it.hasNext()) {
            it.next();
            if (it.name()=="program")
            {
                program_id=it.value().toString();
                token=token+"-"+program_id;
                params<<program_id;
                if (!params.at(0).isNull()||!params.at(0).isEmpty())
                {
                    query.exec("INSERT INTO math.answer (an_user_id, an_token, an_complete,  an_start_date, an_cp_id) VALUES (0, '"+token+"', 0,  '"+dateTime.toString("yyyy-MM-dd hh:mm:ss")+"', '"+program_id+"');");
                    query.exec("SELECT @an_id:=LAST_INSERT_ID();");
                    query.next();
                    answerID = query.value(0).toString();
                    params<<answerID;
                }
            }
            if (it.name()=="exec")
            {
                type=it.value().toString();
            }
            if (it.name()=="lang")
            {
                lang=it.value().toString();
                params<<lang;
            }
            if (it.value().isObject())
            {
                if (type=="execute")
                {
                    QScriptValueIterator sit(it.value());
                    while (sit.hasNext()) {
                        sit.next();
                        if (sit.value().isObject())//--- jeigu tai failas
                        {
                            QScriptValueIterator sits(sit.value());
                            while (sits.hasNext()) {
                                sits.next();
                                if (sits.value().toString()=="file")
                                {
                                    sits.next();

                                    query.exec("SELECT @pp_id:=pp_id FROM math.program_param_list,math.program_param WHERE ppl_pp_id=pp_id and ppl_cp_id="+program_id+" and pp_name='"+sits.name()+"'");
                                    cout << program_id.toStdString() << " program id \n";
                                    query.prepare("INSERT INTO math.answer_param_value (pv_value, pv_pp_id) VALUES (:val, @pp_id);");
                                    query.bindValue(":val",sits.value().toString());
                                    query.exec();
                                    query.exec("SELECT @pv_id:=LAST_INSERT_ID();");
                                    query.exec("INSERT INTO math.answer_param_list (anpl_an_id, anpl_pv_id) VALUES (@an_id, @pv_id)");
                                    query.exec("SELECT BD_DATA FROM math.big_data where BD_ID="+sits.value().toString());
                                    query.next();
                                    file.setFileName(this->binaryPath+"/binaries/"+program_id+"/"+sits.value().toString());
                                    params<<this->binaryPath+"/binaries/"+program_id+"/"+sits.value().toString();
                                    if (file.open(QIODevice::WriteOnly | QIODevice::Text))
                                    {
                                        QTextStream out(&file);
                                        out << query.value(0).toByteArray();
                                    }
                                    file.close();
                                }
                            }
                        }
                        else {
                            params<<sit.value().toString();
                            query.exec("SELECT @pp_id:=pp_id FROM math.program_param_list,math.program_param WHERE ppl_pp_id=pp_id and ppl_cp_id="+program_id+" and pp_name='"+sit.name()+"'");
                            query.prepare("INSERT INTO math.answer_param_value (pv_value, pv_pp_id) VALUES (:val, @pp_id);");
                            query.bindValue(":val",sit.value().toString());
                            query.exec();
                            query.exec("SELECT @pv_id:=LAST_INSERT_ID();");
                            query.exec("INSERT INTO math.answer_param_list (anpl_an_id, anpl_pv_id) VALUES (@an_id, @pv_id)");
                        }
                    }
                }
            }
        }
    }
    QSqlDatabase::removeDatabase(conName);
    if (type=="execute")
    {
        if (params.at(0).isNull()||params.at(0).isEmpty())
        {
            socket.write("Nurodykite programa");
            socket.waitForBytesWritten();
        }
        else  emit this->requestExecute(params);
    }
    if (type=="compile")
    {
        if (params.at(0).isNull()||params.at(0).isEmpty())
        {
            socket.write("Nurodykite programa");
            socket.waitForBytesWritten();
        }
        else  emit this->requestCompile(params);
    }
    // qDebug()<<QString(data);
    socket.write(token.toLatin1());
    socket.flush();
    socket.waitForBytesWritten();
    socket.waitForDisconnected();
    socket.close();

}
Beispiel #22
0
QString UBImportDocument::expandFileToDir(const QFile& pZipFile, const QString& pDir)
{

    QDir rootDir(pDir);
    QuaZip zip(pZipFile.fileName());

    if(!zip.open(QuaZip::mdUnzip))
    {
        qWarning() << "Import failed. Cause zip.open(): " << zip.getZipError();
        return "";
    }

    zip.setFileNameCodec("UTF-8");
    QuaZipFileInfo info;
    QuaZipFile file(&zip);

    // TODO UB 4.x  implement a mechanism that can replace an existing
    // document based on the UID of the document.
    bool createNewDocument = true;
    QString documentRootFolder;

    // first we search the metadata.rdf to check the document properties
    for(bool more = zip.goToFirstFile(); more; more = zip.goToNextFile())
    {
        if(!zip.getCurrentFileInfo(&info))
        {
            qWarning() << "Import failed. Cause: getCurrentFileInfo(): " << zip.getZipError();
            return "";
        }

        QFileInfo currentFileInfo(pDir + "/" + file.getActualFileName());
    }

    if (createNewDocument)
        documentRootFolder = UBPersistenceManager::persistenceManager()->generateUniqueDocumentPath();


    QFile out;
    char c;
    for(bool more=zip.goToFirstFile(); more; more=zip.goToNextFile())
    {
        if(!zip.getCurrentFileInfo(&info))
        {
            //TOD UB 4.3 O display error to user or use crash reporter
            qWarning() << "Import failed. Cause: getCurrentFileInfo(): " << zip.getZipError();
            return "";
        }

        if(!file.open(QIODevice::ReadOnly))
        {
            qWarning() << "Import failed. Cause: file.open(): " << zip.getZipError();
            return "";
        }

        if(file.getZipError()!= UNZ_OK)
        {
            qWarning() << "Import failed. Cause: file.getFileName(): " << zip.getZipError();
            return "";
        }

        QString newFileName = documentRootFolder + "/" + file.getActualFileName();
        QFileInfo newFileInfo(newFileName);
        rootDir.mkpath(newFileInfo.absolutePath());

        out.setFileName(newFileName);
        out.open(QIODevice::WriteOnly);

        // Slow like hell (on GNU/Linux at least), but it is not my fault.
        // Not ZIP/UNZIP package's fault either.
        // The slowest thing here is out.putChar(c).
        QByteArray outFileContent = file.readAll();
        if (out.write(outFileContent) == -1)
        {
            qWarning() << "Import failed. Cause: Unable to write file";
            out.close();
            return "";
        }

        while(file.getChar(&c))
            out.putChar(c);

        out.close();

        if(file.getZipError()!=UNZ_OK)
        {
            qWarning() << "Import failed. Cause: " << zip.getZipError();
            return "";
        }

        if(!file.atEnd())
        {
            qWarning() << "Import failed. Cause: read all but not EOF";
            return "";
        }

        file.close();

        if(file.getZipError()!=UNZ_OK)
        {
            qWarning() << "Import failed. Cause: file.close(): " <<  file.getZipError();
            return "";
        }

    }

    zip.close();

    if(zip.getZipError()!=UNZ_OK)
    {
      qWarning() << "Import failed. Cause: zip.close(): " << zip.getZipError();
      return "";
    }


    return documentRootFolder;
}
const KstTimezone *KstTimezones::local()
{
    const KstTimezone *local = 0;

    // First try the simplest solution of checking for well-formed TZ setting.
    char *envZone = ::getenv("TZ");
    if (envZone)
    {
        if (envZone[0] == '\0')
        {
            return m_UTC;
        }
        else
        if (envZone[0] == ':')
        {
            envZone++;
        }
        local = zone(envZone);
    }
    if (local)
        return local;

    // Try to match /etc/localtime against the list of zoneinfo files.
    QFile f;
    f.setName("/etc/localtime");
    if (f.open(IO_ReadOnly))
    {
        // Compute the MD5 sum of /etc/localtime.
        KMD5 context("");
        context.reset();
        context.update(f);
        QIODevice::Offset referenceSize = f.size();
        QString referenceMd5Sum = context.hexDigest();
        f.close();
        if (!m_zoneinfoDir.isEmpty())
        {
            // Compare it with each zoneinfo file.
            for (ZoneMap::Iterator it = m_zones->begin(); it != m_zones->end(); ++it)
            {
                KstTimezone *zone = it.data();
                f.setName(m_zoneinfoDir + '/' + zone->name());
                if (f.open(IO_ReadOnly))
                {
                    QIODevice::Offset candidateSize = f.size();
                    QString candidateMd5Sum;
                    if (candidateSize == referenceSize)
                    {
                        // Only do the heavy lifting for file sizes which match.
                        context.reset();
                        context.update(f);
                        candidateMd5Sum = context.hexDigest();
                    }
                    f.close();
                    if (candidateMd5Sum == referenceMd5Sum)
                    {
                        local = zone;
                        break;
                    }
                }
            }
        }
    }
    if (local)
        return local;

    // BSD support.
    QString fileZone;
    f.setName("/etc/timezone");
    if (!f.open(IO_ReadOnly))
    {
        // Solaris support using /etc/default/init.
        f.setName("/etc/default/init");
        if (f.open(IO_ReadOnly))
        {
            QTextStream ts(&f);
            ts.setEncoding(QTextStream::Latin1);

            // Read the last line starting "TZ=".
            while (!ts.atEnd())
            {
                fileZone = ts.readLine();
                if (fileZone.startsWith("TZ="))
                {
                    fileZone = fileZone.mid(3);

                    local = zone(fileZone);
                }
            }
            f.close();
        }
    }
    else
    {
        QTextStream ts(&f);
        ts.setEncoding(QTextStream::Latin1);

        // Read the first line.
        if (!ts.atEnd())
        {
            fileZone = ts.readLine();

            local = zone(fileZone);
        }
        f.close();
    }
    if (local)
        return local;

    // None of the deterministic stuff above has worked: try a heuristic. We
    // try to find a pair of matching timezone abbreviations...that way, we'll
    // likely return a value in the user's own country.
    if (!m_zoneinfoDir.isEmpty())
    {
        tzset();
        AbbreviationsMatch matcher(tzname[0], tzname[1]);
        int bestOffset = INT_MAX;
        for (ZoneMap::Iterator it = m_zones->begin(); it != m_zones->end(); ++it)
        {
            KstTimezone *zone = it.data();
            int candidateOffset = QABS(zone->offset(Qt::LocalTime));
            if (zone->parse(matcher) && matcher.test() && (candidateOffset < bestOffset))
            {
                bestOffset = candidateOffset;
                local = zone;
            }
        }
    }
    if (local)
        return local;
    return m_UTC;
}
Document::Document (const QString &fileName) :
  m_name (fileName),
  m_documentAxesPointsRequired (DOCUMENT_AXES_POINTS_REQUIRED_3)
{
  LOG4CPP_INFO_S ((*mainCat)) << "Document::Document"
                              << " fileName=" << fileName.toLatin1().data();

  m_successfulRead = true;

  // Grab first few bytes to determine the version number
  QFile *file = new QFile (fileName);
  if (file->open(QIODevice::ReadOnly)) {

    QByteArray bytesStart = file->read (FOUR_BYTES);
    file->close ();

    if (bytesIndicatePreVersion6 (bytesStart)) {

      QFile *file = new QFile (fileName);
      if (file->open (QIODevice::ReadOnly)) {
        QDataStream str (file);

        m_coordSystemContext.addCoordSystems(NOMINAL_COORD_SYSTEM_COUNT);
        loadPreVersion6 (str);

      } else {

        m_successfulRead = false;
        m_reasonForUnsuccessfulRead = QObject::tr ("Operating system says file is not readable");

      }
    } else {

      QFile *file = new QFile (fileName);
      if (file->open (QIODevice::ReadOnly | QIODevice::Text)) {

        int version = versionFromFile (file);
        switch (version)
        {
          case VERSION_6:
            loadVersion6 (file);
            break;

          case VERSION_7:
          case VERSION_8:
          case VERSION_9:
          case VERSION_10:
          case VERSION_11:
            loadVersions7AndUp (file);
            break;

          default:
            m_successfulRead = false;
            m_reasonForUnsuccessfulRead = QString ("Engauge %1 %2 %3 %4 Engauge")
                                          .arg (VERSION_NUMBER)
                                          .arg (QObject::tr ("cannot read newer files from version"))
                                          .arg (version)
                                          .arg (QObject::tr ("of"));
            break;
        }

        // Close and deactivate
        file->close ();
        delete file;
        file = nullptr;

      } else {

        m_successfulRead = false;
        m_reasonForUnsuccessfulRead = QObject::tr ("Operating system says file is not readable");
      }
    }
  } else {
    file->close ();
    m_successfulRead = false;
    m_reasonForUnsuccessfulRead = QString ("%1 '%2' %3")
                                  .arg (QObject::tr ("File"))
                                  .arg (fileName)
                                  .arg (QObject::tr ("was not found"));
  }
}
Beispiel #25
0
void MainWindow::loadfile(QString filename)
{
    QSettings settings;

    if(filename.isEmpty())
        filename = QFileDialog::getOpenFileName(this, tr("Open..."), settings.value("LoadFile/lastDirectory", QDir::homePath()).toString(), tr("FUSE files (*.fuse *.xml)"));

    if(filename.isEmpty())
        return;

    settings.setValue("LoadFile/lastDirectory", QFileInfo(filename).absolutePath());
    QFile *file = new QFile(filename, this);

    if(file->exists())
    {
        if (!file->open(QFile::ReadOnly | QFile::Text))
        {
            QMessageBox::critical(this, tr("Error!"), tr("Could not open file"));
            return;
        }
    }
    else
    {
        QMessageBox::critical(this, tr("Error!"), tr("No such file"));
        return;
    }

    struct amp_settings amplifier_set;
    struct fx_pedal_settings effects_set[4];
    QString name;
    LoadFromFile *loader = new LoadFromFile(file, &name, &amplifier_set, effects_set);

    loader->loadfile();
    file->close();
    delete loader;
    delete file;

    change_title(name);

    amp->load(amplifier_set);
    if(connected)
        amp->send_amp();
    if(settings.value("Settings/popupChangedWindows").toBool())
        amp->show();

    for(int i = 0; i < 4; i++)
    {
        switch(effects_set[i].fx_slot)
        {
        case 0x00:
            effect1->load(effects_set[i]);
            if(connected)
                effect1->send_fx();
            if(effects_set[i].effect_num)
                if(settings.value("Settings/popupChangedWindows").toBool())
                    effect1->show();
            break;

        case 0x01:
            effect2->load(effects_set[i]);
            if(connected)
                effect2->send_fx();
            if(effects_set[i].effect_num)
                if(settings.value("Settings/popupChangedWindows").toBool())
                    effect2->show();
            break;

        case 0x02:
            effect3->load(effects_set[i]);
            if(connected)
                effect3->send_fx();
            if(effects_set[i].effect_num)
                if(settings.value("Settings/popupChangedWindows").toBool())
                    effect3->show();
            break;

        case 0x03:
            effect4->load(effects_set[i]);
            if(connected)
                effect4->send_fx();
            if(effects_set[i].effect_num)
                if(settings.value("Settings/popupChangedWindows").toBool())
                    effect4->show();
            break;
        }
    }
}
Beispiel #26
0
int main(int argc, char *argv[])
{
    KAboutData aboutData("installer", 0, ki18n("Installer"),
    TRIBE_VERSION, ki18n("Graphical Installer for KaOS, forked from the Chakra-Project"), KAboutData::License_GPL,
                        ki18n("(c) 2008 - 2012 the Chakra Development Team"), ki18n("*****@*****.**"), "http://chakra-project.org");
    aboutData.addAuthor(ki18n("Manuel Tortosa"), ki18n("Maintainer"), "*****@*****.**", "http://chakra-project.org"); 
    aboutData.addAuthor(ki18n("Dario Freddi"), ki18n("Developer"), "*****@*****.**", "http://drfav.wordpress.com");
    aboutData.addAuthor(ki18n("Lukas Appelhans"), ki18n("Developer"), "*****@*****.**", "http://boom1992.wordpress.com");
    aboutData.addAuthor(ki18n("Jan Mette"), ki18n("PostInstall Backend and Artwork"), "", "");
    aboutData.addAuthor(ki18n("Phil Miller"), ki18n("PostInstall Backend"), "*****@*****.**", "http://chakra-project.org");
    aboutData.addAuthor(ki18n("Drake Justice"), ki18n("Developer"), "*****@*****.**", "");
    aboutData.addAuthor(ki18n("Georg Grabler"), ki18n("Developer"), "*****@*****.**", "");
    aboutData.addAuthor(ki18n("Daniele Cocca"), ki18n("Developer"), "*****@*****.**", "");
    aboutData.setBugAddress("http://kaosx.us/phpBB3/");

    KCmdLineArgs::init(argc, argv, &aboutData);

    if (!KUniqueApplication::start()) {
        qWarning("Installer is already running!\n");
        return 0;
    }

    // TODO: Port to KDBusService with FrameWorks5
    KUniqueApplication app;

    app.setWindowIcon(KIcon("tribe"));
    
    // Check the available memory before starting
    QFile memfile;
    memfile.setFileName("/proc/meminfo");
    if (memfile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&memfile);
        QString totalmem = in.readLine();
        memfile.close();               

        totalmem.remove(QRegExp("[^\\d]"));
        uint ram = (totalmem.toUInt() / 1024);

        qDebug() << ":: Starting Installer, RAM available for this install: " << ram << " Mbytes";
    
        if (ram < MIN_MEMORY) {
            int m = KMessageBox::warningContinueCancel(0, i18n("Your system does not meet the minimal memory needed\n"
                    "for installing KaOS with Installer (1gb), total available memory: %1 mbytes\n\n"
                    "Continue at your own risk", ram));
            if (m == KMessageBox::Cancel)
                return 0;
        }
    }
    
    // Check if we have a battery and if the power addaptop is plugged
    bool pu = false;

    foreach(const Solid::Device &device, Solid::Device::listFromType(Solid::DeviceInterface::Battery, QString())) {
        const Solid::Battery *b = qobject_cast<const Solid::Battery*> (device.asDeviceInterface(Solid::DeviceInterface::Battery));
        if(b->type() == Solid::Battery::PrimaryBattery || b->type() == Solid::Battery::UpsBattery) {
            qDebug() << ":: A battery or UPS has been detected";
            if (b->chargeState() == Solid::Battery::Discharging)
                pu = true;
            break;
        }
    }

    if (pu) {
        int r = KMessageBox::warningContinueCancel(0, i18n("It looks like your power adaptar is unplugged. "
                "Installation is a delicate and lenghty process, hence it is strongly advised to have your "
                "PC connected to AC to minimize possible risks."));
        if (r == KMessageBox::Cancel) {
            return 0;
        }
        qDebug() << ":: The power adapter is unplugged";
    }

    // Load the styleSheet
    QFile file(STYLESHEET_INSTALL_PATH);
    file.open(QFile::ReadOnly);
    QString styleSheet = QLatin1String(file.readAll());

    qApp->setStyleSheet(styleSheet);

    MainWindow mw;

    mw.show();

    return app.exec();
}
Beispiel #27
0
void Gopher::on_actionImport_triggered()
{
    QString inFile;
    QFile file;
    QString filename = QFileDialog::getOpenFileName(this, "Open file", "" ,"");
    file.setFileName(filename);
    file.open(QIODevice::ReadWrite | QIODevice::Text);
    inFile = file.readAll();
    file.close();

    QJsonDocument input = QJsonDocument::fromJson(inFile.toUtf8());
    list = input.object();
    //Info
    {
       ImportInfo();
    }
    //TEM 2D
    {
       ImportTEM2D();
    }
    //TEM Tomo
    {
        ImportTEMTomo();
    }
    //Cryo-Tem 2D
    {
        //Cryo-Tem Tab
        {
          ImportCryoTEM();
        }
        //Vitrobot Settings Tab
        {
           ImportCryoTEMVitrobotSettings();
        }
    }
    //Cryo-Tem Tomo
    {
        //Cryo-Tem Tomo Tab
        {
           ImportCryoTEMTomo();
        }
        //Vitrobot Settings Tab
        {
            ImportCryoTEMTomoVitrobotSettings();
        }
    }
    //Stem 2D
    {
       ImportStem2D();
    }
    //Stem Tomo
    {
        ImportStemTomo();
    }
    //SEM
    {
       ImportSEM();
    }
    //Cryo-SEM
    {
        //Cryo-SEM Tab
        {
           ImportCryoSEM();
        }
        //vitrobot Tab
        {
          ImportCryoSEMVitrobotSettings();
        }
    }
    //Confocal
    {
        ImportConfocal();
    }
}
Beispiel #28
0
// -------------------------------------------------------------------------
bool SpiceFile::recreateSubNetlist(QString *SpiceFile, QString *FileName)
{
  // initialize collectors
  ErrText = "";
  NetText = "";
  SimText = "";
  NetLine = "";

  // evaluate properties
  if(Props.at(1)->Value != "")
    makeSubcircuit = true;
  else
    makeSubcircuit = false;
  if(Props.at(2)->Value == "yes")
    insertSim = true;
  else
    insertSim = false;

  // preprocessor run if necessary
  QString preprocessor = Props.at(3)->Value;
  if (preprocessor != "none") {
    bool piping = true;
    QStringList script;
#ifdef __MINGW32__
    QString interpreter = "tinyperl.exe";
#else
    QString interpreter = "perl";
#endif
    if (preprocessor == "ps2sp") {
      script << "ps2sp";
    } else if (preprocessor == "spicepp") {
      script << "spicepp.pl";
    } else if (preprocessor == "spiceprm") {
      script << "spiceprm";
      piping = false;
    }
    SpicePrep = new QProcess(this);
    script << interpreter;
    script << script;
    script << *SpiceFile;

    QFile PrepFile;
    QString PrepName = *SpiceFile + ".pre";

    if (!piping) {
      script << PrepName;
      connect(SpicePrep, SIGNAL(readyReadStandardOutput()), SLOT(slotSkipOut()));
      connect(SpicePrep, SIGNAL(readyReadStandardError()), SLOT(slotGetPrepErr()));
    } else {
      connect(SpicePrep, SIGNAL(readyReadStandardOutput()), SLOT(slotGetPrepOut()));
      connect(SpicePrep, SIGNAL(readyReadStandardError()), SLOT(slotGetPrepErr()));
    }

    QMessageBox *MBox = 
      new QMessageBox(QMessageBox::NoIcon,
                      QObject::tr("Info"),
                      QObject::tr("Preprocessing SPICE file \"%1\".").arg(*SpiceFile),
                      QMessageBox::Abort);
    MBox->setAttribute(Qt::WA_DeleteOnClose);
    connect(SpicePrep, SIGNAL(finished(int)), MBox, SLOT(close()));

    if (piping) {
      PrepFile.setFileName(PrepName);
      if(!PrepFile.open(QIODevice::WriteOnly)) {
        ErrText +=
          QObject::tr("ERROR: Cannot save preprocessed SPICE file \"%1\".").
          arg(PrepName);
        return false;
      }
      prestream = new QTextStream(&PrepFile);
    }

    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    env.insert("PATH", env.value("PATH") );
    SpicePrep->setProcessEnvironment(env);
    SpicePrep->start(script.join(" "));
    //QucsHelp->setCommunication(0);

    if(SpicePrep->state()!=QProcess::Running&&
            SpicePrep->state()!=QProcess::Starting) {
      ErrText += QObject::tr("ERROR: Cannot execute \"%1\".").
              arg(interpreter + " " + script.join(" ") + "\".");
      if (piping) {
        PrepFile.close();
        delete prestream;
      }
      return false;
    }
    //SpicePrep->closeStdin();

    MBox->exec();
    delete SpicePrep;
    if (piping) {
      PrepFile.close();
      delete prestream;
    }
    *SpiceFile = PrepName;
  }

  // begin command line construction
  QString prog;
  QStringList com;
  //prog =  QucsSettings.BinDir + "qucsconv"  + executableSuffix;
  prog =  QucsSettings.Qucsconv;

  if(makeSubcircuit) com << "-g" << "_ref";
  com << "-if" << "spice" << "-of" << "qucs";
  com << "-i" << *SpiceFile;

  // begin netlist text creation
  if(makeSubcircuit) {
    QString f = misc::properFileName(*FileName);
    NetText += "\n.Def:" + misc::properName(f) + " ";
    QString PortNames = Props.at(1)->Value;
    PortNames.replace(',', ' ');
    NetText += PortNames;
    if(makeSubcircuit) NetText += " _ref";
  }
  NetText += "\n";

  // startup SPICE conversion process
  QucsConv = new QProcess(this);
  QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
  env.insert("PATH", env.value("PATH") );
  QucsConv->setProcessEnvironment(env);

  qDebug() << "SpiceFile::recreateSubNetlist :Command:" << prog << com.join(" ");
//  QucsConv->start(com.join(" "));
  QucsConv->start(prog, com);

  /// these slots might write into NetText, ErrText, outstream, filstream
  connect(QucsConv, SIGNAL(readyReadStandardOutput()), SLOT(slotGetNetlist()));
  connect(QucsConv, SIGNAL(readyReadStandardError()), SLOT(slotGetError()));
  connect(QucsConv, SIGNAL(finished(int,QProcess::ExitStatus)), SLOT(slotExited()));

  if(QucsConv->state()!=QProcess::Running&&
          QucsConv->state()!=QProcess::Starting) {
    ErrText += QObject::tr("COMP ERROR: Cannot start QucsConv!");
    return false;
  }
  (*outstream) << NetText;
  (*filstream) << NetText;

  // only interact with the GUI if it was launched
  if (QucsMain) {
    QucsMain->statusBar()->showMessage(tr("Converting SPICE file \"%1\".").arg(*SpiceFile), 2000);
  }
  else
    qDebug() << QObject::tr("Converting SPICE file \"%1\".").arg(*SpiceFile);

  // finish
  QucsConv->waitForFinished();
  delete QucsConv;
  lastLoaded = QDateTime::currentDateTime();
  return true;
}
void ModelGenerator::generateModel(QVector< QVector<int> > passed, QString passed_name) {
    splines = passed;
    filename = passed_name;
    int number_of_rotations = image_manager->number_of_images;
    int image_width = image_manager->getFirstImage().width(); // splines.size()
    int image_height = image_manager->getFirstImage().height(); //= splines.front().size();

    //Generate the texture
    texture = QImage(number_of_rotations * 5, image_height, QImage::Format_RGB32);
    for (int x = 0; x < number_of_rotations; x++) {
        QImage tex = image_manager->getTexture(x);
        tex = tex.scaled(image_width, image_height);
        for (int y = 0; y < image_height; y++) {
            if ((x * 5) - 2 >= 0)texture.setPixel((x * 5) - 2, y, tex.pixel(splines[x][y] - 1, y));
            if ((x * 5) - 1 >= 0)texture.setPixel((x * 5) - 1, y, tex.pixel(splines[x][y] - 1, y));
            texture.setPixel((x * 5), y, tex.pixel(splines[x][y], y));
            texture.setPixel((x * 5) + 1, y, tex.pixel(splines[x][y] + 1, y));
            texture.setPixel((x * 5) + 2, y, tex.pixel(splines[x][y] + 2, y));
        }
    }

    QString texture_file = filename;
    texture_file.append(".png");
    texture.save(texture_file);
    QString mat_file = filename;
    mat_file.append(".mtl");

    //THINGS TO FIX!!!!
    //add cropping of top and bottom
    //add setting center of rotation

    double spline_mult = cos((double) (90 - (double) laserAngle) / 57.29578); //Account for the angle of the laser
    //spline_mult = 0.3;
    for (int x = 0; x < number_of_rotations; x++) {
        QVector<point> spl;
        mesh.push_back(spl);
        double rotation = (360 / (double) number_of_rotations) * (double) x;
        for (int y = 0; y < image_height; y++) {
            double spline_point = ((double) (((double) ((double) image_width * params.center_of_rotation)-(double) splines[x][y])) / spline_mult);
            point po;
            po.x = (double) cos((double) (rotation / 57.29578)) * spline_point;
            po.y = y;
            po.z = (double) sin((double) (rotation / 57.29578)) * spline_point;
            //cerr << "point @ " << po.x << " " << po.y << " " << po.z << endl;
            mesh[x].push_back(po);
        }
    }

    QFile file;
    QString object_file = filename;
    object_file.append(".obj");
    file.setFileName(object_file);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);

    for (int y = splines[0].size()-1; y >=0 ; y--) {
        for (int x = 0; x <splines.size() ; x++) {
            QString line = QString("vt ");
            line.append(QString(" ").append(QString::number((double) (1 / (double)splines.size())*x )));
            line.append(QString(" ").append(QString::number((double) (1 / (double) splines[0].size())*y)));
            out<<line.toStdString().c_str()<<endl;
        }
    }
    out << "mtllib " << mat_file.toStdString().c_str()<< endl;
    out << "usemtl Textured" << endl;

    int count = 1;
    for (int y = 0; y < image_height; y++) {
        for (int x = 0; x < number_of_rotations; x++) {

            QString x_val = QString::number(mesh[x][y].x);
            QString y_val = QString::number(mesh[x][y].y);
            QString z_val = QString::number(mesh[x][y].z);

            QString line;
            line.append("v ");
            line.append(x_val);
            line.append(" ");
            line.append(y_val);
            line.append(" ");
            line.append(z_val);
            line.append("\n");
            out << line.toStdString().c_str();
            count++;
        }
    }



    //cout<<"f v1 v2 v101 v102"<<endl;
    //cout<<"f v2 v3 v101 v102"<<endl;
    //cout<<"f v3 v4 v103 v104"<<endl;

    count = 1;
    for (int y = 0; y < splines[0].size() - 1; y++) {
        for (int x = 0; x < splines.size() - 1; x++) {
            QString line;
            int x_val = count;

            QString tl = QString(" ").append(QString::number(x_val));
            QString tr = QString(" ").append(QString::number(x_val + 1));
            QString bl = QString(" ").append(QString::number(x_val + splines.size()));
            QString br = QString(" ").append(QString::number(x_val + splines.size() + 1));

            line.append("f ");
            line.append(tl);
            line.append("/");
            line.append(QString::number(count));
            line.append(tr);
            line.append("/");
            line.append(QString::number(count + 1));
            line.append(br);
            line.append("/");
            line.append(QString::number(count + splines.size() + 1));
            line.append(bl);
            line.append("/");
            line.append(QString::number(count + splines.size()));
            line.append("\n");
            out << line.toStdString().c_str();
            count++;
        }
    }



    file.close();


    QFile mtl;
    mtl.setFileName(mat_file);
    mtl.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out2(&mtl);
    QString mat_file_line = QString("newmtl Textured \nKa 1.000 1.000 1.000\nKd 1.000 1.000 1.000\nKs 0.000 0.000 0.000\nd 1.0\nTr 1.0\nillum 2\nmap_Ka ");

    mat_file_line.append(texture_file);
    mat_file_line.append("\nmap_Kd ");
    mat_file_line.append(texture_file);
    out2 << mat_file_line.toStdString().c_str();

    mtl.close();

}
void ChatWindowStyle::readStyleFiles()
{
    // load style info
    QString infoPlistFile = d->baseHref + QLatin1String("../Info.plist");
    ChatStylePlistFileReader plistReader(infoPlistFile);
    d->defaultVariantName = plistReader.defaultVariant();
    if (d->defaultVariantName.isEmpty()) {
        // older themes use this
        d->defaultVariantName = plistReader.displayNameForNoVariant();
    }
    if (d->defaultVariantName.isEmpty()) {
        // If name is still empty we use "Normal"
        d->defaultVariantName = i18nc("Normal style variant menu item", "Normal");
    }
    kDebug() << "defaultVariantName = " << d->defaultVariantName;
    d->defaultFontFamily  = plistReader.defaultFontFamily();
    d->defaultFontSize    = plistReader.defaultFontSize();
    d->disableCombineConsecutive = plistReader.disableCombineConsecutive();
    d->messageViewVersion = plistReader.messageViewVersion();

    // specify the files for the identifiers
    QHash<InternalIdentifier, QLatin1String> templateFiles;

    templateFiles.insert(Template, QLatin1String("Template.html"));

    templateFiles.insert(Header, QLatin1String("Header.html"));
    templateFiles.insert(Content, QLatin1String("Content.html"));
    templateFiles.insert(Footer, QLatin1String("Footer.html"));
    templateFiles.insert(Topic, QLatin1String("Topic.html"));

    templateFiles.insert(IncomingContent, QLatin1String("Incoming/Content.html"));
    templateFiles.insert(IncomingNextContent, QLatin1String("Incoming/NextContent.html"));
    templateFiles.insert(OutgoingContent, QLatin1String("Outgoing/Content.html"));
    templateFiles.insert(OutgoingNextContent, QLatin1String("Outgoing/NextContent.html"));
    templateFiles.insert(Status, QLatin1String("Status.html"));

    templateFiles.insert(IncomingHistory, QLatin1String("Incoming/Context.html"));
    templateFiles.insert(IncomingNextHistory, QLatin1String("Incoming/NextContext.html"));
    templateFiles.insert(OutgoingHistory, QLatin1String("Outgoing/Context.html"));
    templateFiles.insert(OutgoingNextHistory, QLatin1String("Outgoing/NextContext.html"));

    templateFiles.insert(ActionIncoming, QLatin1String("Incoming/Action.html"));
    templateFiles.insert(ActionOutgoing, QLatin1String("Outgoing/Action.html"));

    templateFiles.insert(FileTransferIncoming, QLatin1String("FileTransferRequest.html"));
    templateFiles.insert(VoiceClipIncoming, QLatin1String("voiceClipRequest.html"));

    templateFiles.insert(OutgoingStateUnknown, QLatin1String("Outgoing/StateUnknown.html"));
    templateFiles.insert(OutgoingStateSending, QLatin1String("Outgoing/StateSending.html"));
    templateFiles.insert(OutgoingStateSent, QLatin1String("Outgoing/StateSent.html"));
    templateFiles.insert(OutgoingStateError, QLatin1String("Outgoing/StateError.html"));


    // load all files
    QFile fileAccess;
    Q_FOREACH(const QLatin1String &fileName, templateFiles) {
        QString path = d->baseHref + fileName;
        // Load template file
        if (QFile::exists(path)) {
            fileAccess.setFileName(path);
            fileAccess.open(QIODevice::ReadOnly);
            QTextStream headerStream(&fileAccess);
            headerStream.setCodec(QTextCodec::codecForName("UTF-8"));
            QString data = headerStream.readAll();
            if(!data.isEmpty()) {
                //kDebug() << fileName << "was found!";
                setContent( templateFiles.key(fileName), data);
            } else {
                kDebug() << fileName << "was not found!";
            }
            //kDebug() << fileName << content(templateFiles.key(fileName));
            fileAccess.close();
        }
    }