Ejemplo n.º 1
0
void messageHandler(QtMsgType type, const QMessageLogContext &ctx, const QString &msg)
{
    QMutexLocker locker(&m_mutex);

    QString out = QDateTime::currentDateTime().time().toString("hh:mm:ss:zzz") + " ";
    switch (type) {
    case QtDebugMsg:
        out.append("Debug: " + msg);
        cout << out.toStdString() << endl;
        break;
    case QtWarningMsg:
        out.append("Warning: " + msg);
        cerr << out.toStdString() << endl;
        break;
    case QtCriticalMsg:
        out.append("Critical: " + msg);
        cerr << out.toStdString() << endl;
        break;
    case QtFatalMsg:
        cerr << "Fatal: " << msg.toStdString() << endl;
        cerr.flush();

        m_logStream << "Fatal: " << msg << endl;
        m_logStream.flush();

        QApplication::exit(LightpackApplication::QFatalMessageHandler_ErrorCode);
    }

    m_logStream << out << endl;
    m_logStream.flush();
    cerr.flush();
    cout.flush();
}
Ejemplo n.º 2
0
/**
Редактировать атрибуты шрифта.
*/
void font::menu_Parametr ( void )
{
	int rez  = 0;
	int above = 0;
	int below = 0;
	int modes = 0;

	QString  attribute;

	do
	{
		print();
//  edit_menu::s_menu_font_parametr->run();
//  rez = edit_menu::s_menu_font_parametr->get_run_rez();

		switch ( rez )
		{

			case 0: //Above
				std_out << "Above (n>=1) <" << get_above () << "> =";
				std_out.flush();
				std_in >> above ;
				set_above ( above );
				break;

			case 1: //Below
				std_out << "Below (n>=1) <" << get_below() << "> =";
				std_out.flush();
				std_in >> below;
				set_below ( below );
				break;

			case 2: //Modes
				std_out << "Modes (0|2) <" << get_modes() << "> =";
				std_out.flush();
				std_in >> modes;
				set_modes ( modes );
				break;

			case 3: //Attribute
				std_out << "Attribute <" << get_attribute() << "> =";
				std_out.flush();
				attribute = std_in.readLine();
//    std_in >> attribute;
				set_attribute ( attribute );
				break;

			case 4: //Exit
				break;

			default:
				rez = 4;
				break;
		}
	}

	while ( rez >= 0 && rez < 4 );
}
Ejemplo n.º 3
0
    void print(const std::string & log)
    {
        QMutexLocker locker(&_lock);

        assert(_file);
        for (int i = 0; i < _beginsCount; ++i) {
            _stream->operator <<("    ");
        }
        QString str( log.c_str() );
        for (int i = 0; i < str.size(); ++i) {
            _stream->operator <<( str.at(i).toAscii() );
            if ( (i % 80 == 0) && (i != 0) ) { // format to 80 columns
                /*Find closest word end and insert a new line*/
                ++i;
                while ( i < str.size() && str.at(i) != QChar(' ') ) {
                    _stream->operator <<( str.at(i).toAscii() );
                    ++i;
                }
                _stream->operator <<('\n');
                for (int i = 0; i < _beginsCount; ++i) {
                    _stream->operator <<("    ");
                }
            }
        }
        _stream->operator <<( log.c_str() );
        _stream->operator <<('\n');
        _stream->flush();
    }
Ejemplo n.º 4
0
void Ledger::writeCsv(QTextStream &stream)
{
    int i, j;
    QString field;
    for( i=0; i<rowCount(); i++ ){
        if( i==rowCount()-1 && isEmptyRow(i) )
            break;
        for( j=0; j<NCOL; j++ ){
            if( !item(i,j) || item(i,j)->data(Qt::EditRole).isNull() )
                field = "";
            else if( j==COL_DATE )
                field = item(i,j)->data(Qt::EditRole).toDate().toString(Qt::ISODate);
            else if( j==COL_PRICE )
                field.setNum(item(i,j)->data(Qt::EditRole).toDouble(),'f',2);
            else{
                field = item(i,j)->data(Qt::EditRole).toString();
                if( field.contains( QRegularExpression("[\",\n]") ) ){
                    field.replace("\"", "\"\"");
                    field.prepend(QChar('\"'));
                    field.append(QChar('\"'));
                }
            }
            stream << field;
            if(j==NCOL-1) stream << '\n';
            else stream << ',';
        }
    }
    stream.flush();
    undoStack->setClean();
}
Ejemplo n.º 5
0
void MinimalHistoryEditor::saveCall(QTextStream& stream, const Call* call)
{
   const QString direction = (call->direction()==Call::Direction::INCOMING)?
      Call::HistoryStateName::INCOMING : Call::HistoryStateName::OUTGOING;

   const Account* a = call->account();
   stream << QString("%1=%2\n").arg(Call::HistoryMapFields::CALLID          ).arg(call->historyId()                     );
   stream << QString("%1=%2\n").arg(Call::HistoryMapFields::TIMESTAMP_START ).arg(call->startTimeStamp()         );
   stream << QString("%1=%2\n").arg(Call::HistoryMapFields::TIMESTAMP_STOP  ).arg(call->stopTimeStamp()          );
   stream << QString("%1=%2\n").arg(Call::HistoryMapFields::ACCOUNT_ID      ).arg(a?QString(a->id()):""          );
   stream << QString("%1=%2\n").arg(Call::HistoryMapFields::DISPLAY_NAME    ).arg(call->peerName()               );
   stream << QString("%1=%2\n").arg(Call::HistoryMapFields::PEER_NUMBER     ).arg(call->peerContactMethod()->uri() );
   stream << QString("%1=%2\n").arg(Call::HistoryMapFields::DIRECTION       ).arg(direction                      );
   stream << QString("%1=%2\n").arg(Call::HistoryMapFields::MISSED          ).arg(call->isMissed()               );
   stream << QString("%1=%2\n").arg(Call::HistoryMapFields::RECORDING_PATH  ).arg(call->recordingPath()          );
   stream << QString("%1=%2\n").arg(Call::HistoryMapFields::CONTACT_USED    ).arg(false                          );//TODO
   if (call->peerContactMethod()->contact()) {
      stream << QString("%1=%2\n").arg(Call::HistoryMapFields::CONTACT_UID  ).arg(
         QString(call->peerContactMethod()->contact()->uid())
      );
   }
   if (call->certificate())
      stream << QString("%1=%2\n").arg(Call::HistoryMapFields::CERT_PATH).arg(call->certificate()->path().path());
   stream << "\n";
   stream.flush();
}
void generateDcfSubSections( QString indent, QTextStream& out, const DcfSection& sect )
{
    QList<DcfSection>::const_iterator ss = sect.subsections.constBegin();
    while ( ss != sect.subsections.constEnd() ) {
	out << indent << "<section ref=\"" << HtmlGenerator::cleanRef(HtmlGenerator::protect((*ss).ref))
            << "\" title=\"" << HtmlGenerator::protect((*ss).title) << "\"";
	if ((*ss).keywords.isEmpty() && (*ss).subsections.isEmpty()) {
	    out << "/>\n";
	} else {
	    out << ">\n";
	    QString indentIndent = indent + "    ";
	    QList<QPair<QString, QString> >::const_iterator k = (*ss).keywords.constBegin();
	    while ( k != (*ss).keywords.constEnd() ) {
		out << indentIndent << "<keyword ref=\"" << HtmlGenerator::cleanRef((*k).second) << "\">"
                    << HtmlGenerator::protect((*k).first) << "</keyword>\n";
		++k;
	    }

            generateDcfSubSections( indentIndent, out, *ss );
	    out << indent << "</section>\n";
	}
	++ss;
    }
    out.flush();
}
Ejemplo n.º 7
0
void myMessageOutput(QtMsgType type, const char *msg)
{
     //in this function, you can write the message to any stream!
    stream << QString(msg);
    stream << QString("\n");
    stream.flush();
}
Ejemplo n.º 8
0
void ImageHistogram<T>::toAscii( QTextStream& out ) const {
    const QString LINE_END( "\n");
    QString centerStr( "#Bin Center(");
    casa::Unit unit = ImageHistogram::m_image->units();
    QString unitStr( unit.getName().c_str());
    centerStr.append( unitStr + ")");
    out << centerStr << "Count";
    out << LINE_END;
    out.flush();
    int count = m_xValues.size();
    for ( int i = 0; i < count; i++ ) {
        out << QString::number(m_xValues[i]) << QString::number( m_yValues[i]);
        out << LINE_END;
        out.flush();
    }
}
void Docbook2XhtmlGeneratorJob::run()
{
  UMLDoc* umlDoc = UMLApp::app()->document();
  xsltStylesheetPtr cur = NULL;
  xmlDocPtr doc, res;

  const char *params[16 + 1];
  int nbparams = 0;
  params[nbparams] = NULL;

  umlDoc->writeToStatusBar(i18n("Exporting to XHTML..."));

  QString xsltFileName(KGlobal::dirs()->findResource("appdata", QLatin1String("docbook2xhtml.xsl")));
  uDebug() << "XSLT file is'" << xsltFileName << "'";
  QFile xsltFile(xsltFileName);
  xsltFile.open(QIODevice::ReadOnly);
  QString xslt = QString::fromLatin1(xsltFile.readAll());
  uDebug() << "XSLT is'" << xslt << "'";
  xsltFile.close();

  QString localXsl = KGlobal::dirs()->findResource("data", QLatin1String("ksgmltools2/docbook/xsl/html/docbook.xsl"));
  uDebug() << "Local xsl is'" << localXsl << "'";
  if (!localXsl.isEmpty())
  {
    localXsl = QLatin1String("href=\"file://") + localXsl + QLatin1String("\"");
    xslt.replace(QRegExp(QLatin1String("href=\"http://[^\"]*\"")), localXsl);
  }
  KTemporaryFile tmpXsl;
  tmpXsl.setAutoRemove(false);
  tmpXsl.open();
  QTextStream str (&tmpXsl);
  str << xslt;
  str.flush();

  xmlSubstituteEntitiesDefault(1);
  xmlLoadExtDtdDefaultValue = 1;
  uDebug() << "Parsing stylesheet " << tmpXsl.fileName();
  cur = xsltParseStylesheetFile((const xmlChar *)tmpXsl.fileName().toLatin1().constData());
  uDebug() << "Parsing file " << m_docbookUrl.path();
  doc = xmlParseFile((const char*)(m_docbookUrl.path().toUtf8()));
  uDebug() << "Applying stylesheet ";
  res = xsltApplyStylesheet(cur, doc, params);

  KTemporaryFile tmpXhtml;
  tmpXhtml.setAutoRemove(false);
  tmpXhtml.open();

  uDebug() << "Writing HTML result to temp file: " << tmpXhtml.fileName();
  xsltSaveResultToFd(tmpXhtml.handle(), res, cur);

  xsltFreeStylesheet(cur);
  xmlFreeDoc(res);
  xmlFreeDoc(doc);

  xsltCleanupGlobals();
  xmlCleanupParser();

  emit xhtmlGenerated(tmpXhtml.fileName());
}
Ejemplo n.º 10
0
void ScriptHelper::writeEOS(QTextStream& script) {
	script
			<< endl
			<< "@@@"
			<< endl;

	// ensure everything is written to the stream
	script.flush();
}
Ejemplo n.º 11
0
void font::menu_Ascii ( void )
{
	int rez  = 0;
	QString  str;
	ushort  rez_ushort;
	QString   fileName;

	do
	{
		switch ( rez )
		{

			case 1: //ASCII
				std_out << "ASCII:";
				std_out.flush();
				std_in >> str;

				if ( str.length() >=  1 )
				{
					rez_ushort = str[0].unicode () ;
//     number = rez_ushort;
				}

				break;

			case 2: //Attribute
				std_out << "Enter Attribute:";
				std_out.flush();
				std_in >> str;
				m_comment = str;
				break;

			case 3: //Restore
				m_comment = QString ( "Nothing" );
//    number = -1;
				break;

			default:
				break;
		}
	}

	while ( rez >= 0 );
}
Ejemplo n.º 12
0
bool plotsDialog::saveChanges()
{
#ifdef Q_OS_WIN32
    QFile ofile(globalpara.caseName),file("plotTemp.xml");
#endif
#ifdef Q_OS_MAC
    QDir dir = qApp->applicationDirPath();
    /*dir.cdUp();*/
    /*dir.cdUp();*/
    /*dir.cdUp();*/
    QString bundleDir(dir.absolutePath());
    QFile ofile(globalpara.caseName),file(bundleDir+"/plotTemp.xml");
#endif
    QDomDocument odoc,doc;
    QDomElement oroot;
    QTextStream stream;
    stream.setDevice(&ofile);
    if(!ofile.open(QIODevice::ReadWrite|QIODevice::Text))
    {
        globalpara.reportError("Fail to open case file to update plot data.",this);
        return false;
    }
    else if(!odoc.setContent(&ofile))
    {
        globalpara.reportError("Fail to load xml document from case file to update plot data.",this);
        return false;
    }
    if(!file.open(QIODevice::ReadOnly|QIODevice::Text))
    {
        globalpara.reportError("Fail to open plot temp file to update plot data.",this);
        return false;
    }
    else if(!doc.setContent(&file))
    {
        globalpara.reportError("Fail to load xml document from plot temp file to update plot data..",this);
        return false;
    }
    else
    {
        QDomElement plotData = doc.elementsByTagName("plotData").at(0).toElement();
        QDomNode copiedPlot = plotData.cloneNode(true);
        oroot = odoc.elementsByTagName("root").at(0).toElement();
        oroot.replaceChild(copiedPlot,odoc.elementsByTagName("plotData").at(0));

        ofile.resize(0);
        odoc.save(stream,4);
        file.close();
        ofile.close();
        stream.flush();
        return true;
    }
}
Ejemplo n.º 13
0
bool FormattedTouchstone::Write(FormattedNetworkData &network, QTextStream &FormattedTouchstone_out) {
    WriteComments(network, FormattedTouchstone_out);
    WriteOptions(network, FormattedTouchstone_out);
    if (network.numberOfPorts() != 2)
        WriteData(network, FormattedTouchstone_out);
    else {
        FormattedNetworkData copyNetwork = network;
        Flip2Ports(copyNetwork);
        WriteData(copyNetwork, FormattedTouchstone_out);
    }
    FormattedTouchstone_out.flush();
    return(true);
}
Ejemplo n.º 14
0
void plotsDialog::on_copyButton_clicked()
{
    QString pName = tabs->tabText(tabs->currentIndex());
    QString newName = pName+"Copy";
#ifdef Q_OS_WIN32
    QFile file("plotTemp.xml");
#endif
#ifdef Q_OS_MAC
    QDir dir = qApp->applicationDirPath();
    /*dir.cdUp();*/
    /*dir.cdUp();*/
    /*dir.cdUp();*/
    QString bundleDir(dir.absolutePath());
    QFile file(bundleDir+"/plotTemp.xml");
#endif
    QTextStream stream;
    stream.setDevice(&file);
    if(!file.open(QIODevice::ReadWrite|QIODevice::Text))
    {
        globalpara.reportError("Fail to open case file to copy plot.",this);
        return;
    }
    else
    {
        QDomDocument doc;
        if(!doc.setContent(&file))
        {
            globalpara.reportError("Fail to load xml document to copy plot.....",this);
            file.close();
            return;
        }
        else
        {
            QDomElement plotData = doc.elementsByTagName("plotData").at(0).toElement();
            if(!plotData.elementsByTagName(pName).isEmpty())
            {

                QDomNode newNode = plotData.elementsByTagName(pName).at(0).cloneNode(true);
                newNode.toElement().setTagName(newName);
                plotData.appendChild(newNode);

            }
        }
        file.resize(0);
        doc.save(stream,4);
        file.close();
        stream.flush();
    }

    setupPlots(false);
}
Ejemplo n.º 15
0
inline void logMsg(const QString &msg) {
    static QFile logFile(LogFileName);
    static QTextStream qts;

    if (!logFile.isOpen()) {
        if (!logFile.open(QFile::WriteOnly | QIODevice::Append)) {
            throw std::runtime_error("Failed to open log file");
        }
        qts.setDevice(&logFile);
    }

    qts << msg << "\n";
    qts.flush();
}
Ejemplo n.º 16
0
    void endFunction(const std::string & callerName,
                     const std::string & function)
    {
        QMutexLocker locker(&_lock);

        --_beginsCount;
        for (int i = 0; i < _beginsCount; ++i) {
            _stream->operator <<("    ");
        }
        _stream->operator <<("STOP ");
        _stream->operator <<( callerName.c_str() );
        _stream->operator <<("    ");
        _stream->operator <<( function.c_str() );
        _stream->operator <<('\n');
        _stream->flush();
    }
Ejemplo n.º 17
0
void
EditableDenseThreeDimensionalModel::toXml(QTextStream &out,
                                          QString indent,
                                          QString extraAttributes) const
{
    QReadLocker locker(&m_lock);

    // For historical reasons we read and write "resolution" as "windowSize"

    std::cerr << "EditableDenseThreeDimensionalModel::toXml" << std::endl;

    Model::toXml
	(out, indent,
         QString("type=\"dense\" dimensions=\"3\" windowSize=\"%1\" yBinCount=\"%2\" minimum=\"%3\" maximum=\"%4\" dataset=\"%5\" startFrame=\"%6\" %7")
	 .arg(m_resolution)
	 .arg(m_yBinCount)
	 .arg(m_minimum)
	 .arg(m_maximum)
	 .arg(getObjectExportId(&m_data))
         .arg(m_startFrame)
	 .arg(extraAttributes));

    out << indent;
    out << QString("<dataset id=\"%1\" dimensions=\"3\" separator=\" \">\n")
	.arg(getObjectExportId(&m_data));

    for (size_t i = 0; i < m_binNames.size(); ++i) {
	if (m_binNames[i] != "") {
	    out << indent + "  ";
	    out << QString("<bin number=\"%1\" name=\"%2\"/>\n")
		.arg(i).arg(m_binNames[i]);
	}
    }

    for (size_t i = 0; i < m_data.size(); ++i) {
	out << indent + "  ";
	out << QString("<row n=\"%1\">").arg(i);
	for (size_t j = 0; j < m_data.at(i).size(); ++j) {
	    if (j > 0) out << " ";
	    out << m_data.at(i).at(j);
	}
	out << QString("</row>\n");
        out.flush();
    }

    out << indent + "</dataset>\n";
}
Ejemplo n.º 18
0
/**
 * @brief Go through a list of pending messages and check if message should be
 *     logged according to the set log level. Log the message to the output
 *     stream.
 * @param Log level
 * @param String to write to output stream if appropriate to the current
 *     log level.
 */
void Logger::Log()
{
    QMutexLocker locker(&logMutex);
    Q_UNUSED(locker);

    QListIterator<LogMessage> iter(pendingMessages);
    while (iter.hasNext())
    {
        LogMessage pendingMessage = iter.next();

        LogLevel level = pendingMessage.level;
        QString message = pendingMessage.message;
        bool newline = pendingMessage.newline;

        if (outputLevel != LOG_NONE && level <= outputLevel)
        {
            QString displayTime = "";
            QString initialPrefix = "";
            if (outputLevel > LOG_INFO)
            {
                displayTime = QString("[%1] - ").arg(QTime::currentTime().toString("hh:mm:ss.zzz"));
                initialPrefix = displayTime;
            }

            QTextStream *writeStream = outputStream;
            if (level < LOG_INFO && errorStream)
            {
                writeStream = errorStream;
            }

            *writeStream << initialPrefix << message;
            if (newline)
            {
                *writeStream << endl;
            }

            writeStream->flush();
        }
    }

    pendingMessages.clear();
}
Ejemplo n.º 19
0
 void beginFunction(const std::string & callerName,
                    const std::string & function)
 {
     if (!_file) {
         QString filename(NATRON_APPLICATION_NAME + QString("_log") + QString::number( QCoreApplication::instance()->applicationPid() ) + ".txt");
         open( filename.toStdString() );
     }
     QMutexLocker locker(&_lock);
     _stream->operator <<("********************************************************************************\n");
     for (int i = 0; i < _beginsCount; ++i) {
         _stream->operator <<("    ");
     }
     _stream->operator <<("START ");
     _stream->operator <<( callerName.c_str() );
     _stream->operator <<("    ");
     _stream->operator <<( function.c_str() );
     _stream->operator <<('\n');
     _stream->flush();
     ++_beginsCount;
 }
Ejemplo n.º 20
0
IdButton::IdButton( QString id,
                    QString text,
                    int height,
                    int width,
                    QWidget *parent,
                    Qt::Orientation orientation )
    : OrientationButton( text, parent )
    , m_id( id )
    , m_dim( width, height )
{
    setCheckable( true );
    QString qss;
    QTextStream qssStream;
    qssStream.setString( &qss );
    qssStream << " QPushButton {"
                 "     border-radius: 5px;"
                 "     background-color: regba( 32, 32, 32, 200 );"
                 "     max-width: " << width << "px;"
                 "     min-width: " << width << "px;"
                 "     max-height: " << height << "px;"
                 "     min-height: " << height << "px;"
                 "     font-size: 12px;"
                 "     color: white;"
                 " }"
                 " QPushButton:checked {"
                 "     background-color: #FFA858;"
                 "     color: #202020;"
                 " }"
//                 "QPushButton:hover {"
//                 "     background-color: #FFA858;"
//                 "     color: #202020;"
//                 " }"
                 ;
    qssStream.flush();
    setStyleSheet( qss );
    setText( text );
    this->setOrientation( orientation );
}
Ejemplo n.º 21
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.º 22
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QTextStream  cout (stdout);
    
/*    for (int i=1; i<argc; i++)
    {
        cout<<argv[i];
        cout<<"\n";
    }  */
    /*leftthumb.txt out.txt 0.9 0.0001*/
    QString infileName (argv [1]);
    QString outfileName (argv [2]);

    double start;// = QString(argv[3]).toDouble();
    double step;// = QString(argv[4]).toDouble();


    cout<<"contendor version";
    cout<<infileName;
    cout <<"\n";
    cout<<outfileName;
    cout <<"\n";
    //cout<<start;
    cout <<"\n";
    //cout<<step;
    cout <<"\n";

    QList <double> thresholds;
    thresholds<<0.9 << 0.99 << 0.999 << 0.9999 << 1;

    makeFRRForAllFingers(infileName, thresholds).outTableToTextFile(outfileName);



//    TableContendor cnt (1,1);



//    cnt.readFileIntoContendor("tablein.txt");
  //  cnt.outTableToTextFile("tableout.txt");

    return 0;


    //return    onArrayOfThresholds (infileName, outfileName);







    QList <double> listOfValues; //список значений, читаемый из файла
    /*
        Временное решение проблемы - потом, наверное, считывать придётся в табличный контейнер или нечто типа того
    */

    QFile infile (infileName);

    if (!infile.open(QIODevice::ReadOnly | QIODevice::Text      ))
{
        cout<<"Error: infile cannot be opened";
        cout.flush();
        return -1;
    }
    QTextStream str (&infile);
    while(!str.atEnd())
    {
        listOfValues.append(str.readLine().toDouble());
    }
    QHash <int, int> counterValuesLowerThanThreshold;
    //сраный костыль, ибо qHash не может быть с ключом типа double, просто не может, трололо!!!!
//первое значение - ключ
    QHash <int, double> keytable;
//заполняем таблицу порогов
    int j=0;
    for (double i=start; i<=1; i+=step)
    {
        keytable.insert(j,i);
        counterValuesLowerThanThreshold.insert(j,0);
        j++;
    }
    //зерно алгоритма
    foreach (double val, listOfValues)
    {
               {

        for (double i=start; i<=1; i+=step)
            if (val<=i)
            {
    //сраные костыли во все поляяяя!!
                //тролли советуют написать-таки реализацию qHash()с double, вкупе с оператором ==()
                counterValuesLowerThanThreshold.insert(keytable.key(i),counterValuesLowerThanThreshold.value(keytable.key(i))+1  );
                //counterValuesLowerThanThreshold.insert(i,counterValuesLowerThanThreshold.value(i)+1);
            }
        }
    }
Ejemplo n.º 23
0
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{


#ifdef NDEBUG
   // release mode code
    QString strout;
    switch (type) {
    case QtDebugMsg:
        strout = "Release Debug: " + msg + "\n";
        break;
    case QtInfoMsg:
        strout = "Release Info: " + msg + "\n";
        break;
    case QtWarningMsg:
        strout = "Release Warning: " + msg + "\n";
        break;
    case QtCriticalMsg:
        strout = "Release Critical: " + msg + "\n";
        break;
    case QtFatalMsg:
        strout = "Release Fatal: " + msg + "\n";
        abort();
    }

    if(doLogging)
    {
        out << strout;
        out.flush();
    }
    else
        fprintf(stderr, strout.toStdString().c_str());

#else
  // debug mode code
    QString strout;
    switch (type) {
    case QtDebugMsg:
        strout = "Debug Debug: " + msg + "\n";
        break;
    case QtInfoMsg:
        strout = "Debug Info: " + msg + "\n";
        break;
    case QtWarningMsg:
        strout = "Debug Warning: " + msg + "\n";
        break;
    case QtCriticalMsg:
        strout = "Debug Critical: " + msg + "\n";
        break;
    case QtFatalMsg:
        strout = "Debug Fatal: " + msg + "\n";
        abort();
    }

    if(doLogging)
    {
        out << strout;
        out.flush();
    }
    else
        fprintf(stderr, strout.toStdString().c_str());


#endif

}
Ejemplo n.º 24
0
void plotsDialog::on_dataSelectButton_clicked()
{
    QString pName = tabs->tabText(tabs->currentIndex());
    QString tableName;
    bool noTable = false;

    //make name-space for the new plot
#ifdef Q_OS_WIN32
    QFile file("plotTemp.xml");
#endif
#ifdef Q_OS_MAC
    QDir dir = qApp->applicationDirPath();
    /*dir.cdUp();*/
    /*dir.cdUp();*/
    /*dir.cdUp();*/
    QString bundleDir(dir.absolutePath());
    QFile file(bundleDir+"/plotTemp.xml");
#endif
    QTextStream stream;
    stream.setDevice(&file);
    if(!file.open(QIODevice::ReadWrite|QIODevice::Text))
    {
        globalpara.reportError("Fail to open case file to copy plot.",this);
        return;
    }
    else
    {
        QDomDocument doc;
        if(!doc.setContent(&file))
        {
            globalpara.reportError("Fail to load xml document to copy plot..",this);
            file.close();
            return;
        }
        else
        {
            //look for the original table that generated the plot
            QDomElement tableData = doc.elementsByTagName("TableData").at(0).toElement();
            QDomElement plotData = doc.elementsByTagName("plotData").at(0).toElement();
            tableName = plotData.elementsByTagName(pName).at(0).toElement().attribute("tableName");
            if(tableData.elementsByTagName(tableName).count()==0)
            {
                noTable = true;
                file.close();
            }
            else
            {
                noTable = false;
                QDomElement oldPlot = plotData.elementsByTagName(pName).at(0).toElement();
                oldPlot.setTagName("tempNode");
                file.resize(0);
                doc.save(stream,4);
                file.close();
                stream.flush();
            }

        }
    }

    if(noTable)
        globalpara.reportError("The original table for this plot is not available in table data.");
    else
    {
        //ask for new selection of parameters
        newParaPlotDialog *pDialog = new newParaPlotDialog(2,tableName,pName,this);
        pDialog->setWindowTitle("Re-select Parameters");
        pDialog->setModal(true);
        if(pDialog->exec()==QDialog::Accepted)
        {
            //if accepted, delete the original node under name _mod
#ifdef Q_OS_WIN32
            QFile file("plotTemp.xml");
#endif
#ifdef Q_OS_MAC
            QFile file(bundleDir+"/plotTemp.xml");
#endif
            QTextStream stream;
            stream.setDevice(&file);
            if(!file.open(QIODevice::ReadWrite|QIODevice::Text))
            {
                globalpara.reportError("Fail to open case file to copy plot.",this);
                return;
            }
            else
            {
                QDomDocument doc;
                if(!doc.setContent(&file))
                {
                    globalpara.reportError("Fail to load xml document to copy plot...",this);
                    file.close();
                    return;
                }
                else
                {
                    QDomElement plotData = doc.elementsByTagName("plotData").at(0).toElement();
                    plotData.removeChild(plotData.elementsByTagName("tempNode").at(0));
                }
                file.resize(0);
                doc.save(stream,4);
                file.close();
                stream.flush();

                saveChanges();
                setupPlots(false);
            }

        }
        else
        {
            //if canceled, resume the original plot name
#ifdef Q_OS_WIN32
            QFile file("plotTemp.xml");
#endif
#ifdef Q_OS_MAC
            QFile file(bundleDir+"/plotTemp.xml");
#endif

            QTextStream stream;
            stream.setDevice(&file);
            if(!file.open(QIODevice::ReadWrite|QIODevice::Text))
            {
                globalpara.reportError("Fail to open case file to copy plot.",this);
                return;
            }
            else
            {
                QDomDocument doc;
                if(!doc.setContent(&file))
                {
                    globalpara.reportError("Fail to load xml document to copy plot....",this);
                    file.close();
                    return;
                }
                else
                {
                    QDomElement plotData = doc.elementsByTagName("plotData").at(0).toElement();
                    QDomElement oldPlot = plotData.elementsByTagName("tempNode").at(0).toElement();
                    oldPlot.setTagName(pName);
                }
                file.resize(0);
                doc.save(stream,4);
                file.close();
                stream.flush();
            }

        }



    }
}
Ejemplo n.º 25
0
void plotsDialog::deleteCurrentPlot()
{
    QMessageBox * askBox = new QMessageBox(this);
    askBox->addButton("Delete",QMessageBox::YesRole);
    askBox->addButton("Cancel",QMessageBox::NoRole);
    askBox->setText("Confirm to delete the plot?");
    askBox->setWindowTitle("Warning");
    askBox->exec();
    if(askBox->buttonRole(askBox->clickedButton())==QMessageBox::YesRole)
    {
        Plot* plotToDelete = dynamic_cast<Plot*>(tabs->currentWidget());
#ifdef Q_OS_WIN32
        QFile file("plotTemp.xml");
#endif
#ifdef Q_OS_MAC
        QDir dir = qApp->applicationDirPath();
        /*dir.cdUp();*/
        /*dir.cdUp();*/
        /*dir.cdUp();*/
        QString bundleDir(dir.absolutePath());
        QFile file(bundleDir+"/plotTemp.xml");
#endif
        if(!file.open(QIODevice::ReadWrite|QIODevice::Text))
        {
            return;
            globalpara.reportError("Fail to open xml file for plots!",this);
        }
        else
        {
            QDomDocument doc;
            QTextStream stream;
            stream.setDevice(&file);
            if(!doc.setContent(&file))
            {
                globalpara.reportError("Fail to load xml document for plots!",this);
                file.close();
                return;
            }
            else
            {
                QDomElement plotData = doc.elementsByTagName("plotData").at(0).toElement();
                plotData.removeChild(plotData.elementsByTagName(tabs->tabText(tabs->currentIndex())).at(0));
            }
            file.resize(0);
            doc.save(stream,4);
            file.close();
            stream.flush();
        }


        if(tabs->count()>1)
        {
            tabs->removeTab(tabs->currentIndex());
        }
        else if(tabs->count()==1)
        {
            this->close();
        }
    }
    else return;
}
Ejemplo n.º 26
0
AbstractCommand::ReturnCodes Record::record()
{
    if (! checkInRepository())
        return NotInRepo;
    moveToRoot(CheckFileSystem);

    if (m_mode != Unset)
        m_all = m_mode == AllChanges;
    const bool needHunks = !m_all || m_patchName.isEmpty();

    ChangeSet changeSet;
    changeSet.fillFromCurrentChanges(rebasedArguments(), needHunks);

    changeSet.waitForFinishFirstFile();
    bool shouldDoRecord = changeSet.count() > 0;
    if (!shouldDoRecord) {
        Logger::warn() << "No changes!" << endl;
        return Ok;
    }

    QString email = m_author;
    if (email.isEmpty())
        email = getenv("EMAIL");
    QStringList environment;
    if (! email.isEmpty()) {
        QRegExp re("(.*) <([@\\S]+)>");
        if (re.exactMatch(email)) { // meaning its an email AND name
            environment << "GIT_AUTHOR_NAME="+ re.cap(1);
            environment << "GIT_COMMITTER_NAME="+ re.cap(1);
            environment << "GIT_AUTHOR_EMAIL="+ re.cap(2);
            environment << "GIT_COMMITTER_EMAIL="+ re.cap(2);
        }
        else if (m_author.isEmpty()) { // if its an account or shell wide option; just use the git defs.
            environment << "GIT_AUTHOR_EMAIL="+ email;
            environment << "GIT_COMMITTER_EMAIL="+ email;
        }
        else {
            Logger::error() << "Author format invalid. Please provide author formatted like; `name <email@host>\n";
            return InvalidOptions;
        }
    }

    if (shouldDoRecord && !m_all && m_mode != Index) { // then do interview
        HunksCursor cursor(changeSet);
        cursor.setConfiguration(m_config);
        Interview interview(cursor, name());
        interview.setUsePager(shouldUsePager());
        if (! interview.start()) {
            Logger::warn() << "Cancelled." << endl;
            return UserCancelled;
        }
    }

    if (shouldDoRecord && !m_all && m_mode != Index) { // check if there is anything selected
        shouldDoRecord = changeSet.hasAcceptedChanges();
        if (! shouldDoRecord) {
            Logger::warn() << "Ok, if you don't want to record anything, that's fine!" <<endl;
            return UserCancelled;
        }
    }
    if (dryRun())
        return Ok;

    if ((m_editComment || m_patchName.isEmpty()) && getenv("EDITOR")) {
        class Deleter : public QObject {
        public:
            Deleter() : commitMessage(0) { }
            ~Deleter() {
                if (commitMessage)
                    commitMessage->remove();
            }
            QFile *commitMessage;
        };
        Deleter parent;
        QFile *commitMessage;
        int i = 0;
        do {
            commitMessage = new QFile(QString("vng-record-%1").arg(i++), &parent);
        } while (commitMessage->exists());
        parent.commitMessage = commitMessage; // make sure the file is removed from FS.
        if (! commitMessage->open(QIODevice::WriteOnly)) {
            Logger::error() << "Vng failed. Could not create a temporary file for the record message '"
                << commitMessage->fileName() << "`\n";
            return WriteError;
        }
        const char * defaultCommitMessage1 = "\n***END OF DESCRIPTION***"; // we will look for this string later
        const char * defaultCommitMessage2 = "\nPlace the long patch description above the ***END OF DESCRIPTION*** marker.\n\nThis patch contains the following changes:\n\n";
        if (! m_patchName.isEmpty())
            commitMessage->write(m_patchName);
        else
            commitMessage->write("\n", 1);
        commitMessage->write(defaultCommitMessage1, strlen(defaultCommitMessage1));
        commitMessage->write(defaultCommitMessage2, strlen(defaultCommitMessage2));
        QBuffer buffer;
        changeSet.writeDiff(buffer, m_all ? ChangeSet::AllHunks : ChangeSet::UserSelection);
        ChangeSet actualChanges;
        actualChanges.fillFromDiffFile(buffer);
        QTextStream out (commitMessage);
        for (int i=0; i < actualChanges.count(); ++i) {
            File file = actualChanges.file(i);
            file.outputWhatsChanged(out, m_config, true, false);
        }
        for (int i=0; i < changeSet.count(); ++i) {
            File file = changeSet.file(i);
            if (file.isBinary() && (m_all || file.binaryChangeAcceptance() == Vng::Accepted))
                out << "M " << QString::fromLocal8Bit(file.fileName());
            else if (file.fileName().isEmpty() && (m_all || file.renameAcceptance() == Vng::Accepted))
                out << "D " << QString::fromLocal8Bit(file.oldFileName());
        }
        out.flush();

        commitMessage->close();
        QDateTime modification = QFileInfo(*commitMessage).lastModified();
        QString command = QString("%1 %2").arg(getenv("EDITOR")).arg(commitMessage->fileName());
        int rc = system(command.toAscii().data());
        if (rc != 0) {
            // this will keep patchName empty and we fall through to the interview.
            Logger::warn() << "Vng-Warning: Could not start editor '" << getenv("EDITOR") << "`\n";
            Logger::warn().flush();
        }
        else if (modification == QFileInfo(*commitMessage).lastModified()) {
            Logger::warn() << "unchanged, won't record\n";
            return UserCancelled;
        }
        else {
            // get data until the separator line.
            commitMessage->open(QIODevice::ReadOnly);
            m_patchName = commitMessage->readAll();
            commitMessage->close();
            int cuttoff = m_patchName.indexOf(defaultCommitMessage1);
            if (cuttoff > 0)
                m_patchName.truncate(cuttoff);
            for (int i = m_patchName.length()-1; i >= 0; --i) {
                if (m_patchName[i] == '\n' || m_patchName[i] == '\r' || m_patchName[i] == ' ')
                    m_patchName.resize(i); // shrink
                else break;
            }
        }
    }
    if (m_patchName.isEmpty())
        m_patchName = Interview::ask("What is the patch name? ").toUtf8();

    ReturnCodes rc = addFilesPerAcceptance(changeSet, m_all);
    if (rc != Ok)
        return rc;

    QProcess git;
    QStringList arguments;
    arguments << "write-tree";
    GitRunner runner(git, arguments);
    rc = runner.start(GitRunner::WaitForStandardOutput);
    if (rc != Ok) {
        Logger::error() << "Git write-tree failed!, aborting record\n";
        return rc;
    }
    char buf[1024];
    Vng::readLine(&git, buf, sizeof(buf));
    QString tree(buf);
    git.waitForFinished(); // patiently wait for it to finish..
    Logger::debug() << "The tree got git ref; " << tree;
    Logger::debug().flush(); // flush since we do an ask next

    arguments.clear();
    git.setEnvironment(environment);

    arguments << "commit-tree" << tree.left(40);
    if (!m_config.isEmptyRepo())
        arguments << "-p" << "HEAD" ;

    runner.setArguments(arguments);
    rc = runner.start(GitRunner::WaitUntilReadyForWrite);
    if (rc != Ok) {
        Logger::error() << "Git commit-tree failed!, aborting record\n";
        return rc;
    }
    git.write(m_patchName);
    git.write("\n");
    git.closeWriteChannel();
    Vng::readLine(&git, buf, sizeof(buf));
    QString commit(buf);
    Logger::debug() << "commit is ref; " << commit;
    git.waitForFinished(); // patiently wait for it to finish..
    if (commit.isEmpty()) {
        Logger::error() << "Git update-ref failed to produce a reference!, aborting record\n";
        return GitFailed;
    }
    m_sha1 = commit.left(40);

    arguments.clear();
    arguments << "update-ref" << "HEAD" << m_sha1;
    runner.setArguments(arguments);
    rc = runner.start(GitRunner::WaitUntilFinished);
    if (rc != Ok) {
        Logger::error() << "Git update-ref failed!, aborting record\n";
        return rc;
    }

    // We removed files from the index in case they were freshly added, but the user didn't want it in this commit.
    // we have to re-add those files.
    arguments.clear();
    arguments << "update-index" << "--add";
    for (int i=0; i < changeSet.count(); ++i) {
        File file = changeSet.file(i);
        if (! file.oldFileName().isEmpty())
            continue; // not a new added file.
        if (file.renameAcceptance() == Vng::Rejected)
            arguments.append(file.fileName());
    }
    if (arguments.count() > 2) {
        runner.setArguments(arguments);
        runner.start(GitRunner::WaitUntilFinished);
    }

    int endOfLine = m_patchName.indexOf('\n');
    if (endOfLine > 0)
        m_patchName.truncate(endOfLine);
    Logger::warn() << "Finished recording patch `" << m_patchName << "'" << endl;
    return Ok;
}
Ejemplo n.º 27
0
void FileDestination::write(const QString& message, Level)
{
    mOutputStream << message << endl;
    mOutputStream.flush();
}
Ejemplo n.º 28
0
bool TextBuffer::save (const QString &filename)
{
  // codec must be set!
  Q_ASSERT (m_textCodec);

  /**
   * construct correct filter device and try to open
   */
  QIODevice *file = KFilterDev::deviceForFile (filename, m_mimeTypeForFilterDev, false);
  if (!file->open (QIODevice::WriteOnly)) {
    delete file;
    return false;
  }

  /**
   * construct stream + disable Unicode headers
   */
  QTextStream stream (file);
  stream.setCodec (QTextCodec::codecForName("UTF-16"));

  // set the correct codec
  stream.setCodec (m_textCodec);

  // generate byte order mark?
  stream.setGenerateByteOrderMark (generateByteOrderMark());

  // our loved eol string ;)
  QString eol = "\n"; //m_doc->config()->eolString ();
  if (endOfLineMode() == eolDos)
    eol = QString ("\r\n");
  else if (endOfLineMode() == eolMac)
    eol = QString ("\r");

  // just dump the lines out ;)
  for (int i = 0; i < m_lines; ++i)
  {
    // get line to save
    Kate::TextLine textline = line (i);

    // strip trailing spaces
    if (m_removeTrailingSpaces)
    {
      int lastChar = textline->lastChar();
      if (lastChar > -1)
      {
        stream << textline->text().left (lastChar+1);
      }
    }
    else // simple, dump the line
      stream << textline->text();

    // append correct end of line string
    if ((i+1) < m_lines)
      stream << eol;
  }

  // flush stream
  stream.flush ();

  // close and delete file
  file->close ();
  delete file;

#ifndef Q_OS_WIN
  // ensure that the file is written to disk
  // we crete new qfile, as the above might be wrapper around compression
  QFile syncFile (filename);
  syncFile.open (QIODevice::ReadOnly);

#ifdef HAVE_FDATASYNC
  fdatasync (syncFile.handle());
#else
  fsync (syncFile.handle());
#endif
#endif

  // did save work?
  bool ok = stream.status() == QTextStream::Ok;

  // remember this revision as last saved if we had success!
  if (ok)
    m_history.setLastSavedRevision ();

  // report CODEC + ERRORS
  kDebug (13020) << "Saved file " << filename << "with codec" << m_textCodec->name()
    << (ok ? "without" : "with") << "errors";

  // emit signal on success
  if (ok)
    emit saved (filename);

  // return success or not
  return ok;
}
Ejemplo n.º 29
0
    virtual bool ProcessRequest(HttpWorkerThread *pThread,
                                HTTPRequest *pRequest)
    {
        (void)pThread;

        if (!pRequest)
            return false;

        if (pRequest->m_sBaseUrl != "/")
            return false;

        if (pRequest->m_sMethod == "getDeviceDesc")
            return false;

        pRequest->m_eResponseType = ResponseTypeHTML;
        pRequest->m_mapRespHeaders["Cache-Control"] =
            "no-cache=\"Ext\", max-age = 5000";

        SSDPCacheEntries* cache = NULL;
        QString ipaddress = QString();
        if (!UPnp::g_IPAddrList.isEmpty())
            ipaddress = UPnp::g_IPAddrList.at(0);

        QString shortdateformat = gCoreContext->GetSetting("ShortDateFormat",
                                                           "M/d");
        QString timeformat      = gCoreContext->GetSetting("TimeFormat",
                                                           "h:mm AP");
        QString hostname   = gCoreContext->GetHostName();
        QDateTime qdtNow   = QDateTime::currentDateTime();
        QString masterhost = gCoreContext->GetMasterHostName();
        QString masterip   = gCoreContext->GetSetting("MasterServerIP");
        QString masterport = gCoreContext->GetSettingOnHost("BackendStatusPort",
                                                            masterhost, "6544");

        QTextStream stream ( &pRequest->m_response );
        stream.setCodec("UTF-8");

        stream
           << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" "
           << "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\r\n"
           << "<html xmlns=\"http://www.w3.org/1999/xhtml\""
           << " xml:lang=\"en\" lang=\"en\">\r\n"
           << "<head>\r\n"
           << "  <meta http-equiv=\"Content-Type\""
           << "content=\"text/html; charset=UTF-8\" />\r\n"
           << "  <title>MythFrontend Status - "
           << qdtNow.toString(shortdateformat) << " "
           << qdtNow.toString(timeformat) << " - "
           << MYTH_BINARY_VERSION << "</title>\r\n"
           << "  <link rel=\"stylesheet\" href=\"/css/site.css\"   type=\"text/css\">\r\n"
           << "  <link rel=\"stylesheet\" href=\"/css/Status.css\" type=\"text/css\">\r\n"
           << "</head>\r\n"
           << "<body>\r\n\r\n"
           << "  <h1 class=\"status\">MythFrontend Status</h1>\r\n";

        // This frontend
        stream
           << "  <div class=\"content\">\r\n"
           << "    <h2 class=\"status\">This Frontend</h2>\r\n"
           << "Name : " << hostname << "<br />\r\n"
           << "Version : " << MYTH_BINARY_VERSION << "\r\n"
           << "  </div>\r\n";

        // Other frontends

        // This will not work with multiple frontends on the same machine (upnp
        // setup will fail on a second frontend anyway) and the ip address
        // filtering of the current frontend may not work in all situations

        cache = SSDP::Find("urn:schemas-mythtv-org:service:MythFrontend:1");
        if (cache)
        {
            stream
               << "  <div class=\"content\">\r\n"
               << "    <h2 class=\"status\">Other Frontends</h2>\r\n";

            EntryMap map;
            cache->GetEntryMap(map);
            cache->Release();
            cache = NULL;

            QMapIterator< QString, DeviceLocation * > i(map);
            while (i.hasNext())
            {
                i.next();
                QUrl url(i.value()->m_sLocation);
                if (url.host() != ipaddress)
                {
                    stream << "<br />" << url.host() << "&nbsp(<a href=\""
                           << url.toString(QUrl::RemovePath)
                           << "\">Status page</a>)\r\n";
                }
                i.value()->Release();
            }
            stream << "  </div>\r\n";
        }

        // Master backend
        stream
           << "  <div class=\"content\">\r\n"
           << "    <h2 class=\"status\">MythTV Backends</h2>\r\n"
           << "Master: " << masterhost << "&nbsp(<a href=\"http://"
           << masterip << ":" << masterport
           << "\">Status page</a>)\r\n";

        // Slave backends
        cache = SSDP::Find("urn:schemas-mythtv-org:device:SlaveMediaServer:1");
        if (cache)
        {
            EntryMap map;
            cache->GetEntryMap(map);
            cache->Release();
            cache = NULL;

            QMapIterator< QString, DeviceLocation * > i(map);
            while (i.hasNext())
            {
                i.next();
                QUrl url(i.value()->m_sLocation);
                stream << "<br />" << "Slave: " << url.host()
                       << "&nbsp(<a href=\""
                       << url.toString(QUrl::RemovePath)
                       << "\">Status page</a>)\r\n";
                i.value()->Release();
            }
        }

        stream
           << "  </div>\r\n";

        stream
           << "  <div class=\"content\">\r\n"
           << "    <h2 class=\"status\">Services</h2>\r\n"
           << "    <a href=\"MythFE/GetRemote\">Remote Control</a>\r\n"
           << "  </div>\r\n";

        double load[3];
        if (getloadavg(load, 3) != -1)
        {
            stream
               << "  <div class=\"content\">\r\n"
               << "    <h2 class=\"status\">Machine Information</h2>\r\n"
               << "    <div class=\"loadstatus\">\r\n"
               << "      This machine's load average:"
               << "\r\n      <ul>\r\n        <li>"
               << "1 Minute: " << QString::number(load[0]) << "</li>\r\n"
               << "        <li>5 Minutes: " << QString::number(load[1]) << "</li>\r\n"
               << "        <li>15 Minutes: " << QString::number(load[2])
               << "</li>\r\n      </ul>\r\n"
               << "    </div>\r\n"
               << "  </div>\r\n";
        }

        stream << "</body>\r\n</html>\r\n";
        stream.flush();

        return true;
    }
Ejemplo n.º 30
0
void ExporterPluginView::exportData(const bool useSelection, QTextStream &output)
{
  const KTextEditor::Range range = useSelection ? m_view->selectionRange() : m_view->document()->documentRange();
  const bool blockwise = useSelection ? m_view->blockSelection() : false;

  if ( (blockwise || range.onSingleLine()) && (range.start().column() > range.end().column() ) ) {
    return;
  }

  //outputStream.setEncoding(QTextStream::UnicodeUTF8);
  output.setCodec(QTextCodec::codecForName("UTF-8"));

  ///TODO: add more exporters
  AbstractExporter* exporter;

  exporter = new HTMLExporter(m_view, output, !useSelection);

  KTextEditor::HighlightInterface* hiface = qobject_cast<KTextEditor::HighlightInterface*>(m_view->document());

  const KTextEditor::Attribute::Ptr noAttrib(0);

  for (int i = range.start().line(); (i <= range.end().line()) && (i < m_view->document()->lines()); ++i)
  {
    const QString &line = m_view->document()->line(i);

    QList<KTextEditor::HighlightInterface::AttributeBlock> attribs;
    if ( hiface ) {
      attribs = hiface->lineAttributes(i);
    }

    int lineStart = 0;
    int remainingChars = line.length();
    if ( blockwise || range.onSingleLine() ) {
      lineStart = range.start().column();
      remainingChars = range.columnWidth();
    } else if ( i == range.start().line() ) {
      lineStart = range.start().column();
    } else if ( i == range.end().line() ) {
      remainingChars = range.end().column();
    }

    int handledUntil = lineStart;

    foreach ( const KTextEditor::HighlightInterface::AttributeBlock& block, attribs ) {
      // honor (block-) selections
      if ( block.start + block.length <= lineStart ) {
        continue;
      } else if ( block.start >= lineStart + remainingChars ) {
        break;
      }
      int start = qMax(block.start, lineStart);
      if ( start > handledUntil ) {
        exporter->exportText( line.mid( handledUntil, start - handledUntil ), noAttrib );
      }
      int length = qMin(block.length, remainingChars);
      exporter->exportText( line.mid( start, length ), block.attribute);
      handledUntil = start + length;
    }

    if ( handledUntil < lineStart + remainingChars ) {
      exporter->exportText( line.mid( handledUntil, remainingChars ), noAttrib );
    }

    exporter->closeLine(i == range.end().line());
  }

  delete exporter;

  output.flush();
}