Ejemplo n.º 1
0
	void SchemeReply::List ()
	{
		QDir dir (url ().toLocalFile ());
		if (!dir.exists ())
		{
			setError (ContentNotFoundError,
					tr ("%1: no such file or directory")
						.arg (dir.absolutePath ()));
			emit error (ContentNotFoundError);
			emit finished ();
			return;
		}

		if (!dir.isReadable ())
		{
			setError (ContentAccessDenied,
					tr ("Unable to read %1")
						.arg (dir.absolutePath ()));
			emit error (ContentAccessDenied);
			emit finished ();
			return;
		}

		QFile basetplFile (":/plugins/poshuku/plugins/filescheme/basetemplate.tpl");
		if (!basetplFile.open (QIODevice::ReadOnly))
		{
			qWarning () << Q_FUNC_INFO
				<< "unable to open"
				<< basetplFile.fileName ();
			return;
		}

		QFile rowtplFile (":/plugins/poshuku/plugins/filescheme/rowtemplate.tpl");
		if (!rowtplFile.open (QIODevice::ReadOnly))
		{
			qWarning () << Q_FUNC_INFO
				<< "unable to open"
				<< rowtplFile.fileName ();
			return;
		}

		QString html = basetplFile.readAll ();
		QString row = rowtplFile.readAll ();
		QString link = "<a href=\"%1\">%2</a>";

		QString rows;

		if (!dir.isRoot ())
		{
			QIcon icon = qApp->style ()->standardIcon (QStyle::SP_FileDialogToParent);
			QString addr = QString::fromUtf8 (
						QUrl::fromLocalFile (
							QFileInfo (
								dir.absoluteFilePath ("..")
								).canonicalFilePath ()
							).toEncoded( )
						);
			rows += row
				.arg (GetBase64 (icon))
				.arg (link
						.arg (addr)
						.arg (".."))
				.arg (QString ())
				.arg (QString ());
		}

		QFileIconProvider iconProvider;

		const auto& list = dir.entryInfoList (QDir::AllEntries | QDir::Hidden,
				QDir::Name | QDir::DirsFirst);

		for (const auto& entry : list)
		{
			if (entry.fileName () == "." ||
					entry.fileName () == "..")
				continue;

			QUrl urlAddr = QUrl::fromLocalFile (entry.canonicalFilePath ());
			QString addr = QString::fromUtf8 (urlAddr.toEncoded ());
			QString size;
			if (entry.isFile ())
				size = Util::MakePrettySize (entry.size ());
			QString modified = entry.lastModified ()
				.toString (Qt::SystemLocaleShortDate);

			rows += row
				.arg (GetBase64 (iconProvider.icon (entry)))
				.arg (link
						.arg (addr)
						.arg (entry.fileName ()))
				.arg (size)
				.arg (modified);
		}

		html = html
			.arg (dir.absolutePath ())
			.arg (tr ("Contents of %1")
					.arg (dir.absolutePath ()))
			.arg (tr ("File"))
			.arg (tr ("Size"))
			.arg (tr ("Modified"))
			.arg (rows);

		QTextStream stream (&Buffer_);
		stream << html;
		stream.flush ();
		Buffer_.reset ();

		setHeader (QNetworkRequest::ContentTypeHeader,
				QByteArray ("text/html"));
		setHeader (QNetworkRequest::ContentLengthHeader,
				Buffer_.bytesAvailable ());
		setAttribute (QNetworkRequest::HttpStatusCodeAttribute,
				200);
		setAttribute (QNetworkRequest::HttpReasonPhraseAttribute,
				QByteArray ("OK"));
		emit metaDataChanged ();
		emit downloadProgress (Buffer_.size (), Buffer_.size ());
		NetworkError errorCode = error ();
		if (errorCode != NoError)
			emit error (errorCode);
		else if (Buffer_.size () > 0)
			emit readyRead ();

		emit finished ();
	}
Ejemplo n.º 2
0
int main(int argc, char** argv)
{
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("latin1"));
    AppliArgs args(QStringList() << "~help,h" << "~version,v" << "output=1,o");
    QTextStream out(stdout), err(stderr);
    unsigned long int length;
    struct jbg_dec_state sd;
    unsigned char *buffer;
    QString hw("%1 %2\n");
    QByteArray data;
    bool argsErr;
    QFile input;

    // Parse arguments
    argsErr = !args.parse(argc, argv, 1);
    if (argsErr || args.isOptionSet("help")) {
        args.printErrors(err);

        out << QString(_("Usage: %1 [options] <JBIG file>")).arg(args.
            applicationName()) << endl;
        out << _("Available options:") << endl;
        out << _("  --help, -h                Print this help message") << endl;
        out << _("  --output, -o              Select the output file") << endl;
        out << _("  --version, -v             Print the version information") <<
            endl;
        return argsErr ? 1 : 0;
    } else if (args.isOptionSet("version")) {
        out << _("(C) jbgtopbm, 2007 by Aurélien Croc") << endl;
        out << _("This project is under the GNU General Public Licence "
            "version 2") << endl;
        out << _("More information => http://splix.ap2c.org") << endl << endl;
        return 0;
    }


    // Open the input and the output file
    input.setFileName(args.parameter(0));
    if (!input.open(QIODevice::ReadOnly)) {
        err << _("Error: cannot open file ") << args.parameter(0) << endl;
        return -1;
    }
    data = input.readAll();
    buffer = (unsigned char *)data.data();
    length = data.length();
    if (args.isOptionSet("output"))
        output.setFileName(args.optionArg("output", 0));
    else
        output.setFileName("/dev/stdout");
    if (!output.open(QIODevice::WriteOnly)) {
        err << _("Error: cannot open file ") << output.fileName() << endl;
        return -1;
    }


    // Decompress the image
    jbg_dec_init(&sd);
    while (length) {
        unsigned long size;
        int res;

        size = *(unsigned long*)buffer;
        printf("Taille=%lu\n", size);
        buffer += sizeof(size);
        length -= sizeof(size);
        res = jbg_dec_in(&sd, buffer, size, NULL);
        if (res == JBG_EOK) {
            out << _("Processed.") << endl;
            break;
        } else if (res != JBG_EAGAIN) {
            err << _("JBG not ok ") << res << endl;
            break;
        }
        length -= size;
        buffer += size;
    }

    // Store the image
    output.write("P4\n");
    output.write("# Image created by jbgtopbm, (C) 2007 by Aurélien Croc "
        "(AP²C)\n");
    hw = hw.arg(jbg_dec_getwidth(&sd)).arg(jbg_dec_getheight(&sd));
    output.write(hw.toAscii());
    output.write((const char *)jbg_dec_getimage(&sd, 0), jbg_dec_getsize(&sd));
    output.close();

    return 0;
}
Ejemplo n.º 3
0
void FoxGroundDocument::SetBaseFileDoc(const QString file) {

    QFileInfo localfile(file);
    if (!localfile.exists()) {
        CurrentRunDoc = UNKNOW;
        return;
    }
    document_file = file;
    //// try on pole...
    bool poleisrun = false;
    POLE::Storage storage(file.toLocal8Bit());
    if (storage.open()) {
        QBuffer basestore;
        if (Conversion::readStreamPole(storage, "/SummaryInformation", basestore)) {
            LEInputStream *sis_baseSummaryInformation = new LEInputStream(&basestore);
            poleisrun = true;
            CurrentRunDoc = OFFICEMSO;
            document_name = "DOC";
        }
    }
    QByteArray x;
    QFile *f = new QFile(file);
    if (f->open(QIODevice::ReadOnly)) {
        x = f->readAll();
    }
    f->close();
    const QByteArray data = x;
    QDomDocument document;
    QString c;
    int d, o;
    bool xmlbased = false;
    if (document.setContent(data, true, &c)) {
        /// not xml based...
        xmlbased = true;
    }
    const QByteArray rtfsearch = x.mid(0, 5).simplified();
    /// qDebug() << "rtfsearch :" << rtfsearch;
    //// no office family .. doc
    if (!poleisrun) {
        if (xmlbased && data.indexOf("encoding=") != -1) {
            if (data.indexOf("DOCTYPE html") > 0) {
                CurrentRunDoc = HTML;
                document_name = "HTML";
            } else {
                document_name = "XML";
                CurrentRunDoc = XML;
            }
        } else if (rtfsearch == "{\\rtf") {
            CurrentRunDoc = RTF;
            document_name = "RTF";
        } else if (data.mid(0, 4) == "%PDF") {
            if (bin_pdftohtml.size() > 3) {
                CurrentRunDoc = PDF;
                document_name = "PDF";
            } else {
                CurrentRunDoc = UNKNOW;
            }
        } else if (data.mid(0, 2) == "PK") {
            KZip::Stream *unzip = new KZip::Stream(file);
            if (unzip->canread()) {
                unzipfileliste = unzip->filelist();
                corefile = unzip->listData();
                if (docitem("word/document.xml").size() > 20) {
                    CurrentRunDoc = DOCX;
                    document_name = "DOCX";
                } else if (docitem("content.xml").size() > 20) {
                    CurrentRunDoc = ODT;
                    document_name = "ODT";
                } else {
                    CurrentRunDoc = UNKNOW;
                }
            }
            unzip->~Stream();
            unzip = NULL;
        } else {
            CurrentRunDoc = UNKNOW;
        }
    }

    if (CurrentRunDoc == UNKNOW) {
        document_name = "NULL";
    }
}
Ejemplo n.º 4
0
/************************************************************
** Member Function
**
** Name: create
** Parameter: xmlUI - XML UI's file
** Returned Value: bool - Successed return true, failed return
**													  false
** Intro: Create a widget by xml string.
************************************************************/
bool FFactory::create(QFile xmlUI) {
	QString xmlText = xmlUI.readAll();
	return create(xmlText);
}
Ejemplo n.º 5
0
void UploadAssetTask::run() {
    auto data = _receivedMessage->getMessage();
    
    QBuffer buffer { &data };
    buffer.open(QIODevice::ReadOnly);
    
    MessageID messageID;
    buffer.read(reinterpret_cast<char*>(&messageID), sizeof(messageID));
    
    uint64_t fileSize;
    buffer.read(reinterpret_cast<char*>(&fileSize), sizeof(fileSize));
    
    qDebug() << "UploadAssetTask reading a file of " << fileSize << "bytes from"
        << uuidStringWithoutCurlyBraces(_senderNode->getUUID());
    
    auto replyPacket = NLPacket::create(PacketType::AssetUploadReply);
    replyPacket->writePrimitive(messageID);
    
    if (fileSize > MAX_UPLOAD_SIZE) {
        replyPacket->writePrimitive(AssetServerError::AssetTooLarge);
    } else {
        QByteArray fileData = buffer.read(fileSize);
        
        auto hash = hashData(fileData);
        auto hexHash = hash.toHex();
        
        qDebug() << "Hash for uploaded file from" << uuidStringWithoutCurlyBraces(_senderNode->getUUID())
            << "is: (" << hexHash << ") ";
        
        QFile file { _resourcesDir.filePath(QString(hexHash)) };

        bool existingCorrectFile = false;
        
        if (file.exists()) {
            // check if the local file has the correct contents, otherwise we overwrite
            if (file.open(QIODevice::ReadOnly) && hashData(file.readAll()) == hash) {
                qDebug() << "Not overwriting existing verified file: " << hexHash;

                existingCorrectFile = true;

                replyPacket->writePrimitive(AssetServerError::NoError);
                replyPacket->write(hash);
            } else {
                qDebug() << "Overwriting an existing file whose contents did not match the expected hash: " << hexHash;
                file.close();
            }
        }

        if (!existingCorrectFile) {
            if (file.open(QIODevice::WriteOnly) && file.write(fileData) == qint64(fileSize)) {
                qDebug() << "Wrote file" << hexHash << "to disk. Upload complete";
                file.close();

                replyPacket->writePrimitive(AssetServerError::NoError);
                replyPacket->write(hash);
            } else {
                qWarning() << "Failed to upload or write to file" << hexHash << " - upload failed.";

                // upload has failed - remove the file and return an error
                auto removed = file.remove();

                if (!removed) {
                    qWarning() << "Removal of failed upload file" << hexHash << "failed.";
                }
                
                replyPacket->writePrimitive(AssetServerError::FileOperationFailed);
            }
        }


    }
    
    auto nodeList = DependencyManager::get<NodeList>();
    nodeList->sendPacket(std::move(replyPacket), *_senderNode);
}
Ejemplo n.º 6
0
// ---------------------------------------------------
// 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.remove(Collect.begin());
    if(Line == "*") {  // worked on all components ?
      startSimulator(); // <<<<<================== go on ===
      return;
    }
#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";
  if(makeSubcircuit)
    com << "-g" << "_ref";
  com << "-if" << "spice" << "-of" << "qucs";

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

  if(makeSubcircuit) {
    Stream << "\n.Def:" << 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->insert(tr("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()));
}
Ejemplo n.º 7
0
void KConfigINIBackEnd::parseSingleConfigFile(QFile &rFile, KEntryMap *pWriteBackMap, bool bGlobal, bool bDefault)
{
    const char *s;   // May get clobbered by sigsetjump, but we don't use them afterwards.
    const char *eof; // May get clobbered by sigsetjump, but we don't use them afterwards.
    QByteArray data;

    if(!rFile.isOpen()) // come back, if you have real work for us ;->
        return;

    // using kdDebug() here leads to an infinite loop
    // remove this for the release, aleXXX
    // qWarning("Parsing %s, global = %s default = %s",
    //           rFile.name().latin1(), bGlobal ? "true" : "false", bDefault ? "true" : "false");

    QCString aCurrentGroup("<default>");

    unsigned int ll = localeString.length();

#ifdef HAVE_MMAP
    static volatile const char *map;
    map = (const char *)mmap(0, rFile.size(), PROT_READ, MAP_PRIVATE, rFile.handle(), 0);

    if(map != MAP_FAILED)
    {
        s = (const char *)map;
        eof = s + rFile.size();

#ifdef SIGBUS
        struct sigaction act;
        act.sa_handler = mmap_sigbus_handler;
        sigemptyset(&act.sa_mask);
#ifdef SA_ONESHOT
        act.sa_flags = SA_ONESHOT;
#else
        act.sa_flags = SA_RESETHAND;
#endif
        sigaction(SIGBUS, &act, &mmap_old_sigact);

        if(sigsetjmp(mmap_jmpbuf, 1))
        {
            qWarning("SIGBUS while reading %s", rFile.name().latin1());
            munmap((char *)map, rFile.size());
            sigaction(SIGBUS, &mmap_old_sigact, 0);
            return;
        }
#endif
    }
    else
#endif
    {
        rFile.at(0);
        data = rFile.readAll();
        s = data.data();
        eof = s + data.size();
    }

    bool fileOptionImmutable = false;
    bool groupOptionImmutable = false;
    bool groupSkip = false;

    int line = 0;
    for(; s < eof; s++)
    {
        line++;

        while((s < eof) && isspace(*s) && (*s != '\n'))
            s++; // skip leading whitespace, shouldn't happen too often

        // skip empty lines, lines starting with #
        if((s < eof) && ((*s == '\n') || (*s == '#')))
        {
        sktoeol: // skip till end-of-line
            while((s < eof) && (*s != '\n'))
                s++;
            continue; // Empty or comment or no keyword
        }
        const char *startLine = s;

        if(*s == '[') // group
        {
            // In a group [[ and ]] have a special meaning
            while((s < eof) && (*s != '\n'))
            {
                if(*s == ']')
                {
                    if((s + 1 < eof) && (*(s + 1) == ']'))
                        s++; // Skip "]]"
                    else
                        break;
                }

                s++; // Search till end of group
            }
            const char *e = s;
            while((s < eof) && (*s != '\n'))
                s++; // Search till end of line / end of file
            if((e >= eof) || (*e != ']'))
            {
                fprintf(stderr, "Invalid group header at %s:%d\n", rFile.name().latin1(), line);
                continue;
            }
            // group found; get the group name by taking everything in
            // between the brackets
            if((e - startLine == 3) && (startLine[1] == '$') && (startLine[2] == 'i'))
            {
                if(!kde_kiosk_exception)
                    fileOptionImmutable = true;
                continue;
            }

            aCurrentGroup = decodeGroup(startLine + 1, e - startLine);
            // cout<<"found group ["<<aCurrentGroup<<"]"<<endl;

            // Backwards compatibility
            if(aCurrentGroup == "KDE Desktop Entry")
                aCurrentGroup = "Desktop Entry";

            groupOptionImmutable = fileOptionImmutable;

            e++;
            if((e + 2 < eof) && (*e++ == '[') && (*e++ == '$')) // Option follows
            {
                if((*e == 'i') && !kde_kiosk_exception)
                {
                    groupOptionImmutable = true;
                }
            }

            KEntryKey groupKey(aCurrentGroup, 0);
            KEntry entry = pConfig->lookupData(groupKey);
            groupSkip = entry.bImmutable;

            if(groupSkip && !bDefault)
                continue;

            entry.bImmutable |= groupOptionImmutable;
            pConfig->putData(groupKey, entry, false);

            if(pWriteBackMap)
            {
                // add the special group key indicator
                (*pWriteBackMap)[groupKey] = entry;
            }

            continue;
        }
        if(groupSkip && !bDefault)
            goto sktoeol; // Skip entry

        bool optionImmutable = groupOptionImmutable;
        bool optionDeleted = false;
        bool optionExpand = false;
        const char *endOfKey = 0, *locale = 0, *elocale = 0;
        for(; (s < eof) && (*s != '\n'); s++)
        {
            if(*s == '=') // find the equal sign
            {
                if(!endOfKey)
                    endOfKey = s;
                goto haveeq;
            }
            if(*s == '[') // find the locale or options.
            {
                const char *option;
                const char *eoption;
                endOfKey = s;
                option = ++s;
                for(;; s++)
                {
                    if((s >= eof) || (*s == '\n') || (*s == '='))
                    {
                        fprintf(stderr, "Invalid entry (missing ']') at %s:%d\n", rFile.name().latin1(), line);
                        goto sktoeol;
                    }
                    if(*s == ']')
                        break;
                }
                eoption = s;
                if(*option != '$')
                {
                    // Locale
                    if(locale)
                    {
                        fprintf(stderr, "Invalid entry (second locale!?) at %s:%d\n", rFile.name().latin1(), line);
                        goto sktoeol;
                    }
                    locale = option;
                    elocale = eoption;
                }
                else
                {
                    // Option
                    while(option < eoption)
                    {
                        option++;
                        if((*option == 'i') && !kde_kiosk_exception)
                            optionImmutable = true;
                        else if(*option == 'e')
                            optionExpand = true;
                        else if(*option == 'd')
                        {
                            optionDeleted = true;
                            goto haveeq;
                        }
                        else if(*option == ']')
                            break;
                    }
                }
            }
        }
        fprintf(stderr, "Invalid entry (missing '=') at %s:%d\n", rFile.name().latin1(), line);
        continue;

    haveeq:
        for(endOfKey--;; endOfKey--)
        {
            if(endOfKey < startLine)
            {
                fprintf(stderr, "Invalid entry (empty key) at %s:%d\n", rFile.name().latin1(), line);
                goto sktoeol;
            }
            if(!isspace(*endOfKey))
                break;
        }

        const char *st = ++s;
        while((s < eof) && (*s != '\n'))
            s++; // Search till end of line / end of file

        if(locale)
        {
            unsigned int cl = static_cast< unsigned int >(elocale - locale);
            if((ll != cl) || memcmp(locale, localeString.data(), ll))
            {
                // backward compatibility. C == en_US
                if(cl != 1 || ll != 5 || *locale != 'C' || memcmp(localeString.data(), "en_US", 5))
                {
                    // cout<<"mismatched locale '"<<QCString(locale, elocale-locale +1)<<"'"<<endl;
                    // We can ignore this one
                    if(!pWriteBackMap)
                        continue; // We just ignore it
                    // We just store it as is to be able to write it back later.
                    endOfKey = elocale;
                    locale = 0;
                }
            }
        }

        // insert the key/value line
        QCString key(startLine, endOfKey - startLine + 2);
        QCString val = printableToString(st, s - st);
        // qDebug("found key '%s' with value '%s'", key.data(), val.data());

        KEntryKey aEntryKey(aCurrentGroup, decodeKey(key));
        aEntryKey.bLocal = (locale != 0);
        aEntryKey.bDefault = bDefault;

        KEntry aEntry;
        aEntry.mValue = val;
        aEntry.bGlobal = bGlobal;
        aEntry.bImmutable = optionImmutable;
        aEntry.bDeleted = optionDeleted;
        aEntry.bExpand = optionExpand;
        aEntry.bNLS = (locale != 0);

        if(pWriteBackMap)
        {
            // don't insert into the config object but into the temporary
            // scratchpad map
            pWriteBackMap->insert(aEntryKey, aEntry);
        }
        else
        {
            // directly insert value into config object
            // no need to specify localization; if the key we just
            // retrieved was localized already, no need to localize it again.
            pConfig->putData(aEntryKey, aEntry, false);
        }
    }
    if(fileOptionImmutable)
        bFileImmutable = true;

#ifdef HAVE_MMAP
    if(map)
    {
        munmap((char *)map, rFile.size());
#ifdef SIGBUS
        sigaction(SIGBUS, &mmap_old_sigact, 0);
#endif
    }
#endif
}
Ejemplo n.º 8
0
void ATPAssetMigrator::loadEntityServerFile() {
    auto filename = QFileDialog::getOpenFileName(_dialogParent, "Select an entity-server content file to migrate",
                                                 QString(), QString("Entity-Server Content (*.gz)"));
    
    if (!filename.isEmpty()) {
        qCDebug(asset_migrator) << "Selected filename for ATP asset migration: " << filename;
        
        static const QString MIGRATION_CONFIRMATION_TEXT {
            "The ATP Asset Migration process will scan the selected entity-server file, upload discovered resources to the"\
            " current asset-server and then save a new entity-server file with the ATP URLs.\n\nAre you ready to"\
            " continue?\n\nMake sure you are connected to the right domain."
        };
        
        auto button = QMessageBox::question(_dialogParent, MESSAGE_BOX_TITLE, MIGRATION_CONFIRMATION_TEXT,
                                            QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
        
        if (button == QMessageBox::No) {
            return;
        }
        
        // try to open the file at the given filename
        QFile modelsFile { filename };
        
        if (modelsFile.open(QIODevice::ReadOnly)) {
            QByteArray compressedJsonData = modelsFile.readAll();
            QByteArray jsonData;
            
            if (!gunzip(compressedJsonData, jsonData)) {
                QMessageBox::warning(_dialogParent, "Error", "The file at" + filename + "was not in gzip format.");
            }
            
            QJsonDocument modelsJSON = QJsonDocument::fromJson(jsonData);
            _entitiesArray = modelsJSON.object()["Entities"].toArray();
            
            for (auto jsonValue : _entitiesArray) {
                QJsonObject entityObject = jsonValue.toObject();
                QString modelURLString = entityObject.value(MODEL_URL_KEY).toString();
                
                if (!modelURLString.isEmpty()) {
                    QUrl modelURL = QUrl(modelURLString);
                    
                    if (!_ignoredUrls.contains(modelURL)
                        && (modelURL.scheme() == URL_SCHEME_HTTP || modelURL.scheme() == URL_SCHEME_HTTPS
                            || modelURL.scheme() == URL_SCHEME_FILE || modelURL.scheme() == URL_SCHEME_FTP)) {
                        
                        if (_pendingReplacements.contains(modelURL)) {
                            // we already have a request out for this asset, just store the QJsonValueRef
                            // so we can do the hash replacement when the request comes back
                            _pendingReplacements.insert(modelURL, jsonValue);
                        } else if (_uploadedAssets.contains(modelURL)) {
                            // we already have a hash for this asset
                            // so just do the replacement immediately
                            entityObject[MODEL_URL_KEY] = _uploadedAssets.value(modelURL).toString();
                            jsonValue = entityObject;
                        } else if (wantsToMigrateResource(modelURL)) {
                            auto request = ResourceManager::createResourceRequest(this, modelURL);
                            
                            if (request) {
                                qCDebug(asset_migrator) << "Requesting" << modelURL << "for ATP asset migration";
                                
                                // add this combination of QUrl and QJsonValueRef to our multi hash so we can change the URL
                                // to an ATP one once ready
                                _pendingReplacements.insert(modelURL, jsonValue);
                                
                                connect(request, &ResourceRequest::finished, this, [=]() {
                                    if (request->getResult() == ResourceRequest::Success) {
                                        migrateResource(request);
                                    } else {
                                        QMessageBox::warning(_dialogParent, "Error",
                                                             QString("Could not retrieve asset at %1").arg(modelURL.toString()));
                                    }
                                    request->deleteLater();
                                });
                                
                                request->send();
                            } else {
                                QMessageBox::warning(_dialogParent, "Error",
                                                     QString("Could not create request for asset at %1").arg(modelURL.toString()));
                            }
                            
                        } else {
                            _ignoredUrls.insert(modelURL);
                        }
                    }
                }
            }
            
            _doneReading = true;
            
        } else {
            QMessageBox::warning(_dialogParent, "Error",
                                 "There was a problem loading that entity-server file for ATP asset migration. Please try again");
        }
    }
}
Ejemplo n.º 9
0
void LocalApp::readSuffixFilter(){
    QFile *suffixFilterFile = 0;
    if ( appName == "home")
        suffixFilterFile = new QFile (home+"/"+QString("home.suffixfilter"));
    else
        suffixFilterFile = new QFile (home+"/"+ appName + "/"+ appName + QString(".suffixfilter"));
    ERR<<"INFO: LocalApp::readSuffixFilter(): "<<suffixFilterFile->fileName()<<endl;
#ifndef USE_QT5
    if ( ! suffixFilterFile->open(QIODevice::ReadOnly) ){
#else
    if ( ! suffixFilterFile->open(QFile::ReadOnly) ){
#endif
        ERR<<"WARN: LocalApp::readSuffixFilter(): Unable to read : "<<suffixFilterFile->fileName()<<endl;
        suffixFilterFile->close();

    }else {
        suffixFilter += suffixFilterFile->readAll();
        suffixFilterFile->close();
    }

    //TODO: convert suffix filter to map of string
    ERR<<"DBUG: LocalApp::readSuffixFilter(): "<<suffixFilter<<endl;
    delete suffixFilterFile;
}

void LocalApp::readLibraryLoadConfig(){
    QFile *llConfigFile = 0;
    if ( appName == "home")
        llConfigFile = new QFile (home+"/"+QString("home.cfg"));
    else
        llConfigFile = new QFile (home+"/"+ appName + "/"+ appName + QString(".cfg"));
#ifndef USE_QT5
    if ( ! llConfigFile->open(QIODevice::ReadOnly) ){
#else
    if ( ! llConfigFile->open(QFile::ReadOnly) ){
#endif
        ERR<<"DBUG: LocalApp::readLibraryLoadConfig(): Unable to open file :"<<llConfigFile->fileName()<<endl;
    } else {
        QByteArray libConfig;
        while ( (libConfig = llConfigFile->readLine() ).length() > 0 ){
            /*
             * Read the config file
             * <scriptname>:<libraryname>
             */
            QString line(libConfig);
            if( line.split(":").length() > 1) {
                QString script = line.split(":")[0];
                QString soFile = line.split(":")[1];
#ifndef WINDOWS
                soFile.replace(QString("\n"), QString(""));
                soFile += QString(".so");
                //soFile.remove(soFile.length()-1,1);
#else
                soFile.replace(QString("\r\n"), QString(""));
                soFile += QString(".dll");
                //soFile.remove(soFile.length()-2,2);
#endif
                if( appName == "home"){
                    QLibrary *lib = new QLibrary( home + "/" + soFile );
                    lib->setLoadHints(QLibrary::ResolveAllSymbolsHint);
                    lib->load();
                    ERR<<"ERRR: LocalApp::readLibraryLoadConfig(): "<< script<<" -> "<<lib->fileName()<<": Loaded ? "<<lib->isLoaded()<<endl;
                    mapScriptToSo[script] = lib;

                } else {
                    QLibrary *lib = new QLibrary( home + "/" + appName + "/" + soFile, this );
                    lib->setLoadHints(QLibrary::ResolveAllSymbolsHint);
                    lib->load();
                    ERR<<"ERRR: LocalApp::readLibraryLoadConfig(): "<<script<<" -> "<<lib->fileName()<<": Loaded ? "<<lib->isLoaded()<<endl;
                    mapScriptToSo[script] = lib;
                }
            }
        }
    }

    delete llConfigFile;
}


QString LocalApp::readAppName( QUrl url ){
    QString app("");
#ifndef USE_QT5
    ERR<<"INFO: LocalApp::readAppName(): Encoded Path: "<<url.encodedPath()<<endl;
    //QStringList
    app = url.encodedPath().split('/')[0];
    //app = list[0];
    if ( app.contains(".py")){
       app = "home";
    }
    ERR<<"INFO: LocalApp::readAppName(): App: "<<app<<endl;
#else
    ERR<<"INFO: LocalApp::readAppName(): Path: "<<url.path()<<endl;
    app = url.path().split('/')[0];
    if ( app.contains(".py") || app.contains(".")){
        app = "home";
    }
    ERR<<"INFO: LocalApp::readAppName(): App: "<<app<<endl;
    ERR<<"INFO: LocalApp::readAppName(): Path: "<<url.path()<<endl;
#endif
    return app;
}
Ejemplo n.º 10
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QApplication::setOrganizationName(_S("Majister"));
    QApplication::setApplicationName(_S("jPos"));

    qRegisterMetaType<SyncState>("SyncState");

    // Имя файла логов
    logFileName.clear();

    // Настройки базы - SQLite
    QString mainBase = _S("db.sqlite3");
    QString dbDriver = _S("QSQLITE");
    QString dbUser;
    QString dbPass;
    QString dbOptions;
    QString executeModule;
    QString executeParams;


    QString styleFileName;
    bool stylefree = false;

    //  Уровни лога, 1- только ошибки, 2 - основные действия, 3 - отладка каждого чиха
    int  loglevel = 1;
    //  Обнулить файл логов
    bool newlog        = false;
    bool resetSettings = false;
    bool showHelp      = false;
    bool saveSources   = false;


    QStringList args = QCoreApplication::arguments();
    for (int i = 1; i < args.count(); ++i)
    {
        QString value = args.at(i);

        if (value == _S("--logfile") && i < args.count())
        {
            logFileName = args.at(++i);
            continue;
        }

        if (value == _S("--loglevel") && i < args.count())
        {
            loglevel = args.at(++i).toInt();
            continue;
        }

        if (value == _S("--newlog"))
        {
            newlog = true;
            continue;
        }

        if (value == _S("--driver") && i < args.count())
        {
            dbDriver = args.at(++i);
            continue;
        }
        if (value == _S("--user") && i < args.count())
        {
            dbUser = args.at(++i);
            continue;
        }
        if (value == _S("--password") && i < args.count())
        {
            dbPass = args.at(++i);
            continue;
        }
        if (value == _S("--resetsettings"))
        {
            resetSettings = true;
            continue;
        }
        if (value == _S("--stylefree"))
        {
            stylefree = true;
            continue;
        }
        if (value == _S("--istyle") && i < args.count())
        {
            styleFileName = args.at(++i);
            continue;
        }
        if (value == _S("--version"))
        {
            qDebug() << _T("jPOS версия от %1 %2").arg(BUILDDATE).arg(BUILDTIME);
            return 0;
        }
        if (value == _S("--help"))
        {
            showHelp = true;
            break; // all other params not matter
        }
        if (value == _S("--sources"))
        {
            saveSources = true;
            break; // all other params not matter
        }
        if (value == _S("--execute") && i+1 < args.count())
        {
            executeModule = args.at(++i);
            executeParams = args.at(++i);
            continue;
        }
        // если не параметров - значит название базы
        mainBase = value;
    }


    if (saveSources)
    {
        QFile   sourcesFile(_S(":/sources/sources/sources.7z"));
        if(!sourcesFile.open(QFile::ReadOnly))
        {
            qDebug() << _T("%1 Ошибка доступа к исходникам: %2")
                        .arg(posForLog)
                        .arg(sourcesFile.errorString());
            return 1;
        }

        QFile   resultFile(_S("sources.7z"));
        if(!resultFile.open(QFile::WriteOnly))
        {
            qDebug() << _T("%1 Ошибка создания файла для сохранения: %2")
                        .arg(posForLog)
                        .arg(resultFile.errorString());
            return 1;
        }

        resultFile.write(sourcesFile.readAll());
        resultFile.close();
        sourcesFile.close();

        qDebug()<<"Исходники сохранены в файле sources.7z";
        return 0;
    }

    if (showHelp)
    {
        QFile   helpFile(_S(":/texts/texts/help.txt"));
        helpFile.open(QFile::ReadOnly);
        QString helpText = helpFile.readAll();
        qDebug() << _T("jPOS версия от %1 %2").arg(BUILDDATE).arg(BUILDTIME)<<endl;
        qDebug() << helpText;
        return 0;
    }

    if (newlog)
    {
        QFile::remove(logFileName);
    }


    if (!logFileName.isEmpty())
        qInstallMessageHandler(fileMessageHandler);
    //else
    //    qInstallMessageHandler(outputMessageHandler);


    if(!stylefree)
    {
        QFile styleFile;
        if(!styleFileName.isEmpty())
            styleFile.setFileName(styleFileName);
        else
            styleFile.setFileName(":/qss/qss/black-n-orange.qss");

        styleFile.open(QFile::ReadOnly);
        QString styleSheet = QString::fromLatin1(styleFile.readAll());
        qApp->setStyleSheet(styleSheet);
    }

    Datapipe               * data = new Datapipe();
    QMap<QString, QVariant>* vars = data->getVariables();

    if (loglevel > 0)
        qDebug() << _T("%1 Уровень лога: %2").arg(posForLog).arg(loglevel);

    vars->insert(_S("loglevel"), loglevel);


    QSettings *settings = data->getSettings();
    if (resetSettings)
        settings->clear();

    QStringList settingsKeys = settings->allKeys();

    QSettings *defaults = new QSettings(_S(":/defaults/defaults/globalsettings.ini"), QSettings::IniFormat);
    defaults->setIniCodec(QTextCodec::codecForName("UTF-8"));

    QStringList defaultKeys = defaults->allKeys();

    for (int i = 0; i < defaultKeys.count(); i++)
    {
        QString  key   = defaultKeys.at(i);
        QVariant value = defaults->value(key);

        if (!settingsKeys.contains(key))
            settings->setValue(key, value);
    }
    delete defaults;

    QFont font;
    font.setFamily(settings->value("global/default_font","DejaVu Sans").toString());
    font.setPixelSize(settings->value("global/default_font_size",14).toInt());
    font.setBold(settings->value("global/defalut_font_bold",true).toBool());

    qApp->setFont(font);


    // Финт - зададим дефолты для некоторых баз
    if((dbDriver=="QIBASE" || dbDriver=="QFIREBIRD") && dbUser.isEmpty())
        dbUser="******";
    if((dbDriver=="QIBASE" || dbDriver=="QFIREBIRD") && dbPass.isEmpty())
        dbPass="******";


    QSqlDatabase db = QSqlDatabase::addDatabase(dbDriver);

    db.setDatabaseName(mainBase);
    db.setUserName(dbUser);
    db.setPassword(dbPass);
    db.setConnectOptions(dbOptions);

    if (!db.open())
    {
        qCritical()<<_T("%1 Ошибка подключения: %2").arg(posForLog).arg(db.lastError().text());
        return 2;
    }

    if (loglevel > 0)
    {
        qDebug() << _T("%1 База данных: %2").arg(posForLog).arg(mainBase);
        qDebug() << _T("%1 Драйвер: %2").arg(posForLog).arg(dbDriver);
        qDebug() << _T("%1 Пользователь: %2").arg(posForLog).arg(dbUser);
        qDebug() << _T("%1 Пароль: %2").arg(posForLog).arg(dbPass);
        qDebug() << _T("%1 Настройки: %2").arg(posForLog).arg(dbOptions);
    }
    vars->insert(_S("database"), mainBase);
    vars->insert(_S("database_driver"), dbDriver);
    vars->insert(_S("database_user"), dbUser);
    vars->insert(_S("database_password"), dbPass);
    vars->insert(_S("database_settings"), dbOptions);

    QSqlQuery query;


    query.prepare(settings->value(_S("global/queries/settings")).toString());
    if (query.exec())
    {
        while (query.next())
        {
            vars->insert(query.value(0).toString(), query.value(1));
            if(loglevel > 0)
                qDebug() << _T("%1 Переменные: %2 = %3").arg(posForLog).arg(query.value(0).toString()).arg(query.value(1).toString());
        }
    }
    else
    {
        bool solved = false;
        if(dbDriver=="QSQLITE")
        {
            QMessageBox::StandardButton reply;
            reply = QMessageBox::question(0,
                                          _T("Не обнаружена база данных"),
                                          _T("Не обнаружена база данных\nСоздать новую?"),
                                          QMessageBox::Yes|QMessageBox::No);

            if (reply == QMessageBox::Yes)
            {
                QFile file(":/defaults/defaults/database_sqlite.sql");
                if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
                {
                    qCritical() << _T("%1 Ошибка создания новой базы данных\n%2").arg(posForLog).arg(file.errorString());
                    return  0;
                }


                QStringList queryPartsList = QString::fromUtf8(file.readAll()).split(QRegExp("\\s"), QString::SkipEmptyParts);

                int triggerDepth=0;
                int stringDepth=0;
                bool skipOneBegin=false;
                QString queryFromParts;

                for(int i=0; i<queryPartsList.count();++i)
                {
                    QString part = queryPartsList.at(i).trimmed();

                    if(part.isEmpty())
                        continue;

                    if(part.toUpper() == "CREATE" && i+1 < queryPartsList.count())
                        if(queryPartsList.at(i+1)=="TRIGGER")
                        {
                            triggerDepth++;
                            skipOneBegin=true;
                        }


                    if(triggerDepth > 0 && part.toUpper()=="BEGIN")
                    {
                        if(skipOneBegin)
                            skipOneBegin=false;
                        else
                            triggerDepth++;
                    }
                    if(triggerDepth > 0 && part.toUpper()=="CASE")
                            triggerDepth++;

                    if(triggerDepth > 0 && part.toUpper().startsWith("END"))
                            triggerDepth--;

                    queryFromParts += _S(" %1").arg(part);

                    //qDebug()<<part<<triggerDepth<<stringDepth;

                    if(part.contains(";") && triggerDepth==0 && stringDepth==0)
                    {
                        bool skipQuery = false;
                        if(queryFromParts.contains("CREATE TABLE sqlite_sequence"))
                            skipQuery=true;

                        if(queryFromParts.trimmed().isEmpty())
                            skipQuery=true;

                        if(queryFromParts.trimmed()==";")
                            skipQuery=true;

                        if(!skipQuery)
                        {
                            if (!query.exec(queryFromParts))
                            {
                                qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                                return 1;
                            }
                           // qDebug()<<queryFromParts;
                        }
                        queryFromParts.clear();
                    }

                }

                QDialog dlg;
                QFormLayout layout;
                dlg.setLayout(&layout);

                QLineEdit posID;
                layout.addRow(_T("Код ПОС-а"), &posID);

                QLineEdit generatorMin;
                layout.addRow(_T("Генератор мин"), &generatorMin);

                QLineEdit generatorMax;
                layout.addRow(_T("Генератор макс"), &generatorMax);

                QPushButton bt;
                bt.setText("OK");
                layout.addRow(0, &bt);
                dlg.connect(&bt, SIGNAL(clicked()), &dlg, SLOT(accept()));

                if(dlg.exec()==QDialog::Accepted)
                {
                    query.prepare(settings->value(_S("global/queries/set_pos_id")).toString());
                    query.bindValue(":val", posID.text().toInt());
                    if(!query.exec())
                    {
                        qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                        return 1;
                    }
                    query.prepare(settings->value(_S("global/queries/set_generator_min")).toString());
                    query.bindValue(":val", generatorMin.text().toInt());
                    if(!query.exec())
                    {
                        qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                        return 1;
                    }

                    query.prepare(settings->value(_S("global/queries/set_generator_min1_sqlite")).toString());
                    query.bindValue(":val", generatorMin.text().toInt());
                    if(!query.exec())
                    {
                        qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                        return 1;
                    }

                    query.prepare(settings->value(_S("global/queries/set_generator_min2_sqlite")).toString());
                    query.bindValue(":val", generatorMin.text().toInt());
                    if(!query.exec())
                    {
                        qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                        return 1;
                    }

                    query.prepare(settings->value(_S("global/queries/set_generator_max")).toString());
                    query.bindValue(":val", generatorMax.text().toInt());
                    if(!query.exec())
                    {
                        qCritical() << _T("%1 Ошибка создания новой базы данных\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
                        return 1;
                    }

                }
                else
                {
                    QMessageBox message;
                    message.setText(_T("Создание новой базы данных отменено"));
                    message.exec();
                    return 1;
                }

               solved = true;
            }
        }

        if(!solved){
            qCritical() << _T("%1 Ошибка чтения настроек\n%2\n%3").arg(posForLog, query.lastError().text(), query.lastQuery());
            return 1;
        }
    }


    int width  = 0;
    int height = 0;

    if (QApplication::desktop()->screenGeometry().width() > QApplication::desktop()->screenGeometry().height())
    {
        width  = QApplication::desktop()->screenGeometry().width();
        height = QApplication::desktop()->screenGeometry().height();
    }
    else
    {
        width  = QApplication::desktop()->screenGeometry().height();
        height = QApplication::desktop()->screenGeometry().width();
    }


    double scale = settings->value("global/button_scale", 1).toDouble();



    vars->insert(_S("standart_button_width"), (int) width / 12 * scale);
    vars->insert(_S("standart_button_height"), (int) height / 12 * scale);
    vars->insert(_S("standart_text_height"), (int) height / 18 * scale);
    vars->insert(_S("standart_margins"), (int) vars->value(_S("standart_button_width")).toInt() * 0.1 * scale);

    // заполняем тут, чтобы не тянуть в плагины все файлы
    data->setPrinter(new ChequePrinter(data->getSettings(), data->getVariables()));


    if (loglevel > 0)
    {
        QStringList keys = settings->allKeys();
        for (int i = 0; i < keys.count(); i++)
            qDebug() << _T("%1 Настройки: %2 %3").arg(posForLog).arg(keys.at(i)).arg(settings->value(keys.at(i)).toString());
    }


    if (loglevel > 0)
        qDebug() << _T("%1 Запуск ").arg(posForLog);


    MainWindow window(data);
    window.showFullScreen();

    // проверка 3
    return a.exec();
}
Ejemplo n.º 11
0
MainWindow::MainWindow(char *urlx):iskeyboardshow(false)
{
    setWindowFlags(Qt::WindowStaysOnTopHint);
    this->showFullScreen();
//    this->setWindowFlags(Qt::WindowCloseButtonHint);
//    setWindowFlags(Qt::Tool | Qt::FramelessWindowHint);   // 隐藏标题栏己周围框架
//    this->setAttribute(Qt::WA_TranslucentBackground, true);        // 设置背景透明(version >= QT4.5)
//    this->setAttribute(Qt::WA_NoSystemBackground, true);
//    this->setAttribute(Qt::WA_NoBackground, true);
//    QPalette pal = palette();
//    pal.setColor(QPalette::Background, QColor(0x00,0x00,0x00,0x00));
//    this->setPalette(pal);
//    QMessageBox::warning(NULL,"MainWindow",QString("%1").arg((this->centralWidget() == 0)?"nil":"have"));
//    qApp->setStyleSheet("QMainWindow {background-image: url(:/images/111.png);}");

    frm = new QFrame();
    keyboardfrm = new mainForm;
    webView = new WebView(frm);
    pbExit = new QPushButton(frm);
    pbInput = new QPushButton(frm);

//    pbInput->setCheckable(true);

//    keyboardfrm->setAttribute(Qt::WA_TranslucentBackground, false);

    //webView->load(QUrl("http://10.6.14.60:8080/hipicd/cube/index.html"));
   // webView->load(QUrl("http://www.baidu.com"));

    if(NULL != urlx)
    {
        QString urlstr(urlx);

        if (-1 != urlstr.indexOf(QRegExp("[Ff][Ii][Ll][Ee]"),0))
        {
            qDebug() << "localfile: " << urlstr;
            webView->load(QUrl::fromLocalFile( urlstr));
        }
        else if (-1 == urlstr.indexOf(QRegExp("[Hh][Tt][Tt][Pp]"),0))
        {
            urlstr.prepend("http://");
        }


//        QMessageBox::warning(NULL, "error", urlstr);
        webView->load(QUrl(urlstr));
    }
    else
    {
        webView->load(QUrl("http://resource.hipidata.cn/web/s_index.html"));
    }


 
    webPage = webView->page();


//    webHistory = webPage->history();
    //webView->setD

//    urlAddr = new QLineEdit;
//    statusLabel = new QLabel;
//    progressBar = new QProgressBar;

    dockWidget = new QDockWidget();
    dockWidget->setFocusPolicy(Qt::NoFocus);
    dockWidget->setFocusProxy(0);
    dockWidget->setAllowedAreas(Qt::BottomDockWidgetArea);
    dockWidget->setFeatures(QDockWidget::DockWidgetClosable);
    this->setCorner(Qt::BottomLeftCorner, Qt::BottomDockWidgetArea);
//    dockWidget->setFloating(true);


	//ldockWidget = new QDockWidget();
	
	
	
    QFile file;
    file.setFileName(":/myjquery.js");
    file.open(QIODevice::ReadOnly);
    this->jQuery = file.readAll();
    file.close();


	//QMessageBox::about(this,jQuery,this->jQuery);
	//webPage->currentFrame()->evaluateJavaScript(jQuery);
	

//    createActions();
    //createMenus();
    //createToolBars();
    createCentralWidget();

//    createStatusBar();
    createKeyBoardDock();
//    createHeader();
   // createLeftDock();
    setKeyBoardDockShow(false);

    webPage->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);



    connect(dockWidget->toggleViewAction(), SIGNAL(toggled(bool)), this, SLOT(on_dockwidget_toggled(bool)));
    connect(pbInput, SIGNAL(clicked()), this, SLOT(on_pbInput_clicked()));
    connect(pbExit, SIGNAL(clicked()), this, SLOT(on_pbExit_clicked()));
    connect(webView, SIGNAL(linkClicked( const QUrl & )), this, SLOT(myOnLinkClicked( const QUrl & )) );
    connect(webPage, SIGNAL(microFocusChanged()),this, SLOT(myContentChanged()));
    connect(webView, SIGNAL(titleChanged(QString)), this, SLOT(showTitle(const QString &)));

//    connect(urlAddr, SIGNAL(returnPressed()), this, SLOT(loadUrlAddr()));
//    connect(webView, SIGNAL(urlChanged(const QUrl &)), this, SLOT(displayUrlAddr(const QUrl &)));

//    connect(webView, SIGNAL(linkClicked( const QUrl & )), this, SLOT(setKeyBoardDockShow(true)) );
//    connect(webView, SIGNAL(titleChanged(const QString &)), this, SLOT(showTitle(const QString &)));
//    connect(webView, SIGNAL(statusBarMessage(const QString &)),statusLabel, SLOT(setText(const QString &)));

//    connect(webView, SIGNAL(loadStarted()), this, SLOT(webLoadStarted()));

//    connect(webView, SIGNAL(loadProgress(int)), this, SLOT(webLoadProgress(int)));
//    connect(webView, SIGNAL(loadFinished(bool)), this, SLOT(webLoadFinished(bool)));
//    connect(webView, SIGNAL(loadFinished(bool)), this, SLOT(webPage->currentFrame()->evaluateJavaScript(jQuery)));
}
Ejemplo n.º 12
0
	void Syncer::ContinueLocalStorageChecking ()
	{
		if (Paths_.isEmpty ())
		{
			//TODO checking finished
			qDebug () << "finished";
			return;
		}

		QString path = Paths_.takeAt (0);
		QFileInfo info (path);
		DriveItem parentItem = RealPath2Item_.value (info.dir ().absolutePath ());

		bool found = false;
		DriveItem currentItem;
		for (const auto& item : Items_)
		{
			if (item.IsFolder_ != info.isDir () ||
					item.Name_ != info.fileName () ||
					item.Labels_ & DriveItem::ILRemoved ||
					item.ParentId_ != parentItem.Id_)
				continue;

			currentItem = item;
			found = true;
			Items_.removeOne (item);
			break;
		}

		if (found)
		{
			if (QFileInfo (path).exists ())
			{
				RealPath2Item_ [path] = currentItem;
				if (!info.isDir ())
				{
					QFile file (path);
					if (file.open (QIODevice::ReadOnly))
					{
						if (currentItem.Md5_ != QCryptographicHash::hash (file.readAll (), QCryptographicHash::Md5).toHex ())
						{
							//TODO update
							qDebug () << currentItem.Id_ << currentItem.Name_ << "need update";
						}
					}
				}
			}
			else
				DM_->MoveEntryToTrash (currentItem.Id_);
			ContinueLocalStorageChecking ();
		}
		else
		{
			connect (DM_,
					SIGNAL (gotNewItem (DriveItem)),
					this,
					SLOT (handleGotNewItem (DriveItem)));
			RealPathQueue_ << path;
			!info.isDir () ?
				DM_->Upload (path, QStringList () << parentItem.Id_) :
				DM_->CreateDirectory (info.fileName (), parentItem.Id_);
		}
	}
Ejemplo n.º 13
0
void PlasmoidHandler::createRequiredFiles(const QString &serviceType, const QString &pluginName,
                                         const QString &userName, const QString &userEmail, const QString &fileExtension)
{
    // a package may require a file like ui/main.qml
    // but the ui dir may not be required, so lets check for them
    for (const auto &it : package().requiredFiles()) {
        if (m_directoryDefinitions.values().contains(it)) {
            const QString dirName(m_directoryDefinitions.key(it));
            QDir dir(packagePath() + contentsPrefix());
            dir.mkpath(dirName);
            dir.cd(dirName);

            QFile f;
            const QString filePath = dir.path() + QLatin1Char('/') +
                                 m_fileDefinitions[it];
            QString templateFilePath;

            if (it == QLatin1String("mainscript")) {
                if (serviceType == "Plasma/Applet") {
                    templateFilePath.append("mainPlasmoid");
                } else if (serviceType == "KWin/WindowSwitcher") {
                    templateFilePath.append("mainTabbox");
                } else if (serviceType == "KWin/Script") {
                    templateFilePath.append("mainKWinScript");
                } else if (serviceType == "KWin/Effect") {
                    templateFilePath.append("mainKWinEffect");
                }
                f.setFileName(QStandardPaths::locate(QStandardPaths::DataLocation,
                                                 QStringLiteral("templates/") + templateFilePath + fileExtension));

                const bool ok = f.copy(filePath);
                if (!ok) {
                    emit error(QStringLiteral("The mainscript file hasn't been created"));
                }

                f.setFileName(filePath);
                f.open(QIODevice::ReadWrite);

                // Now open these files, and substitute the main class, author, email and date fields
                QByteArray tmpPluginName(pluginName.toLocal8Bit());
                QByteArray tmpAuthor(userName.toLocal8Bit());
                QByteArray tmpEmail(userEmail.toLocal8Bit());
                QByteArray rawData = f.readAll();
                f.close();
                f.open(QIODevice::WriteOnly);

                QByteArray replacedString("$PLASMOID_NAME");
                if (rawData.contains(replacedString)) {
                    rawData.replace(replacedString, tmpPluginName);
                }
                replacedString.clear();

                replacedString.append("$AUTHOR");
                if (rawData.contains(replacedString)) {
                    rawData.replace(replacedString, tmpAuthor);
                }
                replacedString.clear();

                replacedString.append("$EMAIL");
                if (rawData.contains(replacedString)) {
                    rawData.replace(replacedString, tmpEmail);
                }
                replacedString.clear();

                replacedString.append("$DATE");
                QDate date = QDate::currentDate();
                QByteArray datetime(date.toString().toUtf8());
                QTime time = QTime::currentTime();
                datetime.append(", " + time.toString().toUtf8());
                if (rawData.contains(replacedString)) {
                    rawData.replace(replacedString, datetime);
                }

                f.write(rawData);
                f.close();
            }
        }
    }

    loadPackage();
}
Ejemplo n.º 14
0
Application::Application(int &argc, char **argv) : QApplication(argc,argv)
{
	QTranslator *main_translator=nullptr, *plugin_translator=nullptr;
	QFile ui_style(GlobalAttributes::TMPL_CONFIGURATIONS_DIR +
				   GlobalAttributes::DIR_SEPARATOR +
				   GlobalAttributes::UI_STYLE_CONF +
				   GlobalAttributes::CONFIGURATION_EXT);
	QString plugin_name, plug_lang_dir, plug_lang_file;
	QStringList dir_list;
	QDir dir;

	//Creating the initial user's configuration
	createUserConfiguration();

	//Changing the current working dir to the executable's directory in
	QDir::setCurrent(this->applicationDirPath());

	//Adding paths which executable will find plugins and it's dependecies
	this->addLibraryPath(this->applicationDirPath());
	this->addLibraryPath(GlobalAttributes::PLUGINS_DIR);

	//Try to create plugins dir if it does not exists
	if(!dir.exists(GlobalAttributes::PLUGINS_DIR))
	{
		if(!dir.mkdir(GlobalAttributes::PLUGINS_DIR))
		{
			Messagebox msg;
			msg.show(Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(GlobalAttributes::PLUGINS_DIR),
							   ERR_FILE_DIR_NOT_WRITTEN,__PRETTY_FUNCTION__,__FILE__,__LINE__));
		}
	}

	//Check if the temporary dir exists, if not, creates it.
	if(!dir.exists(GlobalAttributes::TEMPORARY_DIR))
	{
		if(!dir.mkdir(GlobalAttributes::TEMPORARY_DIR))
		{
			Messagebox msg;
			msg.show(Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_WRITTEN).arg(GlobalAttributes::TEMPORARY_DIR),
							   ERR_FILE_DIR_NOT_WRITTEN, __PRETTY_FUNCTION__,__FILE__,__LINE__));
		}
	}

	//Trying to identify if the user defined a custom UI language in the pgmodeler.conf file
	QString conf_file =	GlobalAttributes::CONFIGURATIONS_DIR +
											GlobalAttributes::DIR_SEPARATOR +
											GlobalAttributes::GENERAL_CONF +
											GlobalAttributes::CONFIGURATION_EXT;
	QFile input;
	QString lang_id = QLocale::system().name();

	input.setFileName(conf_file);

	if(input.open(QFile::ReadOnly))
	{
		QString buf = QString(input.readAll());
		QRegExp regexp = QRegExp(QString("(%1)(.*)(=)(\\\")(.)+(\\\")(\\\n)").arg(ParsersAttributes::UI_LANGUAGE));
		int idx =	regexp.indexIn(QString(buf));

		//Extract the value of the ui-language attribute in the conf file
		lang_id = buf.mid(idx, regexp.matchedLength());
		lang_id.remove(ParsersAttributes::UI_LANGUAGE);
		lang_id.remove(QChar('"')).remove(QChar('=')).remove(QChar('\n'));
	}

	//Tries to load the main ui translation according to the system's locale
	main_translator=new QTranslator(this);
	main_translator->load(lang_id, GlobalAttributes::LANGUAGES_DIR);
	this->installTranslator(main_translator);

	//Trying to load plugins translations
	dir_list=QDir(GlobalAttributes::PLUGINS_DIR +
								GlobalAttributes::DIR_SEPARATOR,
								QString("*"), QDir::Name, QDir::AllDirs | QDir::NoDotAndDotDot).entryList();

	while(!dir_list.isEmpty())
	{
		plugin_name=dir_list.front();
		dir_list.pop_front();

		//Configure the path to "lang" subdir at current plugin directory
		plug_lang_dir=GlobalAttributes::PLUGINS_DIR +
					  GlobalAttributes::DIR_SEPARATOR + plugin_name +
					  GlobalAttributes::DIR_SEPARATOR + QString("lang") +
					  GlobalAttributes::DIR_SEPARATOR;

		plug_lang_file=plugin_name + QString(".") + lang_id;

		//Check if the .qm file exists for the current plugin. If so create and install a translator
		if(QFileInfo(plug_lang_dir + plug_lang_file + QString(".qm")).exists())
		{
			plugin_translator=new QTranslator(this);
			plugin_translator->load(plug_lang_file, plug_lang_dir);
			this->installTranslator(plugin_translator);
		}
	}

	//Loading app style sheet
	ui_style.open(QFile::ReadOnly);

	//Raises an error if ui style is not found
	if(!ui_style.isOpen())
	{
		Messagebox msg;
		msg.show(Exception(Exception::getErrorMessage(ERR_FILE_DIR_NOT_ACCESSED).arg(ui_style.fileName()),
						   ERR_FILE_DIR_NOT_ACCESSED,__PRETTY_FUNCTION__,__FILE__,__LINE__));
	}
	else
		this->setStyleSheet(ui_style.readAll());
}
Ejemplo n.º 15
0
void MyWindow::initShaders()
{
    QOpenGLShader vShader(QOpenGLShader::Vertex);
    QOpenGLShader fShader(QOpenGLShader::Fragment);    
    QFile         shaderFile;
    QByteArray    shaderSource;

    // Shader color
    shaderFile.setFileName(":/vshader_col.txt");
    shaderFile.open(QIODevice::ReadOnly);
    shaderSource = shaderFile.readAll();
    shaderFile.close();
    qDebug() << "vertex \"color\" compile: " << vShader.compileSourceCode(shaderSource);

    shaderFile.setFileName(":/fshader_col.txt");
    shaderFile.open(QIODevice::ReadOnly);
    shaderSource = shaderFile.readAll();
    shaderFile.close();
    qDebug() << "frag   \"color\" compile: " << fShader.compileSourceCode(shaderSource);

    mProgramCol = new (QOpenGLShaderProgram);
    mProgramCol->addShader(&vShader);
    mProgramCol->addShader(&fShader);
    qDebug() << "shader \"color\" link: " << mProgramCol->link();

    // Shader normal
    shaderFile.setFileName(":/vshader_norm.txt");
    shaderFile.open(QIODevice::ReadOnly);
    shaderSource = shaderFile.readAll();
    shaderFile.close();
    qDebug() << "vertex \"normal\" compile: " << vShader.compileSourceCode(shaderSource);

    shaderFile.setFileName(":/fshader_norm.txt");
    shaderFile.open(QIODevice::ReadOnly);
    shaderSource = shaderFile.readAll();
    shaderFile.close();
    qDebug() << "frag   \"normal\" compile: " << fShader.compileSourceCode(shaderSource);

    mProgramNorm = new (QOpenGLShaderProgram);
    mProgramNorm->addShader(&vShader);
    mProgramNorm->addShader(&fShader);
    qDebug() << "shader \"normal\" link: " << mProgramNorm->link();

    // Shader texture
    shaderFile.setFileName(":/vshader_tex.txt");
    shaderFile.open(QIODevice::ReadOnly);
    shaderSource = shaderFile.readAll();
    shaderFile.close();
    qDebug() << "vertex \"texture\" compile: " << vShader.compileSourceCode(shaderSource);

    shaderFile.setFileName(":/fshader_tex.txt");
    shaderFile.open(QIODevice::ReadOnly);
    shaderSource = shaderFile.readAll();
    shaderFile.close();
    qDebug() << "frag   \"texture\" compile: " << fShader.compileSourceCode(shaderSource);

    mProgramTex = new (QOpenGLShaderProgram);
    mProgramTex->addShader(&vShader);
    mProgramTex->addShader(&fShader);
    qDebug() << "shader \"texture\" link: " << mProgramTex->link();
}
Ejemplo n.º 16
0
int main(int argc, char **argv)
{
    QCoreApplication application(argc, argv);
    application.setOrganizationName("CutePaste");
    application.setApplicationName("CutePaste Desktop Console Frontend");

    QTextStream standardOutputStream(stdout);
    QFile dataFile;
    QString firstArgument = QCoreApplication::arguments().size() < 2 ? QString() : QCoreApplication::arguments().at(1);
    if (!firstArgument.isEmpty()) {
        dataFile.setFileName(firstArgument);
        dataFile.open(QIODevice::ReadOnly);
    } else {
        dataFile.open(stdin, QIODevice::ReadOnly);
    }

    QByteArray pasteTextByteArray = dataFile.readAll();

    QJsonObject requestJsonObject;
    requestJsonObject.insert(QStringLiteral("data"), QString::fromUtf8(pasteTextByteArray));
    requestJsonObject.insert(QStringLiteral("language"), QStringLiteral("text"));

    QJsonDocument requestJsonDocument(requestJsonObject);

    QString baseUrlString = QStringLiteral("http://pastebin.kde.org");

    QNetworkRequest networkRequest;
    networkRequest.setAttribute(QNetworkRequest::DoNotBufferUploadDataAttribute, true);
    networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    networkRequest.setUrl(QUrl(baseUrlString + "/api/json/create"));

    QNetworkAccessManager networkAccessManager;
    QScopedPointer<QNetworkReply> networkReplyScopedPointer(networkAccessManager.post(networkRequest, requestJsonDocument.toJson()));
    QObject::connect(networkReplyScopedPointer.data(), &QNetworkReply::finished, [&]() {

        QJsonParseError jsonParseError;
        QByteArray replyJsonByteArray = networkReplyScopedPointer->readAll();
        QJsonDocument replyJsonDocument = QJsonDocument::fromJson(replyJsonByteArray, &jsonParseError);
        if (jsonParseError.error != QJsonParseError::NoError) {
            qDebug() << "The json network reply is not valid json:" << jsonParseError.errorString();
            QCoreApplication::quit();
        }

        if (!replyJsonDocument.isObject()) {
            qDebug() << "The json network reply is not an object";
            QCoreApplication::quit();
        }
        
        QJsonObject replyJsonObject = replyJsonDocument.object();
        QJsonValue resultValue = replyJsonObject.value(QStringLiteral("result"));

        if (!resultValue.isObject()) {
            qDebug() << "The json network reply does not contain an object for the \"result\" key";
            QCoreApplication::quit();
        }

        QJsonValue identifierValue = resultValue.toObject().value(QStringLiteral("id"));

        if (!identifierValue.isString()) {
            qDebug() << "The json network reply does not contain a string for the \"id\" key";
            QCoreApplication::quit();
        }

        endl(standardOutputStream << baseUrlString << '/' << identifierValue.toString());

        QCoreApplication::quit();
    });

    QObject::connect(networkReplyScopedPointer.data(), static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), [&](QNetworkReply::NetworkError networkReplyError) {
        if (networkReplyError != QNetworkReply::NoError)
            endl(standardOutputStream << networkReplyScopedPointer->errorString());
    });

    QObject::connect(networkReplyScopedPointer.data(), &QNetworkReply::sslErrors, [&](QList<QSslError> networkReplySslErrors) {
        if (!networkReplySslErrors.isEmpty()) {
            foreach (const QSslError &networkReplySslError, networkReplySslErrors)
                endl(standardOutputStream << networkReplySslError.errorString());
        }
    });
Ejemplo n.º 17
0
void ImportConfig::on_cmdImport_clicked()
{
    if (!m_ui->txtExistingOvpn->text().isEmpty()) {
        // Import existing file
        QString configName (m_ui->txtExistingOvpn->text().replace(".ovpn", ""));
        configName = configName.right(configName.size() - configName.lastIndexOf("/") - 1);

        // Anderer name als Dateiname
        if (m_ui->rbSaveAsName->isChecked()) {
            if (!m_ui->txtNewName->text().isEmpty()) {
                configName = m_ui->txtNewName->text();
            }
        }

        QString pathToConfig (m_ui->txtExistingOvpn->text());
        // Copy config to local app data and rename it, if an other name is specified
        // Only in service mode!
        if(!Settings::getInstance()->getIsPortableClient()) {

            // If file is available copy it
            // First create folder
            QString newConfigFolderPath (QString("%1/config/%2")
                                         .arg(AppFunc::getAppSavePath())
                                         .arg(configName));
            QDir newConfigFolderPathDirectory (newConfigFolderPath);
            if (newConfigFolderPathDirectory.exists(newConfigFolderPath)){
                // A config with this name is already existing
                Message::error(QObject::tr("A configuration with this name is already existing!"));
                //
                return;
            }

            // Create path
            newConfigFolderPathDirectory.mkpath(newConfigFolderPath);

            // Now copy Files
            QString newConfigPath (QString("%1/%2.ovpn")
                                   .arg(newConfigFolderPath)
                                   .arg(configName));

            QFile::copy(pathToConfig, newConfigPath);
            //
            QString sourceDirectory (pathToConfig.left(pathToConfig.lastIndexOf("/")));
            //
            // Override old path
            pathToConfig = newConfigPath;
            // Ca

			auto copyConfigFile = [&](const QString &key)
			{
				auto keyValue = (ConfigValues::instance()->valueFromConfigKey(pathToConfig, key));

				if(!keyValue.isEmpty())
				{
					QString sourcePath (QString("%1/%2")
						.arg(sourceDirectory)
						.arg(keyValue));

					QString destName (keyValue);

					if (ConfigValues::instance()->isGivenPathAbsolute(keyValue)) {
						// Yes, override path
						sourcePath = keyValue;
						// Get the file name from path
						destName = ConfigValues::instance()->fileNameOfAbsolutePath(keyValue);
						// Change value in config
						ConfigValues::instance()->changeKeyValueInConfig(pathToConfig, key, QString("\"%1\"")
							.arg(destName));
					}
					// Copy
					QFile::copy(sourcePath, QString("%1/%2")
						.arg(newConfigFolderPath)
						.arg(destName));
				}
			};

			for(const auto &key : keys)
			{
				copyConfigFile(key);
			}
        }

        Preferences::instance()->addNewConfigToDatabase(configName, pathToConfig);
        Preferences::instance()->refreshConfigList();
        Preferences::instance()->setConnectionStatus();
        Preferences::instance()->setIcon();

        // Fertig
        Message::information(QObject::tr("Import successfully ended!"), QObject::tr("Import Configuration"));
        Preferences::instance()->refreshDialog();
        this->close();
    } else {
        // Import crypt file
        if (m_ui->txtPassword->text().isEmpty()) {
            Message::error(QObject::tr("No password specified!"), QObject::tr("Import Configuration"));
            return;
        }
        if (!m_ui->txtImportPath->text().isEmpty()) {
            if (m_ui->rbSaveAsName->isChecked() && m_ui->txtNewName->text().isEmpty()) {
                Message::error(QObject::tr("No import name specified!"), QObject::tr("Import Configuration"));
                return;
            }

            // Portale oder install
            QString dirPath;
            QString configName;

            if (!m_ui->rbSaveAsName->isChecked()) {
                configName = m_ui->txtImportPath->text().right(m_ui->txtImportPath->text().size() - m_ui->txtImportPath->text().lastIndexOf("/") -1);
                configName = configName.left(configName.size()-6);
            } else {
                configName = m_ui->txtNewName->text().trimmed();
            }

            dirPath = AppFunc::getAppSavePath() + QString ("/config/") + configName;

            // Verzeichnis da?
            QDir dirobj (dirPath);
            if (!dirobj.exists(dirPath)){
                //Verzeichnis existiert nicht
                // Pfad erstellen
                if (!dirobj.mkpath(dirPath)) {
                    // Pfad konnte nicht erstellt werden
                    Message::error(QObject::tr("Unable to create directory!"), QObject::tr("Import Configuration"));
                    return;
                }
            } else {
                // Verzeichnis existiert
                Message::error(QObject::tr("A diretory with this name already exists!"), QObject::tr("Import Configuration"));
                return;
            }
            // Datei ins neue Verzeichnis kopieren
            //QFile importFileCrypt (m_ui->txtImportPath->text());
            QString packFile = dirPath + QString("/") + configName + QString(".zip");

            // Erstmal entschlüsseln
            if(QFile::exists(packFile)) {
                QFile::remove(packFile);
            }

            // Die Daten einlesen
            {
                QFile crypted (m_ui->txtImportPath->text());
                if (crypted.open(QIODevice::ReadOnly)) {
                    // Nun das Ziel öfffnen
                    QFile targetFile (packFile);
                    if (targetFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
                        // Alles offen, kann losgehen
                        QByteArray data = crypted.readAll();
                        Crypt crypt;
                        crypt.setSecretKey(m_ui->txtPassword->text());
                        targetFile.write(crypt.cryptToPlainTextExt(data));
                        targetFile.waitForBytesWritten(3000);
                        targetFile.flush();
                        targetFile.waitForBytesWritten(3000);

                        // Alles Ok
                        targetFile.close();
                        crypted.close();
                    }
                } else {
                    Message::error(QObject::tr("Can't open crypted file"));
                    return;
                }
            }

            // Nun die Datei entpacken
            if (!Zip::extract(packFile, dirPath)) {
                Message::error(QObject::tr("Can't open zip file"));
                return;
            }

            // Nun ist alles entpackt, das Ziparchiv nun löschen
            QFile configZip (packFile);
            if (!configZip.remove()) {
                Message::error(configZip.errorString(), QObject::tr("Import Configuration"));
            }

            QString saveName;
            QString savePath;
            QString ovpnFilePath = m_ui->txtImportPath->text().right(m_ui->txtImportPath->text().size() - m_ui->txtImportPath->text().lastIndexOf("/") -1);

            saveName = ovpnFilePath.left(ovpnFilePath.size()-6);
            savePath = dirPath + QString("/") + ovpnFilePath.left(ovpnFilePath.size()-6) + QString(".ovpn");

            if (m_ui->rbSaveAsName->isChecked()) {
                // ovpn umbennen
                QFile ovpnFile (savePath);
                if (ovpnFile.exists()) {
                    // umbenennen
                    ovpnFile.rename(dirPath + QString("/") + configName + QString(".ovpn"));
                    saveName = configName;
                }
            }
            savePath = dirPath + QString("/") + saveName + QString(".ovpn");

            QFile ovpnFile (dirPath + QString("/") + configName + QString(".ovpn"));
            if (!ovpnFile.exists()) {
                Message::error(QObject::tr("Import failed! Removing empty directory."), QObject::tr("Import Configuration"));
                dirobj.rmdir(dirPath);
            } else {
                Preferences::instance()->addNewConfigToDatabase(saveName, savePath.replace("\\", "/"));
                Preferences::instance()->refreshConfigList();
                Preferences::instance()->setConnectionStatus();
                Message::information(QObject::tr("Import successfully ended!"), QObject::tr("Import Configuration"));
                Preferences::instance()->refreshDialog();
                Preferences::instance()->setIcon();
                this->close();
            }
        } else {
            Message::error(QObject::tr("No import file selected!"), QObject::tr("Import Configuration"));
        }
    }
}
Ejemplo n.º 18
0
void XmlSettingsDialog::RegisterObject (QObject* obj, const QString& basename)
{
	Basename_ = QFileInfo (basename).baseName ();
	WorkingObject_ = obj;
	QString filename;
	if (QFile::exists (basename))
		filename = basename;
	else if (QFile::exists (QString (":/") + basename))
		filename = QString (":/") + basename;
#ifdef Q_WS_WIN
	else if (QFile::exists (QString ("settings/") + basename))
		filename = QString ("settings/") + basename;
#elif defined (Q_WS_MAC)
	else if (QFile::exists (QApplication::applicationDirPath () +
			"/../Resources/settings/" + basename))
		filename = QApplication::applicationDirPath () +
				"/../Resources/settings/" + basename;
#else
	else if (QFile::exists (QString ("/usr/local/share/leechcraft/settings/") + basename))
		filename = QString ("/usr/local/share/leechcraft/settings/") + basename;
	else if (QFile::exists (QString ("/usr/share/leechcraft/settings/") + basename))
		filename = QString ("/usr/share/leechcraft/settings/") + basename;
#endif
	QFile file (filename);
	if (!file.open (QIODevice::ReadOnly))
	{
		qWarning () << "cannot open file"
			<< filename
			<< basename;
		return;
	}
	QByteArray data = file.readAll ();
	file.close ();

	QString emsg;
	int eline;
	int ecol;
	if (!Document_->setContent (data, &emsg, &eline, &ecol))
	{
		qWarning () << "Could not parse file, line"
			<< eline
			<< "; column"
			<< ecol
			<< emsg;
		return;
	}
	QDomElement root = Document_->documentElement ();
	if (root.tagName () != "settings")
	{
		qWarning () << "Bad settings file";
		return;
	}

	QDomElement declaration = root.firstChildElement ("declare");
	while (!declaration.isNull ())
	{
		HandleDeclaration (declaration);
		declaration = declaration.nextSiblingElement ("declare");
	}

	QDomElement pageChild = root.firstChildElement ("page");
	while (!pageChild.isNull ())
	{
		ParsePage (pageChild);
		pageChild = pageChild.nextSiblingElement ("page");
	}

	obj->installEventFilter (this);

	UpdateXml (true);
}
void DeviceMetaData::parse_meta_data_file(QString file_name) {
    device_types.clear();

    QFile file;

	if ((file_name == "") || (QFile::exists(file_name) == false)) {
		Utility::thread_call(MainWindow::mw, [file_name] {
			QMessageBox::warning(MainWindow::mw, "Can't open measurement equipment meta data file",
								 "Can't open measurement equipment meta data file: " + file_name);
        });
        return;
    }
    file.setFileName(file_name);

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
		Utility::thread_call(MainWindow::mw, [file_name] {
			QMessageBox::warning(MainWindow::mw, "Can't open measurement equipment meta data file",
								 "Can't open measurement equipment meta data file: " + file_name);
        });
        return;
    }
    QString json_string = file.readAll();
    file.close();
    QJsonDocument j_doc = QJsonDocument::fromJson(json_string.toUtf8());
    if (j_doc.isNull()) {
		Utility::thread_call(MainWindow::mw, [file_name] {
            QMessageBox::warning(MainWindow::mw, "measurement equipment meta data parse error",
                                 "could not parse measurement equipment meta data file: " + file_name);
        });
        return;
    }
    QJsonObject j_obj = j_doc.object();
    QJsonArray js_device_types = j_obj["device_types"].toArray();
    QStringList device_names;
    for (QJsonValue js_device_type : js_device_types) {
        DeviceMetaDataGroup device_type{};

        QJsonObject obj = js_device_type.toObject();
        QString proto_type = obj["protocol"].toString().trimmed();
        // device_type.isEmpty = false;
        device_type.commondata.device_name = obj["device_name"].toString();
        if (device_names.contains(device_type.commondata.device_name.toLower() + proto_type.toLower())) {
            QMessageBox::critical(nullptr, "Device meta data error",
								  QString("The device meta data table contains more than one device-group with the equal name \"%1\". This is not allowed. "
                                          "You can use the \"devices\" array to insert more devices of the same type.")
                                      .arg(device_type.commondata.device_name));
            throw; //
            //should not contain more than one device with the same name
        }
        device_names.append(device_type.commondata.device_name.toLower() + proto_type.toLower());
        device_type.commondata.manufacturer = obj["manufacturer"].toString();
        device_type.commondata.description = obj["description"].toString();
        device_type.commondata.manual_path = obj["manual_path"].toString();

        if (proto_type.toLower() == "scpi") {
            device_type.commondata.protocol_type = ProtocolType::SCPI;
        } else if (proto_type.toLower() == "manual") {
            device_type.commondata.protocol_type = ProtocolType::Manual;
        } else {
            //TODO: put error here
            assert(0);
        }

        QJsonArray js_devices = obj["devices"].toArray();
        QStringList serial_numbers;
        for (QJsonValue js_device : js_devices) {
            DeviceMetaDataDetail device{};
            const QString DATE_FORMAT = "yyyy.M.d"; // 1985.5.25
            QJsonObject obj = js_device.toObject();
            device.serial_number = obj["serial_number"].toString();
            if (serial_numbers.contains(device.serial_number.toLower())) {
				QMessageBox::critical(nullptr, "Device meta data error", QString("The device meta data table contains more than one device with the equal name "
																				 "\"%1\" and the equal serialnumber \"%2\". This is not allowed.")
																			 .arg(device_type.commondata.device_name)
																			 .arg(device.serial_number));
                throw; //
                //should not contain more than one device with the same name
            }
            serial_numbers.append((device.serial_number.toLower()));
            QString tmp = obj["expery_date"].toString();

            device.expery_date = QDate::fromString(tmp, DATE_FORMAT);
            tmp = obj["purchase_date"].toString();
            device.purchase_date = QDate::fromString(tmp, DATE_FORMAT);
            device.valid = true;
            device.locked = false;

            QString locked_str = obj["locked"].toString();
            if (locked_str == "yes") {
                device.locked = true;
            }
            if (locked_str == "true") {
                device.locked = true;
            }
            int locked_num = obj["locked"].toInt();
            if (locked_num) {
                device.locked = true;
            }
            device.note = obj["note"].toString();
            device.calibration_certificate_path = obj["calibration_certificate_path"].toString();
            device_type.devices.append(device);
        }
        device_types.append(device_type);
    }
}
Ejemplo n.º 20
0
static QStringList _split( QFile& f )
{
	return utility::split( f.readAll() ) ;
}
Ejemplo n.º 21
0
void TestAusmt::checkDoubleApplied()
{
    GET_DIR;
    GET_VAR_DIR;
    GET_FILES_DIR;

    // Check files
    QFile fileSimple (filesDir.absoluteFilePath("simple.qml"));
    QFile patchedSimple (":/patched/simple-patch1.qml");
    QVERIFY(fileSimple.open(QIODevice::ReadOnly));
    QVERIFY(patchedSimple .open(QIODevice::ReadOnly));
    QCOMPARE(fileSimple.readAll(), patchedSimple .readAll());
    fileSimple.close();
    patchedSimple.close();
    QFile fileOther (filesDir.absoluteFilePath("other.qml"));
    QFile patchedOther (":/patched/other-patch.qml");
    QVERIFY(fileOther.open(QIODevice::ReadOnly));
    QVERIFY(patchedOther .open(QIODevice::ReadOnly));
    QCOMPARE(fileOther.readAll(), patchedOther .readAll());
    fileOther.close();
    patchedOther.close();

    // Check orig
    QVERIFY(QFile::exists(filesDir.absoluteFilePath("simple.qml.webosinternals.orig")));
    QVERIFY(QFile::exists(filesDir.absoluteFilePath("other.qml.webosinternals.orig")));

    // Check metadata
    QFile packages (varDir.absoluteFilePath("packages"));
    QVERIFY(packages.open(QIODevice::ReadOnly));
    QList<QByteArray> allLines = packages.readAll().trimmed().split('\n');
    packages.close();
    QCOMPARE(allLines.count(), 1);
    QCOMPARE(allLines.first(), QByteArray("double-patch ausmt-sailfishos-1"));

    QFile fileControl (varDir.absoluteFilePath("control/file_control"));
    QVERIFY(fileControl.open(QIODevice::ReadOnly));
    allLines = fileControl.readAll().trimmed().split('\n');
    fileControl.close();
    QCOMPARE(allLines.count(), 2);
    QList<QByteArray> allEntries = allLines.at(0).split(' ');
    QCOMPARE(allEntries.count(), 3);
    QCOMPARE(allEntries.at(0), QByteArray("test"));
    QCOMPARE(allEntries.at(1), filesDir.absoluteFilePath("other.qml").toLocal8Bit());
    allEntries = allLines.at(1).split(' ');
    QCOMPARE(allEntries.count(), 3);
    QCOMPARE(allEntries.at(0), QByteArray("test"));
    QCOMPARE(allEntries.at(1), filesDir.absoluteFilePath("simple.qml").toLocal8Bit());

    QFile fileMd5sums (varDir.absoluteFilePath("control/file_md5sums"));
    QVERIFY(fileMd5sums.open(QIODevice::ReadOnly));
    allLines = fileMd5sums.readAll().trimmed().split('\n');
    fileMd5sums.close();
    QCOMPARE(allLines.count(), 2);
    allEntries = allLines.at(0).split(' ');
    QCOMPARE(allEntries.count(), 3);
    QCOMPARE(allEntries.at(0), QByteArray("double-patch"));
    QCOMPARE(allEntries.at(1), filesDir.absoluteFilePath("other.qml").toLocal8Bit());
    QCOMPARE(allEntries.at(2), QByteArray("805bec6be121a2ac7198f2f82b2395d9"));
    allEntries = allLines.at(1).split(' ');
    QCOMPARE(allEntries.count(), 3);
    QCOMPARE(allEntries.at(0), QByteArray("double-patch"));
    QCOMPARE(allEntries.at(1), filesDir.absoluteFilePath("simple.qml").toLocal8Bit());
    QCOMPARE(allEntries.at(2), QByteArray("62a1d5ed1773a6a8dec1f5d0be3de388"));
}
Ejemplo n.º 22
0
volumeMiniPropertiesTaskResult zuluMountTask::volumeMiniProperties( const QString& volume )
{
	auto _loopDeviceIsGone =[]( const QString& device ){

		QDir d( "/sys/block" ) ;
		QStringList l = d.entryList() ;
		QString e ;
		QString dev = QString( "%1\n" ).arg( device ) ;
		QByteArray s ;
		QFile f ;

		for( const auto& it : l ){

			if( it.startsWith( "loop" ) ){

				e = QString( "/sys/block/%1/loop/backing_file" ).arg( it ) ;

				f.setFileName( e ) ;

				if( f.open( QIODevice::ReadOnly ) ){

					s = f.readAll() ;

					f.close() ;
				}

				if( s == dev ){

					return false ;
				}
			}
		}
		return true ;
	} ;

	volumeMiniPropertiesTaskResult s{ volume,false,nullptr } ;

	if( !volume.startsWith( "UUID" ) && !volume.startsWith( "/dev/" ) ){

		/*
		 * There is some sort of a race condition here and things do not always work as expected
		 * try to sleep for a second to see if it will help
		 */

		utility::Task::waitForOneSecond() ;

		if( _loopDeviceIsGone( volume ) ){

			/*
			 * we were just asked to find properties of a loop device
			 * that no longer exists,remove it from the list in the GUI window
			 */

			s.volumeRemoved = true ;
			return s ;
		}
	}

	auto r = utility::Task( utility::appendUserUID( "%1 -L -d \"%2\"" ).arg( zuluMountPath,volume ) ) ;

	if( r.success() ){

		s.entry = new volumeEntryProperties( r.splitOutput( '\t' ),_volumeIsSystemVolume( volume ) ) ;
	}

	return s ;
}
Ejemplo n.º 23
0
void ConfigProject::configQtPro(QString proname)
{
    QFile file;
    QTextStream stream;
    QString textcontent;
    QString filename=proname;
    QFileInfo fileinfo(filename);

    file.setFileName(filename);
    if(!file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        return;
    }
    textcontent=file.readAll();
    file.close();
    if(textcontent.contains("TEMPLATE = subdirs"))
    {
        return;
    }
    if(!textcontent.contains(QString("PROJNAME = %1").arg(fileinfo.baseName())))
    {
        textcontent=textcontent+QString("\nPROJNAME = %1").arg(fileinfo.baseName());
    }
    if(ui.Library->isChecked())
    {
        if(!textcontent.contains("INSTALLTYPE = MOD"))
        {
            textcontent=textcontent+QString("\nINSTALLTYPE = MOD");
        }
        if(textcontent.contains("INSTALLTYPE = APP"))
        {
            textcontent.remove(QString("\nINSTALLTYPE = APP"));
        }
        if(textcontent.contains("INSTALLTYPE = SDK"))
        {
            textcontent.remove(QString("\nINSTALLTYPE = SDK"));
        }
    }
    else if(ui.Application->isChecked())
    {
        if(!textcontent.contains("INSTALLTYPE = APP"))
        {
            textcontent=textcontent+QString("\nINSTALLTYPE = APP");
        }
        if(textcontent.contains("INSTALLTYPE = MOD"))
        {
            textcontent.remove(QString("\nINSTALLTYPE = MOD"));
        }
        if(textcontent.contains("INSTALLTYPE = SDK"))
        {
            textcontent.remove(QString("\nINSTALLTYPE = SDK"));
        }
    }
    if(!textcontent.contains("include(RobotSDK_Main.pri)"))
    {
        textcontent=textcontent+QString("\ninclude(RobotSDK_Main.pri)");
    }
    file.open(QIODevice::WriteOnly|QIODevice::Text);
    stream.setDevice(&file);
    stream<<textcontent;
    file.close();

    file.setFileName(QString("%1/RobotSDK_Main.pri").arg(ROBOTSDKTOOLS));
    if(!file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        return;
    }
    textcontent=file.readAll();
    file.close();
    file.setFileName(QString("%1/RobotSDK_Main.pri").arg(fileinfo.absolutePath()));
    file.open(QIODevice::WriteOnly|QIODevice::Text);
    stream.setDevice(&file);
    stream<<textcontent;
    file.close();

    file.setFileName(QString("%1/RobotSDK_Install.pri").arg(ROBOTSDKTOOLS));
    if(!file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        return;
    }
    textcontent=file.readAll();
    file.close();
    file.setFileName(QString("%1/RobotSDK_Install.pri").arg(fileinfo.absolutePath()));
    file.open(QIODevice::WriteOnly|QIODevice::Text);
    stream.setDevice(&file);
    stream<<textcontent;
    file.close();
    return;
}
Ejemplo n.º 24
0
// ---------------------------------------------------
// 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.remove(Collect.begin());
    if(Line == "*") {  // worked on all components ?
      startSimulator(); // <<<<<================== go on ===
      return;
    }
    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;

  QStringList com;
  com << (QucsSettings.BinDir + "qucsconv");
  if(makeSubcircuit)
    com << "-g" << "_ref";
  com << "-if" << "spice" << "-of" << "qucs";
  SimProcess.setArguments(com);

  QFile SpiceFile;
  if(FileName.find(QDir::separator()) < 0)  // add path ?
    SpiceFile.setName(QucsWorkDir.path() + QDir::separator() + FileName);
  else
    SpiceFile.setName(FileName);
  if(!SpiceFile.open(IO_ReadOnly)) {
    ErrText->insert(tr("ERROR: Cannot open SPICE file \"%1\".").arg(FileName));
    FinishSimulation(-1);
    return;
  }


  if(makeSubcircuit) {
    Stream << "\n.Def:" << properName(FileName) << " ";
  
    Line.replace(',', ' ');
    Stream << Line;
    if(!Line.isEmpty()) Stream << " _ref";
  }
  Stream << "\n";


  ProgressText = "";
  if(!SimProcess.start()) {
    ErrText->insert(tr("ERROR: Cannot start QucsConv!"));
    FinishSimulation(-1);
    return;
  }

  QByteArray SpiceContent = SpiceFile.readAll();
  SpiceFile.close();
  SimProcess.writeToStdin(SpiceContent);
  connect(&SimProcess, SIGNAL(wroteToStdin()), SLOT(slotCloseStdin()));
}
Ejemplo n.º 25
0
Archivo: main.cpp Proyecto: xjohncz/qt5
QT_USE_NAMESPACE

int main(int argc, char *argv[])
{
    QCoreApplication coreApplication(argc, argv);
    int argumentCount = QCoreApplication::arguments().size();
    QStringList argumentList = QCoreApplication::arguments();

    QTextStream standardOutput(stdout);

    if (argumentCount == 1) {
        standardOutput << QObject::tr("Usage: %1 <serialportname> [baudrate]").arg(argumentList.first()) << endl;
        return 1;
    }

    QSerialPort serialPort;
    QString serialPortName = argumentList.at(1);
    serialPort.setPortName(serialPortName);

    if (!serialPort.open(QIODevice::WriteOnly)) {
        standardOutput << QObject::tr("Failed to open port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
        return 1;
    }

    int serialPortBaudRate = (argumentCount > 2) ? argumentList.at(2).toInt() : QSerialPort::Baud9600;
    if (!serialPort.setBaudRate(serialPortBaudRate)) {
        standardOutput << QObject::tr("Failed to set 9600 baud for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
        return 1;
    }

    if (!serialPort.setDataBits(QSerialPort::Data8)) {
        standardOutput << QObject::tr("Failed to set 8 data bits for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
        return 1;
    }

    if (!serialPort.setParity(QSerialPort::NoParity)) {
        standardOutput << QObject::tr("Failed to set no parity for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
        return 1;
    }

    if (!serialPort.setStopBits(QSerialPort::OneStop)) {
        standardOutput << QObject::tr("Failed to set 1 stop bit for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
        return 1;
    }

    if (!serialPort.setFlowControl(QSerialPort::NoFlowControl)) {
        standardOutput << QObject::tr("Failed to set no flow control for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
        return 1;
    }

    QFile dataFile;
    if (!dataFile.open(stdin, QIODevice::ReadOnly)) {
        standardOutput << QObject::tr("Failed to open stdin for reading") << endl;
        return 1;
    }

    QByteArray writeData(dataFile.readAll());
    dataFile.close();

    if (writeData.isEmpty()) {
        standardOutput << QObject::tr("Either no data was currently available on the standard input for reading, or an error occurred for port %1, error: %2").arg(serialPortName).arg(serialPort.errorString()) << endl;
        return 1;
    }

    SerialPortWriter serialPortWriter(&serialPort);
    serialPortWriter.write(writeData);

    return coreApplication.exec();
}
Ejemplo n.º 26
0
Config::Config()
{
	int i = 0;
	xmppwinFound = false;
	connectionFound = false;
	otherFound = false;
	noConfig = false;
	QByteArray config;
	//Loads last configuration from ~/.Kapture/conf.xml
	QDir *confDir = new QDir(QDir::homePath() + "/.Kapture/");
	if (!confDir->exists())
	{
		QDir::home().mkdir(".Kapture");
	}
	confDir->setPath(QDir::homePath() + "/.Kapture/");
	
	if (!confDir->exists())
	{
		noConfig = true;
		QMessageBox::critical(0, QString("Jabber"), QString("Unable to create config file. Check permissions for\n \"$HOME/.Kapture/conf.xml\""), QMessageBox::Ok);
		return;
	}
	
	QFile *conf = new QFile(QDir::homePath() + "/.Kapture/conf.xml");
	conf->open(QIODevice::ReadOnly);
	config = conf->readAll();
	d.setContent(config);

	if (d.documentElement().tagName() != "Kapture")
	{
		noConfig = true;
		return;
	}

	classes = d.documentElement().childNodes();
	for(i = 0; i < classes.count() ;i++)
	{
		if (classes.at(i).toElement().tagName() == "xmppwin")
		{
			xmppwinFound = true;
			xmppwinN = i;
		}

		if (classes.at(i).toElement().tagName() == "connection")
		{
			connectionFound = true;
			connectionN = i;
		}

		if (classes.at(i).toElement().tagName() == "other")
		{
			otherFound = true;
			otherN = i;
		}
	}

	// Loading xmppwin class data.
	if (xmppwinFound)
	{
		QDomNodeList profilesNodeList = classes.at(xmppwinN).childNodes();
		for (int j = 0; j < profilesNodeList.count(); j++)
		{
			cJid = Jid("");
			cPassword = "";
			cPersonnalServer = "";
			cPort = "5222";
			cProfile = profilesNodeList.at(j).toElement().attribute("name");
			QDomNodeList infos = profilesNodeList.at(j).childNodes();
			for (i = 0; i < infos.count(); i++)
			{
				if (infos.at(i).toElement().tagName() == "jid" && infos.at(i).hasChildNodes())
					cJid = Jid(infos.at(i).firstChild().toText().data());
	
				if (infos.at(i).toElement().tagName() == "password" && infos.at(i).hasChildNodes())
					cPassword = QByteArray::fromBase64(infos.at(i).firstChild().toText().data().toLatin1());
	
				if (infos.at(i).toElement().tagName() == "server" && infos.at(i).hasChildNodes())
					cPersonnalServer = infos.at(i).firstChild().toText().data();
	
				if (infos.at(i).toElement().tagName() == "port" && infos.at(i).hasChildNodes())
					cPort = infos.at(i).firstChild().toText().data();
			}
			Profile *profile = new Profile(cProfile);
			profile->setData(cJid, cPassword, cPersonnalServer, cPort);
			profiles << *profile;
		}
	}

	// Loading connection class data
	if (connectionFound)
	{
		QDomNodeList connectionNodeList = classes.at(connectionN).childNodes();
		for (int i = 0; i < connectionNodeList.count(); i++)
		{
			// File Transfer Port
			if (connectionNodeList.at(i).localName() == "ftport")
				cFTPort = connectionNodeList.at(i).toElement().attribute("val", "8010");
			// Proxy
			if (connectionNodeList.at(i).localName() == "proxy")
				cProxy = connectionNodeList.at(i).toElement().attribute("val", "");
			// Resource
			if (connectionNodeList.at(i).localName() == "resource")
				cResource = connectionNodeList.at(i).toElement().attribute("val", "Kapture");
		}
	}
	else
	{
		// Default Values
		cFTPort = "8010";
		cProxy = "";
		cResource = "Kapture";
	}

	// Loading Other class data
	if (otherFound)
	{
		QDomNodeList otherNodeList = classes.at(otherN).childNodes();
		for (int i = 0; i < otherNodeList.count(); i++)
		{
			if (otherNodeList.at(i).localName() == "systray")
				cUseSysTray = otherNodeList.at(i).toElement().attribute("val", "true") == "true" ? true : false;
		}
	}
	else
	{
		// Default Values.
		cUseSysTray = true;
	}
	/* TODO:
	 * 	Should create an initial config if there's none at all.
	 */
}
Ejemplo n.º 27
0
/* Create an SGS or SWS to associate with a simulation
 */
QString Gridifier::makeSteeringService(const QString &factory,
				       const LauncherConfig &config){
  QString result;

#ifndef REG_WSRF

  QProcess *makeSimSGSProcess = new QProcess(QString("./make_sgs.pl"));
  makeSimSGSProcess->setWorkingDirectory(mScriptsDir);
  makeSimSGSProcess->addArgument(factory);
  // the tag is handled correctly if it contains spaces - thanks QT!
  makeSimSGSProcess->addArgument(config.mJobData->toXML(QString("SGS")));
  makeSimSGSProcess->addArgument(config.topLevelRegistryGSH);
  makeSimSGSProcess->addArgument(config.currentCheckpointGSH);
  makeSimSGSProcess->addArgument(config.mInputFileName);
  makeSimSGSProcess->addArgument(QString::number(config.mTimeToRun));
  if (config.treeTag.length() > 0){
    makeSimSGSProcess->addArgument(config.treeTag);
    makeSimSGSProcess->addArgument(config.checkPointTreeFactoryGSH);
  }
  makeSimSGSProcess->start();

  while(makeSimSGSProcess->isRunning()){
    usleep(10000);
    mApplication->processEvents();
  }

  // Grab the sgs and return it
  // Do some error checking here - or in the calling class?
  result = QString(makeSimSGSProcess->readStdout()).stripWhiteSpace();

#else // REG_WSRF is defined

  struct reg_job_details   job;
  char                    *chkTree;

  // Initialize job_details struct
  snprintf(job.userName, REG_MAX_STRING_LENGTH,
	   config.mJobData->mPersonLaunching.ascii());
  snprintf(job.group, REG_MAX_STRING_LENGTH, "RSS");
  snprintf(job.software, REG_MAX_STRING_LENGTH, 
	   config.mJobData->mSoftwareDescription.ascii());
  snprintf(job.purpose, REG_MAX_STRING_LENGTH,
	   config.mJobData->mPurposeOfJob.ascii());
  snprintf(job.inputFilename, REG_MAX_STRING_LENGTH,
	   config.mInputFileName.ascii());
  job.lifetimeMinutes = config.mTimeToRun;
  snprintf(job.passphrase, REG_MAX_STRING_LENGTH,
	   config.mServicePassword.ascii());

  // Create a new checkpoint tree if requested
  if(config.treeTag.length()){
    chkTree = Create_checkpoint_tree(config.checkPointTreeFactoryGSH.ascii(), 
				     config.treeTag.ascii());
    if(!chkTree){
      QMessageBox::critical( NULL, "Checkpoint tree error",
                             "Failed to create new checkpoint tree.\n\n",
                             QMessageBox::Ok, 0, 0 );
      return result;
    }
  }
  else{
    chkTree = (char *)(config.currentCheckpointGSH.ascii());
  }
  snprintf(job.checkpointAddress, REG_MAX_STRING_LENGTH, chkTree);

  char *EPR = Create_steering_service(&job,
				      factory.ascii(), 
				      config.topLevelRegistryGSH.ascii(),
                                      &(config.registrySecurity));
  result = QString(EPR);

  struct soap mySoap;
  soap_init(&mySoap);

  // Put contents of input deck (if any) into the RP doc of the SWS
  if( EPR && !(config.mInputFileName.isEmpty()) ){

    QFile *inputFile = new QFile(config.mInputFileName);
    inputFile->open( IO_ReadOnly );
    QByteArray fileData = inputFile->readAll();
    inputFile->close();
    QString fileRP("<inputFileContent><![CDATA[");
    fileRP.append(fileData.data());
    fileRP.append("]]></inputFileContent>");
    if(Set_resource_property(&mySoap, EPR, job.userName, 
			     job.passphrase, 
			     (char *)(fileRP.ascii()) ) != REG_SUCCESS){
      cout << "Gridifier::makeSteeringService: WARNING - failed to store "
	"job input file on SWS." << endl;
    }
  }

  if(EPR && config.mIOProxyPort){

    QString resourceProp("<dataSink><Proxy><address>");
    resourceProp.append(config.mIOProxyAddress);
    resourceProp.append("</address><port>");
    resourceProp.append(QString::number(config.mIOProxyPort, 10));
    resourceProp.append("</port></Proxy></dataSink>");
     
    //cout << "Gridifier::makeSteeringService: Calling Set_resource_property "
    //  "with >>" << resourceProp << "<<" << endl;

    if(Set_resource_property(&mySoap, EPR,
			     job.userName,
			     job.passphrase,
			     (char *)(resourceProp.ascii())) != REG_SUCCESS){
      cout << "Gridifier::makeSteeringService: WARNING - failed to set "
	"details of ioProxy on the SWS" << endl;
    }
  }

  soap_end(&mySoap);
  soap_done(&mySoap);

  if(EPR){
    cout << "Address of SWS = " << EPR << endl;
  }
  else{
    cout << "FAILED to create SWS :-(" << endl;
  }

#endif // ndef REG_WSRF

  return result;
}
Ejemplo n.º 28
0
void ZHttpServer::readFile(QUrl url, QTcpSocket *socket) const
{
    QFileInfo fileInfo(sysroot + url.path());

    do{
        if(!fileInfo.absoluteFilePath().contains(sysroot)){
            socket->write(messagePackage("", "text/html",  HttpInfo::UnauthorizedAccessError, "Unauthorized Access"));
            break;
        }

        QFile file;

        if(fileInfo.isFile()){
            file.setFileName(fileInfo.absoluteFilePath());
        }else if(fileInfo.isDir()){
            QSettings setting(fileInfo.absoluteFilePath().append("/.ini"), QSettings::IniFormat);
            QString jump = setting.value("jump").toString();

            if(jump.isEmpty()){
                file.setFileName(fileInfo.absoluteFilePath().append(setting.value("default", "default.html").toString()));
            }else{
                QDir dir(fileInfo.absoluteFilePath());

                if(dir.cd(jump)){
                    url.setPath(dir.absolutePath().replace(sysroot, ""));
                    socket->write(getJumpPackage(url.toString().toUtf8()));
                    break;
                }else{
                    socket->write(messagePackage("", "text/Html", HttpInfo::UnknowError, QString("Jump to %1 failed").arg(jump)));
                    break;
                }
            }
        }

        qWarning() << "Open file:" << file.fileName();

        if(!file.exists()){
            socket->write(messagePackage("", "text/html",  HttpInfo::FileNotFoundError, "File Not Found"));
            break;
        }

        if(file.open(QIODevice::ReadOnly)){
            fileInfo.setFile(file.fileName());

            if(fileInfo.suffix() == "html" || fileInfo.suffix() == "xml") {
                socket->write(messagePackage(file.readAll(), "text/Html"));
            } else {
                socket->write(messagePackage(file.read(64), "text/plain;charset=utf-8", HttpInfo::NoError, QString(), file.size()));

                QPointer<QTcpSocket> socket_pointer = socket;
                qint64 send_buffer_size = socket->socketOption(QTcpSocket::SendBufferSizeSocketOption).toLongLong();

                send_buffer_size = qMin(send_buffer_size, qint64(16384));

                while (!file.atEnd() && socket_pointer && socket->state() == QTcpSocket::ConnectedState) {
                    socket->write(file.read(send_buffer_size));
                    socket->waitForBytesWritten(500);

                    qApp->processEvents();
                }
            }
        }else{
            qWarning() << "Open file failed:" << file.fileName() << "error:" << file.errorString();
            socket->write(messagePackage("", "text/html", HttpInfo::OtherError, file.errorString()));
        }
    }while(false);
}
Ejemplo n.º 29
0
MainWindow::MainWindow(OCContext* context, QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QStorageInfo storage(qApp->applicationDirPath());
    qDebug() << storage.rootPath();
    if (storage.isReadOnly())
        qDebug() << "isReadOnly:" << storage.isReadOnly();

    qDebug() << "name:" << storage.name();
    qDebug() << "fileSystemType:" << storage.fileSystemType();
    qDebug() << "size:" << storage.bytesTotal()/1000/1000 << "MB";
    qDebug() << "availableSize:" << storage.bytesAvailable()/1000/1000 << "MB";



    QList<QStorageInfo> drives = QStorageInfo::mountedVolumes();

    for(auto& drive : drives)
    {
       qDebug() << drive.rootPath();
       if (drive.isReadOnly())
           qDebug() << "isReadOnly:" << drive.isReadOnly();

       qDebug() << "name:" << drive.name();
       qDebug() << "fileSystemType:" << drive.fileSystemType();
       qDebug() << "size:" << drive.bytesTotal()/1000/1000 << "MB";
       qDebug() << "availableSize:" << drive.bytesAvailable()/1000/1000 << "MB";
    }
    _context = context;

    MediaExplorerPresenter* mediaExplorerPresenter = new MediaExplorerPresenter(_context);
    PlaybackPresenter* playbackPresenter = new PlaybackPresenter(_context);

    //Add preview pane
    //ui->gridLayout_3->addWidget(new PreviewPane(playbackPresenter));

    //Set Media Explorer widget
    //ui->dockWidget_3->setWidget(new MediaExplorerView(mediaExplorerPresenter));

    //QGridLayout* layout = new QGridLayout();
    //layout->addWidget(new PlaybackSlider(playbackPresenter)), ui->widget->setLayout(layout);

    stdout = freopen("output_file", "w", stdout);

    QFile f;
    f.open(stderr, QIODevice::ReadOnly);
    QByteArray output = f.readAll();
    QString out(output);

    /*ui->label_2->setText(out);
    ui->textBrowser->setText(out);

    ui->textBrowser->append("TEST\n");
    ui->textBrowser->append("12345\n");
*/
    BackupPresenter* backupPresenter = new BackupPresenter(context);
    ui->stackedWidget->addWidget(new BackupLayout(this, *backupPresenter));

    ui->stackedWidget->addWidget(new ClipProcessorLayout());

    //ui->buttonGroup->addButton(new QPushButton("Test", this));

    connect(ui->buttonGroup, SIGNAL(buttonClicked(int)), SLOT(on_pushButton_7_clicked(int)));

    /*QMenu* importMenu = new QMenu();
    QAction* testAction = new QAction("test menu item", this);
    connect(testAction,SIGNAL(triggered()), SLOT(SelectImportFolder()));
    importMenu->addAction(testAction);*/
}
Ejemplo n.º 30
0
int main(int argc, char **argv)
{
#if 0
  for(option_t opt : options)
  {
    qDebug() << "is_long      :" << opt.is_long;
    qDebug() << "flag_name    :" << QByteArray(opt.flag_name.data    , opt.flag_name.length);
    qDebug() << "value_name   :" << QByteArray(opt.value_name.data   , opt.value_name.length);
    qDebug() << "value_pattern:" << QByteArray(opt.value_pattern.data, opt.value_pattern.length);
    qDebug() << "description  :" << QByteArray(opt.description.data  , opt.description.length);
    qDebug() << "";
  }
  return 0;

#elif 0
  lua_State* L = luaL_newstate();
  luaL_openlibs(L);
  const char* script_string =
      "\nlocal p = {}"
      "\n  function p.render_embedded(args)"
      "\n    local rval = \"embedded<br>start<br>\""
      "\n    for index, value in ipairs(args) do"
      "\n      rval = rval .. \"i:\" .. tostring(index) .. \" - \""
      "\n      rval = rval .. \"v:\" .. value .. \"<br>\""
      "\n    end"
      "\n    rval = rval .. \"end\""
      "\n    return rval"
      "\n  end"
      "\nreturn p";

  const char* funcname_string = "render_embedded";

  if(luaL_dostring(L, script_string))
  {
    printf("error: %s\n", lua_tostring(L, -1));
    return -1;
  }

  int idx = lua_gettop(L);

  lua_getfield(L, idx, funcname_string);

  lua_newtable(L);

  lua_pushunsigned(L, 1);
  lua_pushstring(L, "one");
  lua_settable(L, -3);

  lua_pushunsigned(L, 2);
  lua_pushstring(L, "two");
  lua_settable(L, -3);

  lua_pushunsigned(L, 3);
  lua_pushstring(L, "three");
  lua_settable(L, -3);

  lua_pushunsigned(L, 4);
  lua_pushstring(L, "four");
  lua_settable(L, -3);

  if(lua_pcall(L, 1, 1, 0))
  {
    printf("error: %s\n", lua_tostring(L, -1));
    return -1;
  };

  printf("returned type: %i\n", lua_type(L, -1));

  if(!lua_isstring(L, -1))
  {
    printf("bad type\n");
    return -1;
  }

  printf("returned value: %s\n", lua_tostring(L, -1));

  lua_close(L);

  return 0;


#elif 1
  QResource::registerResource("resources.qrc");;

  CHttpDaemon service("QtWiki Service", "A Wiki engine written in Qt/C++", KIWI_PORT, argc, argv);

  QtServiceController controller("QtWiki Service");

  if(controller.isRunning())
  {
    qDebug("\nALREADY ACTIVE!\r\n");
    return 0;
  }

  service.logMessage("\nstarting QtWiki Service\r\n", CHttpDaemon::Information);

  return service.exec();
#elif 0

  const char data[] = "{ {{ }}}";

  CCharStream stream;
  stream.setData(data, sizeof(data));

  int depth = 0, start = 0, end = 0;

  ++stream;
  ++stream;

  qDebug() << "found:" << find_match<open_curlybracket, close_curlybracket>(stream, depth, start, end);
  qDebug() << "depth:" << (int)depth;
  qDebug() << "start:" << start;
  qDebug() << "end  :" << end;

  return 0;
#elif 0
  auto results = QueryThread::fastQuery("SELECT img_timestamp, img_name, img_width, img_height FROM image ORDER BY img_name");
  for(auto pos = results.begin(); pos != results.end(); ++pos)
  {
    auto row = *pos;
//    if(row[1] != "TurboGrafx-16-Service-Manual.pdf")
      continue;
    qDebug() << row[1];
    QFile file ("/home/gravis/images/" + row[1].toString());
    file.open(QIODevice::ReadOnly);
    Q_ASSERT(file.isOpen());
    QueryThread::fastQuery("INSERT INTO image_data (img_timestamp, img_name, img_width, img_height, img_data) VALUES (?,?,?,?,?)",
                            row[0], row[1], row[2], row[3], file.readAll());
  }
  return 0;
#endif
}