示例#1
1
void Application::newConnection()
{
	QLocalSocket *socket = m_localServer->nextPendingConnection();

	if (!socket)
	{
		return;
	}

	socket->waitForReadyRead(1000);

	MainWindow *window = (getWindows().isEmpty() ? NULL : getWindow());
	QString data;
	QTextStream stream(socket);
	stream >> data;

	const QStringList encodedArguments = QString(QByteArray::fromBase64(data.toUtf8())).split(QLatin1Char(' '));
	QStringList decodedArguments;

	for (int i = 0; i < encodedArguments.count(); ++i)
	{
		decodedArguments.append(QString(QByteArray::fromBase64(encodedArguments.at(i).toUtf8())));
	}

	QCommandLineParser *parser = getParser();
	parser->parse(decodedArguments);

	const QString session = parser->value(QLatin1String("session"));
	const bool isPrivate = parser->isSet(QLatin1String("privatesession"));

	if (session.isEmpty())
	{
		if (!window || !SettingsManager::getValue(QLatin1String("Browser/OpenLinksInNewTab")).toBool() || (isPrivate && !window->getWindowsManager()->isPrivate()))
		{
			window = createWindow(isPrivate);
		}
	}
	else
	{
		const SessionInformation sessionData = SessionsManager::getSession(session);

		if (sessionData.clean || QMessageBox::warning(NULL, tr("Warning"), tr("This session was not saved correctly.\nAre you sure that you want to restore this session anyway?"), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
		{
			for (int i = 0; i < sessionData.windows.count(); ++i)
			{
				createWindow(isPrivate, false, sessionData.windows.at(i));
			}
		}
	}

	if (window)
	{
		if (!parser->positionalArguments().isEmpty())
		{
			const QStringList urls = parser->positionalArguments();

			for (int i = 0; i < urls.count(); ++i)
			{
				window->openUrl(urls.at(i));
			}
		}
		else if (session.isEmpty())
		{
			window->openUrl();
		}
	}

	delete socket;

	if (window)
	{
		window->raise();
		window->activateWindow();
	}

	delete parser;
}
示例#2
0
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RigEquil RigEquil::parseString(const QString& keywordData)
{
    double datumDepth                       = 0.0;
    double datuDepthPressure                = 0.0;
    double waterOilContactDepth             = 0.0;
    double waterOilContactCapillaryPressure = 0.0;
    double gasOilContactDepth               = 0.0;
    double gasOilContactCapillaryPressure   = 0.0;
    bool   liveOilInitConstantRs            = false;
    bool   wetGasInitConstantRv             = false;
    int    initializationTargetAccuracy     = -5;

    QString line(keywordData);
    line.replace("\t", " ");

    QStringList items = line.split(" ");
    if (items.size() > 0)
    {
        datumDepth = items.at(0).toDouble();
    }

    if (items.size() > 1)
    {
        datuDepthPressure = items.at(1).toDouble();
    }
    if (items.size() > 2)
    {
        waterOilContactDepth = items.at(2).toDouble();
    }
    if (items.size() > 3)
    {
        waterOilContactCapillaryPressure = items.at(3).toDouble();
    }
    if (items.size() > 4)
    {
        gasOilContactDepth = items.at(4).toDouble();
    }
    if (items.size() > 5)
    {
        gasOilContactCapillaryPressure = items.at(5).toDouble();
    }
    if (items.size() > 6)
    {
        liveOilInitConstantRs = items.at(6).toInt() > 0 ? true : false;
    }
    if (items.size() > 7)
    {
        wetGasInitConstantRv = items.at(7).toInt() > 0 ? true : false;
    }
    if (items.size() > 8)
    {
        initializationTargetAccuracy = items.at(8).toInt();
    }

    return RigEquil(datumDepth,
                    datuDepthPressure,
                    waterOilContactDepth,
                    waterOilContactCapillaryPressure,
                    gasOilContactDepth,
                    gasOilContactCapillaryPressure,
                    liveOilInitConstantRs,
                    wetGasInitConstantRv,
                    initializationTargetAccuracy);
}
void VideoTab::populateBoxes()
{
    QStringList values;
    QString current_selected = "";
    int index = -1;

    //aspect_ratio
    values = code_int->get_combo_vals("Video", "aspect_ratio");
    values.removeAll("");
    current_selected = cmb_aspect_ratio->currentText();
    cmb_aspect_ratio->clear();

    cmb_aspect_ratio->addItem("");

    for(int i = 0; i < values.size(); i++)
    {
        cmb_aspect_ratio->addItem(values[i]);
    }
    index = cmb_aspect_ratio->findText(current_selected);
    cmb_aspect_ratio->setCurrentIndex(index);


    //color_matrix
    values = code_int->get_combo_vals("Video", "color_matrix");
    values.removeAll("");
    current_selected = cmb_color_matrix->currentText();
    cmb_color_matrix->clear();
    cmb_color_matrix->addItem("");

    for(int i = 0; i < values.size(); i++)
    {
        cmb_color_matrix->addItem(values[i]);
    }
    index = cmb_color_matrix->findText(current_selected);
    cmb_color_matrix->setCurrentIndex(index);


    //encryption
    values = code_int->get_combo_vals("Video", "encryption");
    values.removeAll("");
    current_selected = cmb_encryption->currentText();
    cmb_encryption->clear();

    cmb_encryption->addItem("");

    for(int i = 0; i < values.size(); i++)
    {
        cmb_encryption->addItem(values[i]);
    }
    index = cmb_encryption->findText(current_selected);
    cmb_encryption->setCurrentIndex(index);


    //frame_rate_scan
    values = code_int->get_combo_vals("Video", "frame_rate_scan");
    values.removeAll("");
    current_selected = cmb_frame_rate_scan->currentText();
    cmb_frame_rate_scan->clear();

    cmb_frame_rate_scan->addItem("");

    for(int i = 0; i < values.size(); i++)
    {
        cmb_frame_rate_scan->addItem(values[i]);
    }
    index = cmb_frame_rate_scan->findText(current_selected);
    cmb_frame_rate_scan->setCurrentIndex(index);


    //frame_rate_value_min
    values = code_int->get_combo_vals("Video", "frame_rate_value");
    values.removeAll("");
    current_selected = cmb_frame_rate_min->currentText();
    cmb_frame_rate_min->clear();

    cmb_frame_rate_min->addItem("");

    for(int i = 0; i < values.size(); i++)
    {
        cmb_frame_rate_min->addItem(values[i]);
    }
    index = cmb_frame_rate_min->findText(current_selected);
    cmb_frame_rate_min->setCurrentIndex(index);


    //frame_rate_value_max
    values = code_int->get_combo_vals("Video", "frame_rate_value");
    values.removeAll("");
    current_selected = cmb_frame_rate_max->currentText();
    cmb_frame_rate_max->clear();

    cmb_frame_rate_max->addItem("");

    for(int i = (values.size() - 1); i >= 0; i--)
    { //Reverses the order of the elements
        cmb_frame_rate_max->addItem(values[i]);
    }
    index = cmb_frame_rate_max->findText(current_selected);
    cmb_frame_rate_max->setCurrentIndex(index);


    //res_size
    values = code_int->get_combo_vals("Video", "res_size");
    values.removeAll("");
    current_selected = cmb_res_size->currentText();
    cmb_res_size->clear();

    cmb_res_size->addItem("");

    for(int i = 0; i < values.size(); i++)
    {
        cmb_res_size->addItem(values[i]);
    }
    index = cmb_res_size->findText(current_selected);
    cmb_res_size->setCurrentIndex(index);


    //res_standard
    values = code_int->get_combo_vals("Video", "res_standard");
    values.removeAll("");
    current_selected = cmb_res_standard->currentText();
    cmb_res_standard->clear();

    cmb_res_standard->addItem("");

    for(int i = 0; i < values.size(); i++)
    {
        cmb_res_standard->addItem(values[i]);
    }
    index = cmb_res_standard->findText(current_selected);
    cmb_res_standard->setCurrentIndex(index);


    //sampling
    values = code_int->get_combo_vals("Video", "sampling");
    values.removeAll("");
    current_selected = cmb_sampling->currentText();
    cmb_sampling->clear();

    cmb_sampling->addItem("");

    for(int i = 0; i < values.size(); i++)
    {
        cmb_sampling->addItem(values[i]);
    }
    index = cmb_sampling->findText(current_selected);
    cmb_sampling->setCurrentIndex(index);


    //video_bitrate_Kb
    values = code_int->get_combo_vals("Video", "video_bitrate_Kb");
    values.removeAll("");
    current_selected = cmb_video_bitrate->currentText();
    cmb_video_bitrate->clear();

    cmb_video_bitrate->addItem("");

    for(int i = 0; i < values.size(); i++)
    {
        cmb_video_bitrate->addItem(values[i]);
    }
    index = cmb_video_bitrate->findText(current_selected);
    cmb_video_bitrate->setCurrentIndex(index);


    //video_format
    values = code_int->get_combo_vals("Video", "video_format");
    values.removeAll("");
    current_selected = cmb_video_format->currentText();
    cmb_video_format->clear();

    cmb_video_format->addItem("");

    for(int i = 0; i < values.size(); i++)
    {
        cmb_video_format->addItem(values.at(i));
    }
    index = cmb_video_format->findText(current_selected);
    cmb_video_format->setCurrentIndex(index);

}
示例#4
0
void QrcEditor::resolveLocationIssues(QStringList &files)
{
    const QDir dir = QFileInfo(m_treeview->fileName()).absoluteDir();
    const QString dotdotSlash = QLatin1String("../");
    int i = 0;
    int count = files.count();

    // Find first troublesome file
    for (; i < count; i++) {
        QString const &file = files.at(i);
        const QString relativePath = dir.relativeFilePath(file);
        if (relativePath.startsWith(dotdotSlash))
            break;
    }

    // All paths fine -> no interaction needed
    if (i == count) {
        return;
    }

    // Interact with user from now on
    bool abort = false;
    for (; i < count; i++) {
        // Path fine -> skip file
        QString const &file = files.at(i);
        QString const relativePath = dir.relativeFilePath(file);
        if (!relativePath.startsWith(dotdotSlash)) {
            continue;
        }

        // Path troublesome and aborted -> remove file
        if (abort) {
            files.removeAt(i);
            count--;
            i--;
            continue;
        } else {
            // Path troublesome -> query user
            QMessageBox message(this);
            message.setWindowTitle(tr("Invalid file"));
            message.setIcon(QMessageBox::Warning);
            QPushButton * const continueButton = message.addButton(tr("Add anyway"), QMessageBox::AcceptRole);
            QPushButton * const copyButton = message.addButton(tr("Copy"), QMessageBox::ActionRole);
            QPushButton * const skipButton = message.addButton(tr("Don't add"), QMessageBox::DestructiveRole);
            QPushButton * const abortButton = message.addButton(tr("Abort"), QMessageBox::RejectRole);
            message.setDefaultButton(copyButton);
            message.setEscapeButton(skipButton);
            message.setText(tr("The file %1 is not in a subdirectory of the resource file. Continuing will result in an invalid resource file.")
                            .arg(QDir::toNativeSeparators(file)));
            message.exec();
            if (message.clickedButton() == continueButton) {
                continue;
            } else if (message.clickedButton() == skipButton) {
                files.removeAt(i);
                count--;
                i--; // Compensate i++
            } else if (message.clickedButton() == copyButton) {
                const QFileInfo fi(file);
                const QFileInfo suggestion(dir, fi.fileName());
                const QString copyName = QFileDialog::getSaveFileName(this, tr("Choose copy location"),
                                                                suggestion.absoluteFilePath());
                if (!copyName.isEmpty()) {
                    if (QFile::exists(copyName)) {
                        if (!QFile::remove(copyName)) {
                            QMessageBox::critical(this, tr("Overwrite failed"),
                                                  tr("Could not overwrite file %1.")
                                                  .arg(QDir::toNativeSeparators(copyName)));
                            // Remove file
                            files.removeAt(i);
                            count--;
                            i--; // Compensate i++
                            continue;
                        }
                    }
                    if (!QFile::copy(file, copyName)) {
                        QMessageBox::critical(this, tr("Copying failed"),
                                              tr("Could not copy the file to %1.")
                                              .arg(QDir::toNativeSeparators(copyName)));
                        // Remove file
                        files.removeAt(i);
                        count--;
                        i--; // Compensate i++
                        continue;
                    }
                    files[i] = copyName;
                } else {
                    // Remove file
                    files.removeAt(i);
                    count--;
                    i--; // Compensate i++
                }
            } else if (message.clickedButton() == abortButton) {
                abort = true;

                files.removeAt(i);
                count--;
                i--; // Compensate i++
            }
        }
    }
}
void QmitkImageStatisticsView::OnClipboardStatisticsButtonClicked()
{
  QLocale tempLocal;
  QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
  if ( m_CurrentStatisticsValid && !( m_SelectedPlanarFigure != NULL))
   {
    const std::vector<mitk::ImageStatisticsCalculator::Statistics> &statistics =
      this->m_CalculationThread->GetStatisticsData();

    // Set time borders for for loop ;)
    unsigned int startT, endT;
    if(this->m_Controls->m_CheckBox4dCompleteTable->checkState()==Qt::CheckState::Unchecked)
    {
        startT = this->GetRenderWindowPart()->GetTimeNavigationController()->GetTime()->
          GetPos();
        endT = startT+1;
    }
    else
    {
        startT = 0;
        endT = statistics.size();
    }
    QVector< QVector<QString> > statisticsTable;
    QStringList headline;

    // Create Headline
    headline << " "
             << "Mean"
             << "Median"
             << "StdDev"
             << "RMS"
             << "Max"
             << "Min"
             << "NumberOfVoxels"
             << "Skewness"
             << "Kurtosis"
             << "Uniformity"
             << "Entropy"
             << "MPP"
             << "UPP"
             << "V [mm³]";

    for(int i=0;i<headline.size();i++)
    {
        QVector<QString> row;
        row.append(headline.at(i));
        statisticsTable.append(row);
    }

    // Fill Table
    for(unsigned int t=startT;t<endT;t++)
    {
        // Copy statistics to clipboard ("%Ln" will use the default locale for
        // number formatting)
        QStringList value;
        value << QString::number(t)
              << QString::number(statistics[t].GetMean())
              << QString::number(statistics[t].GetMedian())
              << QString::number(statistics[t].GetSigma())
              << QString::number(statistics[t].GetRMS())
              << QString::number(statistics[t].GetMax())
              << QString::number(statistics[t].GetMin())
              << QString::number(statistics[t].GetN())
              << QString::number(statistics[t].GetSkewness())
              << QString::number(statistics[t].GetKurtosis())
              << QString::number(statistics[t].GetUniformity())
              << QString::number(statistics[t].GetEntropy())
              << QString::number(statistics[t].GetMPP())
              << QString::number(statistics[t].GetUPP())
              << QString::number(m_Controls->m_StatisticsTable->item(7, 0)->data(Qt::DisplayRole).toDouble());

         for(int z=0;z<value.size();z++)
         {
             statisticsTable[z].append(value.at(z));
         }
    }

    // Create output string
    QString clipboard;
    for(int i=0;i<statisticsTable.size();i++)
    {
        for(int t=0;t<statisticsTable.at(i).size();t++)
        {
            clipboard.append(statisticsTable.at(i).at(t));
            clipboard.append("\t");
        }
        clipboard.append("\n");
    }
    QApplication::clipboard()->setText(clipboard, QClipboard::Clipboard);
  }
  else
  {
    QApplication::clipboard()->clear();
  }
  QLocale::setDefault(tempLocal);
}
示例#6
0
Optimization::Optimization(QDomElement domProblem,Project* project,bool &ok)
    :Problem((ProjectBase*)project)
{
    // initialization
    _omProject = project;
    _algos = OptimAlgoUtils::getNewAlgos(this);

    // look for modmodelplus
    ok = !domProblem.isNull();
    ok = ok && (domProblem.tagName()==Optimization::className());
    if(ok)
    {

        QDomElement  domInfos = domProblem.firstChildElement("Infos");
        this->setName(domInfos.attribute("name", "" ));

        // compatibility with older saving format (one model, saved in Infos node)
        if(!domInfos.attribute("model").isEmpty())
        {
            QString modelName = domInfos.attribute("model");
            ModModelPlus* model = project->modModelPlus(modelName);

            // read corresponding controlers
            QDomElement domCtrls = domProblem.firstChildElement(ModPlusCtrls::className());
            ModPlusCtrls* ctrls = new ModPlusCtrls(project,model,domCtrls);

            // add model
            this->addModel(domInfos.attribute("model"));
        }

        // new format
        QDomElement domModels = domProblem.firstChildElement("Models");
        QDomElement domModel = domModels.firstChildElement("Model");
        while(!domModel.isNull())
        {
            QString modelName = domModel.attribute("name");
            ModModelPlus* model = project->modModelPlus(modelName);

            // read corresponding controlers
            QDomElement domCtrls = domModel.firstChildElement(ModPlusCtrls::className());
            ModPlusCtrls* ctrls = new ModPlusCtrls(project,model,domCtrls);

            // add model and controlers
            this->addModel(modelName,ctrls);


            domModel = domModel.nextSiblingElement("Model");
        }

    }


    //initialize default(otherwise seg fault in destructor)
    _optimizedVariables = new OptVariables(true);
    _scannedVariables = new ScannedVariables(true);
    _overwritedVariables = new Variables(true);
    _objectives = new OptObjectives(true);

    // Optimized Variables
    QDomElement domOptVars = domProblem.firstChildElement("OptimizedVariables");
    this->optimizedVariables()->setItems(domOptVars);

    // Objectives
    QDomElement domObj = domProblem.firstChildElement("Objectives");
    this->objectives()->setItems(domObj);

    // Scanned Variables
    QDomElement domScann = domProblem.firstChildElement("ScannedVariables");
    this->scannedVariables()->setItems(domScann);

    // Overvars Variables
    QDomElement domOverVars = domProblem.firstChildElement("OverwritedVariables");
    this->overwritedVariables()->setItems(domOverVars);
    for(int i=0;i<overwritedVariables()->size();i++)
        overwritedVariables()->at(i)->setIsEditableField(Variable::VALUE,true);

    // Files to copy
    QDomElement cFilesToCopy = domProblem.firstChildElement("FilesToCopy");
    QString text = cFilesToCopy.text();
    QStringList strList = text.split("\n",QString::SkipEmptyParts);
    for(int i=0;i<strList.size();i++)
        this->_filesToCopy.push_back(QFileInfo(strList.at(i)));

    // BlockSubstitutions
    QDomElement domBlockSubs = domProblem.firstChildElement("BlockSubstitutions");
    _blockSubstitutions = new BlockSubstitutions(project,domBlockSubs);

    // EA
    QDomElement domEA = domProblem.firstChildElement("EA");
    QDomElement domEAInfos = domEA.firstChildElement("Infos");
    if(!domEAInfos.isNull())
    {
        this->setiCurAlgo(domEAInfos.attribute("num", "" ).toInt());
    }
    QDomElement domEAParameters = domEA.firstChildElement("Parameters");
    if(!domEAParameters.isNull())
    {
        this->getCurAlgo()->_parameters->update(domEAParameters);
    }
}
示例#7
0
bool Optimization::addModels(QStringList models)
{
    for(int i=0;i<models.size();i++)
        addModel(models.at(i));
}
示例#8
0
void beamtest::readfile()
{

QTime time;
time.start();
Handle_AIS_InteractiveContext ic = ui::getInstance()->getWindowContext();

double chunk = 30000000;
double chunkcount = 3;
//double maxpoints = chunkcount * chunk;
double maxpoints = chunk-1;
Graphic3d_Array1OfVertex* thepointcloud1 = new Graphic3d_Array1OfVertex(1,chunk);


//Graphic3d_Array1OfVertex thepointcloud2(1,chunk);
//Graphic3d_Array1OfVertex thepointcloud3(1,chunk);


QString filename = QFileDialog::getOpenFileName ( this,
												 tr("Import File"),"",
												 tr( "All point cloud formats (*.ptx);;" 
												 "XYZ (*.xyz *XYZ);;" 
												 "PTX (*.ptx *.PTX)"));

QFile file(filename);
if (!file.open(QFile::ReadOnly)) return ;

QMap<QString,gp_Pnt> pointmap;


QProgressDialog progress("loading cloudpoint", "Abort Copy", 1,100);

int count = 0;
int filepos = 0;
QTextStream stream(&file );
QString line;
 do {
        filepos++;
        //qDebug() << "file-linepos:" << filepos;


    line = stream.readLine();


        QStringList linelist = line.split(tr(" "));
        if (linelist.size() == 4)
        {
           
               double x = linelist.at(0).toDouble();
               double y = linelist.at(1).toDouble();
               double z = linelist.at(2).toDouble();
               QString index = linelist.at(0) + linelist.at(1) + linelist.at(2) ;

               if(!pointmap.contains(index))
               {
			    	   count++;
					   if (count % 100000 == 0){
					   progress.setValue((count *100/maxpoints));
						   }
                      // double intensity = linelist.at(3).toDouble();
                       gp_Pnt p1(x,y,z);
                       //TopoDS_Shape point =hsf::AddNewPoint(p1);
                       //vis(point)
					   Graphic3d_Vertex thevert(x,y,z);
					   thepointcloud1->SetValue(count,thevert);
			/*		   if (count < chunk && count > 0)
					   {
						   thepointcloud1.SetValue(count,thevert);
					   } else if (count > chunk && count <= (2*chunk))
					   {
						   thepointcloud2.SetValue(count-chunk,thevert);
					   } else if (count > (2*chunk) && count < (3 * chunk))
					   {
						   thepointcloud3.SetValue(count-(chunk*2),thevert);
					   }*/
					   

                       pointmap.insert(index,p1);
               }

        }

if (count > maxpoints) break;

 } while (!line.isNull());

//Handle(AIS_PointCloud) mypc1 = new AIS_PointCloud(*thepointcloud1);
//ic->Display(mypc1);

//
//Handle(AIS_PointCloud) mypc2 = new AIS_PointCloud(thepointcloud2);
//ic->Display(mypc2);
//
//
//Handle(AIS_PointCloud) mypc3 = new AIS_PointCloud(thepointcloud3);
//ic->Display(mypc3);

//ENDPART

double milliseconds = time.elapsed();
double seconds = (milliseconds/1000);
double minutes = seconds/60;
double hours = minutes/60;


QString timetxt;
QTextStream linestream(&timetxt);
linestream << "h" << hours << ":m " << minutes << ":s " << seconds << ".ms" << milliseconds; 

ui::getInstance()->Statusbar(timetxt);
qDebug() <<  "time ellapsed:" << timetxt;



}
示例#9
0
void beamtest::writebinarytochunkswithcolor()
	{
QFileInfo fileInfo;

QString filename = QFileDialog::getOpenFileName ( this,tr("Import File"),
												 "",tr( "All point cloud formats (*.ptx);;"
												 "XYZ (*.xyz *XYZ);;"
												 "PTX (*.ptx *.PTX)"));



	
		 int chunk = 2000000;
		 //int numfiles = floor((double) shapecount / (double) chunk);
		 int shapecounter=0;
		 int filecounter = 0;

double chunksize= 2000000;
int count =0;
int debugcount = 0;
char buf[1024];
QFile file(filename);
qint64 lineLength=0;
QStringList linelist;

QString filename2 = QFileDialog::getSaveFileName(this, tr("SaveBinary"), " ",tr("dat (*.dat "));
QFile file2(filename2);
 file2.open(QIODevice::WriteOnly);
 QDataStream out(&file2);   // we will serialize the data into the file

 	fileInfo.setFile(filename2);

	QString dirname = fileInfo.absoluteDir().absolutePath();
	filename = fileInfo.fileName();
	QString basename = fileInfo.baseName();
	QString bundlename = fileInfo.bundleName();

 if (file.open(QFile::ReadOnly)) {
        do {

    lineLength = file.readLine(buf, sizeof(buf));
    if (lineLength != -1) {
        QString line(buf);

        linelist = line.split(tr(" "));

        if (linelist.size() == 4)
        {
			
			double x = linelist.at(0).toDouble();
            double y = linelist.at(1).toDouble();
            double z = linelist.at(2).toDouble();
			double intensity= linelist.at(3).toDouble();
			if(x != 0 && y != 0 && z != 0 )
			{
			count++;
			shapecounter++;
				if(shapecounter == chunk)
					{
					
					shapecounter = 0;
					filecounter++;
					QString curfilename = dirname + tr("/") + basename + QString::number(filecounter) + tr(".data");
					file2.close();
					file2.setFileName(curfilename);
					file2.open(QFile::WriteOnly);
					
			
					}


			if (count % 100000 == 0) qDebug() << count;

			out << x << y << z << intensity;
			}

        }

   //if (count > 10000) break;


    }
        }while (lineLength != -1);
 }


if(file2.isOpen()) file2.close();






	}
示例#10
0
int main(int argc, char *argv[])
{
    Application app(argc, argv);
    QApplication::setOrganizationName(Common::ORG_NAME);
    QApplication::setOrganizationDomain(Common::ORG_DOMAIN);
    QApplication::setApplicationName(Common::APP_NAME);
    QApplication::setWindowIcon( QIcon(":/res/ico/anonymous.png") );
    QSettings settings;
    NetworkAccessManager::instance()->setCache(0);
    LocalServer localServer;
    //LocalServer::removeServer(Common::APP_NAME);
    bool serverStarted = localServer.listen(Common::APP_NAME);
    QStringList argList;
    QStringList urlList;
    bool fillingUrlList = false;

    for (int i = 0; i < argc; ++i)
    {
        QString arg(argv[i]);

        if ( arg.at(0) == LocalServer::PREFIX.at(0) )
        {
            argList << arg;

            if (fillingUrlList)
                fillingUrlList = false;
            else if (LocalServer::ARG_URLS == arg)
                fillingUrlList = true;
        }
        else if (fillingUrlList)
        {
            urlList << QUrl::fromUserInput(arg).toString();
        }
    }

    if ( !serverStarted && !argList.contains(LocalServer::ARG_MULTIPLE) )
    {
        if ( argList.contains(LocalServer::ARG_URLS) )
        {
            QLocalSocket socket;
            socket.connectToServer(Common::APP_NAME, QIODevice::WriteOnly);

            if ( !socket.waitForConnected() )
                return 1;

            QByteArray data;

            for (int i = 0; i < argc; ++i)
            {
                data.append(argv[i]).append('\0');
            }

            if ( -1 == socket.write(data) )
                return 2;

            if ( !socket.waitForBytesWritten() )
                return 3;

            socket.disconnectFromServer();
        }

        return 0;
    }

    qRegisterMetaType<ParceTask::Result>("ParceTask::Result");
    qRegisterMetaType<SaveTask::Result>("SaveTask::Result");
    qRegisterMetaType<SavePageTask::Result>("SavePageTask::Result");
    qRegisterMetaType<RmdirTask::Result>("RmdirTask::Result");
    qRegisterMetaType<ImageboardThread*>("ImageboardThread*");
    qRegisterMetaType<InfoWidget*>("InfoWidget*");
    qRegisterMetaType<QModelIndex>("QModelIndex");
    qRegisterMetaType<ImageboardThread::Modifiable>("ImageboardThread::Modifiable");
    QThreadPool::globalInstance()->setMaxThreadCount(10);
    ThreadManager threadManager(0);
    QObject::connect( &localServer,
             SIGNAL( addThreadSilent(ImageboardThread::Parameters, bool) ),
             &threadManager,
             SLOT( requestAddThread(ImageboardThread::Parameters, bool) ) );

    if ( argList.contains(LocalServer::ARG_DEFAULT) && !urlList.isEmpty() )
    {
        bool start = argList.contains(LocalServer::ARG_START);
        settings.beginGroup(ParametersDialog::GROUP_PARAMETERS);
          settings.beginGroup(ThreadManager::SUB_GROUP_DEFAULT);
            ImageboardThread::Parameters param =
                    ImageboardThread::readParameters(settings);
          settings.endGroup();
        settings.endGroup();

        for (int i = 0; i < urlList.count(); ++i)
        {
            param.url = urlList.at(i);
            param.added = QDateTime::currentDateTime();
            threadManager.requestAddThread(param, start);
        }
    }

    MainWindow *mainWindow = new MainWindow(threadManager.threadModel(),
                                            threadManager.categoryModel(), 0);
    QObject::connect(&app, SIGNAL( requestWriteSettings() ),
                     mainWindow, SLOT( writeSettings() ),
                     Qt::DirectConnection);
    QObject::connect(
                mainWindow,
                SIGNAL( requestAddThread(ImageboardThread::Parameters, bool) ),
                &threadManager,
                SLOT( requestAddThread(ImageboardThread::Parameters, bool) ) );
    QObject::connect( mainWindow, SIGNAL( requestBackup(QString) ),
                      &threadManager, SLOT( requestBackup(QString) ) );
    QObject::connect( mainWindow,
                      SIGNAL( requestRemoveThread(QList<int>, bool) ),
                      &threadManager,
                      SLOT( requestRemoveThread(QList<int>, bool) ) );
    QObject::connect( mainWindow, SIGNAL( requestStartThread(int) ),
                      &threadManager, SLOT( requestStartThread(int) ) );
    QObject::connect( mainWindow, SIGNAL( requestStopThread(int) ),
                      &threadManager, SLOT( requestStopThread(int) ) );
    QObject::connect( mainWindow, SIGNAL( requestOpenDir(int) ),
                      &threadManager, SLOT( requestOpenDir(int) ) );
    QObject::connect( mainWindow, SIGNAL( requestOpenUrl(int) ),
                      &threadManager, SLOT( requestOpenUrl(int) ) );
    QObject::connect( mainWindow, SIGNAL( requestOpenLocal(int) ),
                      &threadManager, SLOT( requestOpenLocal(int) ) );
    QObject::connect( mainWindow,
                      SIGNAL(requestSetObservedThread(int, InfoWidget*) ),
                      &threadManager,
                      SLOT( requestSetObservedThread(int, InfoWidget*) ) );
    QObject::connect( mainWindow,
                      SIGNAL( requestModifyParameters(
                                 QList<int>, ImageboardThread::Modifiable) ),
                      &threadManager,
                      SLOT( requestModifyParameters(
                               QList<int>, ImageboardThread::Modifiable) ) );
    QObject::connect( mainWindow, SIGNAL( requestRetranslate() ),
                      &threadManager, SLOT( requestRetranslate() ) );
    QObject::connect( mainWindow, SIGNAL( requestWriteSettings() ),
                      &threadManager, SLOT( requestWriteSettings() ) );
    QObject::connect( &localServer, SIGNAL( addThreads(QStringList) ),
                      mainWindow, SLOT( callAddThreadDialog(QStringList) ) );
    ParametersDialog::CommonParameters commonParam =
            ParametersDialog::readCommonParameters(settings);
    mainWindow->setVisibility(!commonParam.startMinimized);

    if ( !argList.contains(LocalServer::ARG_DEFAULT) && !urlList.isEmpty() )
        mainWindow->callAddThreadDialog(urlList);

    int err = app.exec();
    //LocalServer::removeServer(Common::APP_NAME);
    localServer.close();
    return err;
}
示例#11
0
void tst_qdeclarativeinstruction::dump()
{
    QDeclarativeCompiledData *data = new QDeclarativeCompiledData(0);
    {
        QDeclarativeInstruction i;
        i.line = 0;
        i.type = QDeclarativeInstruction::Init;
        i.init.bindingsSize = 0;
        i.init.parserStatusSize = 3;
        i.init.contextCache = -1;
        i.init.compiledBinding = -1;
        data->bytecode << i;
    }

    {
        QDeclarativeCompiledData::TypeReference ref;
        ref.className = "Test";
        data->types << ref;

        QDeclarativeInstruction i;
        i.line = 1;
        i.type = QDeclarativeInstruction::CreateObject;
        i.create.type = 0;
        i.create.data = -1;
        i.create.bindingBits = -1;
        i.create.column = 10;
        data->bytecode << i;
    }

    {
        data->primitives << "testId";

        QDeclarativeInstruction i;
        i.line = 2;
        i.type = QDeclarativeInstruction::SetId;
        i.setId.value = data->primitives.count() - 1;
        i.setId.index = 0;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 3;
        i.type = QDeclarativeInstruction::SetDefault;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 4;
        i.type = QDeclarativeInstruction::CreateComponent;
        i.createComponent.count = 3;
        i.createComponent.column = 4;
        i.createComponent.endLine = 14;
        i.createComponent.metaObject = 0;

        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 5;
        i.type = QDeclarativeInstruction::StoreMetaObject;
        i.storeMeta.data = 3;
        i.storeMeta.aliasData = 6;
        i.storeMeta.propertyCache = 7;

        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 6;
        i.type = QDeclarativeInstruction::StoreFloat;
        i.storeFloat.propertyIndex = 3;
        i.storeFloat.value = 11.3;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 7;
        i.type = QDeclarativeInstruction::StoreDouble;
        i.storeDouble.propertyIndex = 4;
        i.storeDouble.value = 14.8;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 8;
        i.type = QDeclarativeInstruction::StoreInteger;
        i.storeInteger.propertyIndex = 5;
        i.storeInteger.value = 9;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 9;
        i.type = QDeclarativeInstruction::StoreBool;
        i.storeBool.propertyIndex = 6;
        i.storeBool.value = true;

        data->bytecode << i;
    }

    {
        data->primitives << "Test String";
        QDeclarativeInstruction i;
        i.line = 10;
        i.type = QDeclarativeInstruction::StoreString;
        i.storeString.propertyIndex = 7;
        i.storeString.value = data->primitives.count() - 1;
        data->bytecode << i;
    }

    {
        data->urls << QUrl("http://www.qt-project.org");
        QDeclarativeInstruction i;
        i.line = 11;
        i.type = QDeclarativeInstruction::StoreUrl;
        i.storeUrl.propertyIndex = 8;
        i.storeUrl.value = data->urls.count() - 1;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 12;
        i.type = QDeclarativeInstruction::StoreColor;
        i.storeColor.propertyIndex = 9;
        i.storeColor.value = 0xFF00FF00;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 13;
        i.type = QDeclarativeInstruction::StoreDate;
        i.storeDate.propertyIndex = 10;
        i.storeDate.value = 9;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 14;
        i.type = QDeclarativeInstruction::StoreTime;
        i.storeTime.propertyIndex = 11;
        i.storeTime.valueIndex = 33;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 15;
        i.type = QDeclarativeInstruction::StoreDateTime;
        i.storeDateTime.propertyIndex = 12;
        i.storeDateTime.valueIndex = 44;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 16;
        i.type = QDeclarativeInstruction::StorePoint;
        i.storeRealPair.propertyIndex = 13;
        i.storeRealPair.valueIndex = 3;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 17;
        i.type = QDeclarativeInstruction::StorePointF;
        i.storeRealPair.propertyIndex = 14;
        i.storeRealPair.valueIndex = 9;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 18;
        i.type = QDeclarativeInstruction::StoreSize;
        i.storeRealPair.propertyIndex = 15;
        i.storeRealPair.valueIndex = 8;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 19;
        i.type = QDeclarativeInstruction::StoreSizeF;
        i.storeRealPair.propertyIndex = 16;
        i.storeRealPair.valueIndex = 99;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 20;
        i.type = QDeclarativeInstruction::StoreRect;
        i.storeRect.propertyIndex = 17;
        i.storeRect.valueIndex = 2;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 21;
        i.type = QDeclarativeInstruction::StoreRectF;
        i.storeRect.propertyIndex = 18;
        i.storeRect.valueIndex = 19;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 22;
        i.type = QDeclarativeInstruction::StoreVector3D;
        i.storeVector3D.propertyIndex = 19;
        i.storeVector3D.valueIndex = 9;
        data->bytecode << i;
    }

    {
        data->primitives << "color(1, 1, 1, 1)";
        QDeclarativeInstruction i;
        i.line = 23;
        i.type = QDeclarativeInstruction::StoreVariant;
        i.storeString.propertyIndex = 20;
        i.storeString.value = data->primitives.count() - 1;

        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 24;
        i.type = QDeclarativeInstruction::StoreObject;
        i.storeObject.propertyIndex = 21;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 25;
        i.type = QDeclarativeInstruction::StoreVariantObject;
        i.storeObject.propertyIndex = 22;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 26;
        i.type = QDeclarativeInstruction::StoreInterface;
        i.storeObject.propertyIndex = 23;
        data->bytecode << i;
    }

    {
        data->primitives << "console.log(1921)";

        QDeclarativeInstruction i;
        i.line = 27;
        i.type = QDeclarativeInstruction::StoreSignal;
        i.storeSignal.signalIndex = 2;
        i.storeSignal.value = data->primitives.count() - 1;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 29;
        i.type = QDeclarativeInstruction::StoreScriptString;
        i.storeScriptString.propertyIndex = 24;
        i.storeScriptString.value = 3;
        i.storeScriptString.scope = 1;
        data->bytecode << i;
    }

    {
        data->datas << "mySignal";

        QDeclarativeInstruction i;
        i.line = 30;
        i.type = QDeclarativeInstruction::AssignSignalObject;
        i.assignSignalObject.signal = 0;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 31;
        i.type = QDeclarativeInstruction::AssignCustomType;
        i.assignCustomType.propertyIndex = 25;
        i.assignCustomType.valueIndex = 4;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 32;
        i.type = QDeclarativeInstruction::StoreBinding;
        i.assignBinding.property = 26;
        i.assignBinding.value = 3;
        i.assignBinding.context = 2;
        i.assignBinding.owner = 0;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 33;
        i.type = QDeclarativeInstruction::StoreCompiledBinding;
        i.assignBinding.property = 27;
        i.assignBinding.value = 2;
        i.assignBinding.context = 4;
        i.assignBinding.owner = 0;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 34;
        i.type = QDeclarativeInstruction::StoreValueSource;
        i.assignValueSource.property = 29;
        i.assignValueSource.owner = 1;
        i.assignValueSource.castValue = 4;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 35;
        i.type = QDeclarativeInstruction::StoreValueInterceptor;
        i.assignValueInterceptor.property = 30;
        i.assignValueInterceptor.owner = 2;
        i.assignValueInterceptor.castValue = -4;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 36;
        i.type = QDeclarativeInstruction::BeginObject;
        i.begin.castValue = 4;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 38;
        i.type = QDeclarativeInstruction::StoreObjectQList;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 39;
        i.type = QDeclarativeInstruction::AssignObjectList;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 40;
        i.type = QDeclarativeInstruction::FetchAttached;
        i.fetchAttached.id = 23;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 42;
        i.type = QDeclarativeInstruction::FetchQList;
        i.fetch.property = 32;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 43;
        i.type = QDeclarativeInstruction::FetchObject;
        i.fetch.property = 33;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 44;
        i.type = QDeclarativeInstruction::FetchValueType;
        i.fetchValue.property = 34;
        i.fetchValue.type = 6;
        i.fetchValue.bindingSkipList = 7;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 45;
        i.type = QDeclarativeInstruction::PopFetchedObject;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 46;
        i.type = QDeclarativeInstruction::PopQList;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 47;
        i.type = QDeclarativeInstruction::PopValueType;
        i.fetchValue.property = 35;
        i.fetchValue.type = 8;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 48;
        i.type = QDeclarativeInstruction::Defer;
        i.defer.deferCount = 7;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = -1;
        i.type = QDeclarativeInstruction::Defer;
        i.defer.deferCount = 7;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 48;
        i.type = QDeclarativeInstruction::StoreImportedScript;
        i.storeScript.value = 2;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 50;
        i.type = (QDeclarativeInstruction::Type)(1234); // Non-existent
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 51;
        i.type = QDeclarativeInstruction::StoreVariantInteger;
        i.storeInteger.value = 11;
        i.storeInteger.propertyIndex = 32;
        data->bytecode << i;
    }

    {
        QDeclarativeInstruction i;
        i.line = 52;
        i.type = QDeclarativeInstruction::StoreVariantDouble;
        i.storeDouble.value = 33.7;
        i.storeDouble.propertyIndex = 19;
        data->bytecode << i;
    }

    QStringList expect;
    expect 
        << "Index\tLine\tOperation\t\tData1\tData2\tData3\tComments"
        << "-------------------------------------------------------------------------------"
        << "0\t\t0\tINIT\t\t\t0\t3\t-1\t-1"
        << "1\t\t1\tCREATE\t\t\t0\t-1\t\t\"Test\""
        << "2\t\t2\tSETID\t\t\t0\t\t\t\"testId\""
        << "3\t\t3\tSET_DEFAULT"
        << "4\t\t4\tCREATE_COMPONENT\t3"
        << "5\t\t5\tSTORE_META\t\t3"
        << "6\t\t6\tSTORE_FLOAT\t\t3\t11.3"
        << "7\t\t7\tSTORE_DOUBLE\t\t4\t14.8"
        << "8\t\t8\tSTORE_INTEGER\t\t5\t9"
        << "9\t\t9\tSTORE_BOOL\t\t6\ttrue"
        << "10\t\t10\tSTORE_STRING\t\t7\t1\t\t\"Test String\""
        << "11\t\t11\tSTORE_URL\t\t8\t0\t\tQUrl(\"http://www.qt-project.org\") "
        << "12\t\t12\tSTORE_COLOR\t\t9\t\t\t\"ff00ff00\""
        << "13\t\t13\tSTORE_DATE\t\t10\t9"
        << "14\t\t14\tSTORE_TIME\t\t11\t33"
        << "15\t\t15\tSTORE_DATETIME\t\t12\t44"
        << "16\t\t16\tSTORE_POINT\t\t13\t3"
        << "17\t\t17\tSTORE_POINTF\t\t14\t9"
        << "18\t\t18\tSTORE_SIZE\t\t15\t8"
        << "19\t\t19\tSTORE_SIZEF\t\t16\t99"
        << "20\t\t20\tSTORE_RECT\t\t17\t2"
        << "21\t\t21\tSTORE_RECTF\t\t18\t19"
        << "22\t\t22\tSTORE_VECTOR3D\t\t19\t9"
        << "23\t\t23\tSTORE_VARIANT\t\t20\t2\t\t\"color(1, 1, 1, 1)\""
        << "24\t\t24\tSTORE_OBJECT\t\t21"
        << "25\t\t25\tSTORE_VARIANT_OBJECT\t22"
        << "26\t\t26\tSTORE_INTERFACE\t\t23"
        << "27\t\t27\tSTORE_SIGNAL\t\t2\t3\t\t\"console.log(1921)\""
        << "28\t\t29\tSTORE_SCRIPT_STRING\t24\t3\t1"
        << "29\t\t30\tASSIGN_SIGNAL_OBJECT\t0\t\t\t\"mySignal\""
        << "30\t\t31\tASSIGN_CUSTOMTYPE\t25\t4"
        << "31\t\t32\tSTORE_BINDING\t26\t3\t2"
        << "32\t\t33\tSTORE_COMPILED_BINDING\t27\t2\t4"
        << "33\t\t34\tSTORE_VALUE_SOURCE\t29\t4"
        << "34\t\t35\tSTORE_VALUE_INTERCEPTOR\t30\t-4"
        << "35\t\t36\tBEGIN\t\t\t4"
        << "36\t\t38\tSTORE_OBJECT_QLIST"
        << "37\t\t39\tASSIGN_OBJECT_LIST"
        << "38\t\t40\tFETCH_ATTACHED\t\t23"
        << "39\t\t42\tFETCH_QLIST\t\t32"
        << "40\t\t43\tFETCH\t\t\t33"
        << "41\t\t44\tFETCH_VALUE\t\t34\t6\t7"
        << "42\t\t45\tPOP"
        << "43\t\t46\tPOP_QLIST"
        << "44\t\t47\tPOP_VALUE\t\t35\t8"
        << "45\t\t48\tDEFER\t\t\t7"
        << "46\t\tNA\tDEFER\t\t\t7"
        << "47\t\t48\tSTORE_IMPORTED_SCRIPT\t2"
        << "48\t\t50\tXXX UNKNOWN INSTRUCTION\t1234"
        << "49\t\t51\tSTORE_VARIANT_INTEGER\t\t32\t11"
        << "50\t\t52\tSTORE_VARIANT_DOUBLE\t\t19\t33.7"
        << "-------------------------------------------------------------------------------";

    messages = QStringList();
    QtMessageHandler old = qInstallMessageHandler(msgHandler);
    data->dumpInstructions();
    qInstallMessageHandler(old);

    QCOMPARE(messages.count(), expect.count());
    for (int ii = 0; ii < messages.count(); ++ii) {
        QCOMPARE(messages.at(ii), expect.at(ii));
    }

    data->release();
}
示例#12
0
int UIDnDHandler::dragStartInternal(const QStringList &lstFormats,
                                    Qt::DropAction defAction, Qt::DropActions actions)
{
    int rc = VINF_SUCCESS;

#ifdef VBOX_WITH_DRAG_AND_DROP_GH

    LogFlowFunc(("defAction=0x%x\n", defAction));
    LogFlowFunc(("Number of formats: %d\n", lstFormats.size()));
# ifdef DEBUG
    for (int i = 0; i < lstFormats.size(); i++)
        LogFlowFunc(("\tFormat %d: %s\n", i, lstFormats.at(i).toAscii().constData()));
# endif

# ifdef DEBUG_DND_QT
    QFile *pFileDebugQt = new QFile(DEBUG_DND_QT_LOGFILE);
    if (pFileDebugQt->open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
    {
        g_pStrmLogQt = new QTextStream(pFileDebugQt);

        qInstallMsgHandler(UIDnDHandler::debugOutputQt);
        qDebug("========================================================================");
    }
# endif

# ifdef RT_OS_WINDOWS

    UIDnDDropSource *pDropSource = new UIDnDDropSource(m_pParent);
    if (!pDropSource)
        return VERR_NO_MEMORY;
    UIDnDDataObject *pDataObject = new UIDnDDataObject(this, lstFormats);
    if (!pDataObject)
        return VERR_NO_MEMORY;

    DWORD dwOKEffects = DROPEFFECT_NONE;
    if (actions)
    {
        if (actions & Qt::CopyAction)
            dwOKEffects |= DROPEFFECT_COPY;
        if (actions & Qt::MoveAction)
            dwOKEffects |= DROPEFFECT_MOVE;
        if (actions & Qt::LinkAction)
            dwOKEffects |= DROPEFFECT_LINK;
    }

    DWORD dwEffect;
    LogRel2(("DnD: Starting drag and drop operation\n", dwOKEffects));
    LogRel3(("DnD: DoDragDrop dwOKEffects=0x%x\n", dwOKEffects));
    HRESULT hr = ::DoDragDrop(pDataObject, pDropSource, dwOKEffects, &dwEffect);
    LogRel3(("DnD: DoDragDrop ended with hr=%Rhrc, dwEffect=%RI32\n", hr, dwEffect));

    if (pDropSource)
        pDropSource->Release();
    if (pDataObject)
        pDataObject->Release();

# else /* !RT_OS_WINDOWS */

    QDrag *pDrag = new QDrag(m_pParent);
    if (!pDrag)
        return VERR_NO_MEMORY;

    /* Note: pMData is transferred to the QDrag object, so no need for deletion. */
    m_pMIMEData = new UIDnDMIMEData(this, lstFormats, defAction, actions);
    if (!m_pMIMEData)
    {
        delete pDrag;
        return VERR_NO_MEMORY;
    }

    /* Inform the MIME data object of any changes in the current action. */
    connect(pDrag, SIGNAL(actionChanged(Qt::DropAction)),
            m_pMIMEData, SLOT(sltDropActionChanged(Qt::DropAction)));

    /* Invoke this handler as data needs to be retrieved by our derived QMimeData class. */
    connect(m_pMIMEData, SIGNAL(sigGetData(Qt::DropAction, const QString&, QVariant::Type, QVariant&)),
            this, SLOT(sltGetData(Qt::DropAction, const QString&, QVariant::Type, QVariant&)));

    /*
     * Set MIME data object and start the (modal) drag'n drop operation on the host.
     * This does not block Qt's event loop, however (on Windows it would).
     */
    pDrag->setMimeData(m_pMIMEData);
    LogFlowFunc(("Executing modal drag'n drop operation ...\n"));

    Qt::DropAction dropAction;
#  ifdef RT_OS_DARWIN
#    ifdef VBOX_WITH_DRAG_AND_DROP_PROMISES
        dropAction = pDrag->exec(actions, defAction, true /* fUsePromises */);
#    else
        /* Without having VBOX_WITH_DRAG_AND_DROP_PROMISES enabled drag and drop
         * will not work on OS X! It also requires some handcrafted patches within Qt
         * (which also needs VBOX_WITH_DRAG_AND_DROP_PROMISES set there). */
        dropAction = Qt::IgnoreAction;
        rc = VERR_NOT_SUPPORTED;
#    endif
#  else /* !RT_OS_DARWIN */
    dropAction = pDrag->exec(actions, defAction);
#  endif /* RT_OS_DARWIN */
    LogRel3(("DnD: Ended with dropAction=%ld\n", UIDnDHandler::toVBoxDnDAction(dropAction)));

    /* Note: The UIDnDMimeData object will not be not accessible here anymore,
     *       since QDrag had its ownership and deleted it after the (blocking)
     *       QDrag::exec() call. */

    /* pDrag will be cleaned up by Qt automatically. */

# endif /* !RT_OS_WINDOWS */

    reset();

#ifdef DEBUG_DND_QT
    if (g_pStrmLogQt)
    {
        delete g_pStrmLogQt;
        g_pStrmLogQt = NULL;
    }

    if (pFileDebugQt)
    {
        pFileDebugQt->close();
        delete pFileDebugQt;
    }
#endif /* DEBUG_DND_QT */

#else /* !VBOX_WITH_DRAG_AND_DROP_GH */

    rc = VERR_NOT_SUPPORTED;

#endif /* VBOX_WITH_DRAG_AND_DROP_GH */

    LogFlowFuncLeaveRC(rc);
    return rc;
}
示例#13
0
/*!
 * \brief  功能概述 初始化通道参数
 * \param  参数描述 strChannelFileName_是通道文件绝对路径名,pDatabaseReturn是实时库指针
 * \return 返回值描述 成功返回true,失败返回false
 * \author zzy
 * \date   2015/5/27
 */
bool CProtocolBase::OnCreateChannel(const QString strChannelFileName_, CRTDBI *pDatabaseReturn)
{
    m_strChannelFileName = strChannelFileName_;
    CPRTI *pPRTI = m_pPRTMapI->FindChannelNumber(m_nChannelNumber);
    if (NULL != pPRTI)
    {
        pPRTI->SetDriverType(m_nPROTOCOL_TYPE);/// @note 设置驱动的类型 该驱动为转发驱动
    }
//    m_pPRTMapI->FindChannelNumber(m_nChannelNumber)->SetDriverType(m_nPROTOCOL_TYPE);/// @note 设置驱动的类型 该驱动为转发驱动
    m_pRTDB = pDatabaseReturn;/// @note 设置实时库指针

    QFile file(strChannelFileName_);
    QDomDocument ChannelDoc;
    if (!file.open(QFile::ReadOnly | QFile::Text))
    {
        return false;
    }
    QString errorStr;
    int errorLine;
    int errorColumn;
    if (!ChannelDoc.setContent(&file, false, &errorStr, &errorLine, &errorColumn))
    {
        qDebug()<<strChannelFileName_<<"XML File Error Message:"<<errorStr<<" Error Line:"<<errorLine<<" Error Column:"<<errorColumn;
        return false;
    }
    file.close();

    QDomElement docElem = ChannelDoc.documentElement();
    if (docElem.childNodes().count() != 5)///<zzy 2015/1/15 修改:
    {
        return false;
    }
    QDomElement Channel    = docElem.childNodes().at(0).toElement();
    QDomElement Top        = docElem.childNodes().at(1).toElement();
//    QDomElement Protocol   = docElem.childNodes().at(2).toElement();
    QDomElement MainPort   = docElem.childNodes().at(3).toElement();
//    QDomElement DeviceList = docElem.childNodes().at(4).toElement();
    QString strZTChannelNumber = Top.attribute("ZTChannelNumber");
    if (strZTChannelNumber.isEmpty())
    {
        m_nZTChannelNumber = -1;
    }else
    {
        m_nZTChannelNumber = strZTChannelNumber.toInt();/// @note 组态时设置的通道号
    }

    QStringList strListZTDeliversChannelNumberList = Top.attribute("NotifyNumber").split(",", QString::SkipEmptyParts);
    for (int i = 0; i < strListZTDeliversChannelNumberList.count(); ++i)
    {
        qDebug()<<m_nChannelNumber<<strListZTDeliversChannelNumberList.at(i).toInt()<<"===================";
        m_ZTDeliversChannelNumberList.push_back(strListZTDeliversChannelNumberList.at(i).toInt());
    }
    QString strChannelFileName2 = strChannelFileName_;

    /// @note 是否保存报文部分的处理
    if (Top.attribute("SaveFrame") == "True")
    {
        m_IsSaveFrame = true;
        QDir dir(strChannelFileName2);
        QString strFileName = dir.dirName();
        strFileName = strFileName.remove(".xml").append(".log");

        m_FileLog.setFileName(strFileName);
        if (!m_FileLog.open(QIODevice::ReadWrite|QIODevice::Text|QIODevice::Append))
        {
            qDebug()<<"未生成文件"<<strFileName;
        }else
        {
            qDebug()<<"生成文件了"<<strFileName;

        }
    }else
    {
        m_IsSaveFrame = false;
    }///是否保存报文部分的处理 end

//    InitPoint(DeviceList);
    QString strChannelName = tr("__")+Channel.attribute("Name").append("__");


    if (SetInitLink(Top,MainPort))
    {
        qDebug()<<"CLink Open succeed."<<m_pLink->GetLinkType()<<strChannelName;
    }else
    {
        qDebug()<<"CLink Open failed."<<m_pLink->GetLinkType()<<strChannelName;
    }
//#if defined(Q_PROCESSOR_ARM)
    m_pFrameSharedMemory = new CFrameSharedMemory(strChannelName,1024*30,this);
    m_bCreateStatusFrameSharedMemory = m_pFrameSharedMemory->CreateSharedMemory();
//#elif defined(Q_PROCESSOR_X86)

//#endif
    return true;
}
示例#14
0
bool CProtocolBase::OnCreateChannel(const QDomElement &ChannelElement_, ChannelType nChannelType_, int nComOrCanNumber_, CRTDBI *pDatabaseReturn_)
{
    CPRTI *pPRTI = m_pPRTMapI->FindChannelNumber(m_nChannelNumber);
    if (NULL != pPRTI)
    {
        pPRTI->SetDriverType(m_nPROTOCOL_TYPE);/// @note 设置驱动的类型 该驱动为转发驱动
    }
//    m_pPRTMapI->FindChannelNumber(m_nChannelNumber)->SetDriverType(m_nPROTOCOL_TYPE);/// @note 设置驱动的类型 该驱动为转发驱动
    m_pRTDB = pDatabaseReturn_;/// @note 设置实时库指针

    ChannelElement_.elementsByTagName("Top");
    if (ChannelElement_.elementsByTagName("Top").isEmpty())
    {
        return false;
    }

#if 0
    QDomElement docElem = ChannelDoc.documentElement();
    if (docElem.childNodes().count() != 5)///<zzy 2015/1/15 修改:
    {
        return false;
    }
    QDomElement Channel    = docElem.childNodes().at(0).toElement();
    QDomElement Top        = docElem.childNodes().at(1).toElement();
    QString strZTChannelNumber = Top.attribute("ZTChannelNumber");
    if (strZTChannelNumber.isEmpty())
    {
        m_nZTChannelNumber = -1;
    }else
    {
        m_nZTChannelNumber = strZTChannelNumber.toInt();/// @note 组态时设置的通道号
    }

    QStringList strListZTDeliversChannelNumberList = Top.attribute("NotifyNumber").split(",", QString::SkipEmptyParts);
    for (int i = 0; i < strListZTDeliversChannelNumberList.count(); ++i)
    {
        qDebug()<<m_nChannelNumber<<strListZTDeliversChannelNumberList.at(i).toInt()<<"===================";
        m_ZTDeliversChannelNumberList.push_back(strListZTDeliversChannelNumberList.at(i).toInt());
    }
#endif
#if 0
    QString strChannelFileName2 = strChannelFileName_;
    /// @note 是否保存报文部分的处理
    if (Top.attribute("SaveFrame") == "True")
    {
        m_IsSaveFrame = true;
        QDir dir(strChannelFileName2);
        QString strFileName = dir.dirName();
        strFileName = strFileName.remove(".xml").append(".log");

        m_FileLog.setFileName(strFileName);
        if (!m_FileLog.open(QIODevice::ReadWrite|QIODevice::Text|QIODevice::Append))
        {
            qDebug()<<"未生成文件"<<strFileName;
        }else
        {
            qDebug()<<"生成文件了"<<strFileName;

        }
    }else
    {
        m_IsSaveFrame = false;
    }///是否保存报文部分的处理 end
#endif
    ChannelElement_.elementsByTagName("MainPort");
    if (ChannelElement_.elementsByTagName("MainPort").isEmpty())
    {
        return false;
    }
    QDomElement MainPort   = ChannelElement_.elementsByTagName("MainPort").at(0).toElement();

    QString strChannelName;/// = tr("__")+Channel.attribute("Name").append("__");
    switch (nChannelType_)
    {
    case ChannelType_COM:
        MainPort.setAttribute("Name",QString("COM%1").arg(nComOrCanNumber_));
        strChannelName = tr("__")+MainPort.attribute("Name").append("__");
        break;
    case ChannelType_NET:
        if (ChannelElement_.tagName() != "Link")
        {
            return false;
        }
        MainPort = ChannelElement_;
        strChannelName = tr("__")+MainPort.attribute("Name").append("__");
        break;
    case ChannelType_CAN:
        MainPort.setAttribute("Name",QString("can%1").arg(nComOrCanNumber_-1));
        strChannelName = tr("__")+MainPort.attribute("Name").append("__");
        break;
    default:
        break;
    }
    if (SetInitLink(nChannelType_,MainPort))
    {
        qDebug()<<"CLink Open succeed."<<m_pLink->GetLinkType();
    }else
    {
        qDebug()<<"CLink Open failed."<<m_pLink->GetLinkType();
    }
//#if 0
    qDebug()<<__func__<<"SharedMemoryKey ="<<strChannelName;
    m_pFrameSharedMemory = new CFrameSharedMemory(strChannelName,1024*30,this);
    m_bCreateStatusFrameSharedMemory = m_pFrameSharedMemory->CreateSharedMemory();
//#endif
    return true;
}
示例#15
0
int main(int argc, char *argv[]) {
    int i_file, i_v, i_curve;
    int i_plot;
    QString fullPath;

    KAboutData aboutData("kst", I18N_NOOP("Kst"),
                         KSTVERSION, description, KAboutData::License_GPL,
                         I18N_NOOP("(c) 2000-2007 Barth Netterfield"),
                         0,
                         "http://kst.kde.org/");
    aboutData.addAuthor("Barth Netterfield",
                        I18N_NOOP("Original author and maintainer."),
                        "*****@*****.**",
                        "http://omega.astro.utoronto.ca/");
    aboutData.addAuthor("Staikos Computing Services Inc.",
                        I18N_NOOP("Developed for the University of Toronto."),
                        "*****@*****.**",
                        "http://www.staikos.net/");
    aboutData.addAuthor("Sumus Technology Limited",
                        I18N_NOOP("Developed for the University of British Columbia"),
                        "*****@*****.**",
                        "http://www.sumusltd.com/");
    aboutData.addAuthor("Rick Chern",
                        I18N_NOOP("University of British Columbia"),
                        "",
                        "");
    aboutData.addAuthor("Duncan Hanson",
                        I18N_NOOP("University of British Columbia"),
                        "",
                        "");
    aboutData.addAuthor("Nicolas Brisset",
                        "",
                        "",
                        "");
    aboutData.addAuthor("Matthew Truch",
                        "",
                        "http://matt.truch.net/",
                        "*****@*****.**");
    aboutData.addAuthor("Theodore Kisner",
                        "",
                        "*****@*****.**",
                        "");
    aboutData.setTranslator(I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"),
                            I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails"));

    KCmdLineArgs::init( argc, argv, &aboutData );
    KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.

    KApplication app;
    KImageIO::registerFormats();

    KstDialogs::replaceSelf(new KstGuiDialogs);
    KstData::replaceSelf(new KstGuiData);
    KstApp::initialize();

    atexit(exitHelper);

    if (app.isRestored()) {
        RESTORE(KstApp)
    } else {
        KstApp *kst = new KstApp;
        InType in;
        QColor color;
        QCStringList ycolList;
        QCStringList matrixList;
        QCStringList yEqList;
        QCStringList psdList;
        QCStringList hsList;
        QCStringList errorList;
        unsigned int i_ycol;
        QCStringList::Iterator hs_string;
        QCStringList::Iterator eq_i;
        QCStringList::Iterator mat_i;
        bool showQuickStart = false;
        bool showDataWizard = false;
        bool nOK;
        int n_y = 0;
        KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

        CheckForCMDErrors(args);

        QString wizardfile = args->getOption("w");
        QString printfile = args->getOption("print");
        QString pngfile = args->getOption("png");
        bool print_and_exit = false;

        if (printfile != "<none>") {
            print_and_exit = true;
        }
        if (pngfile != "<none>") {
            print_and_exit = true;
        }

        if (!print_and_exit) {
            app.setMainWidget(kst);
            QRect rect = KGlobalSettings::desktopGeometry(kst);
            kst->resize(5 * rect.width() / 6, 5 * rect.height() / 6);
            kst->show();
        }

        // get Y axis columns
        ycolList = args->getOptionList("y");
        matrixList = args->getOptionList("z");
        yEqList = args->getOptionList("ye");
        psdList = args->getOptionList("p");
        hsList = args->getOptionList("h");
        errorList = args->getOptionList("e");

        // y axis or PSD specified, so the files are data files, not kst files.
        n_y = ycolList.count() + psdList.count() + hsList.count() + yEqList.count() + matrixList.count();
        if (n_y > 0) {
            QString creatingEquations = i18n("Creating equations");
            QString creatingCurves = i18n("Creating curves");
            QString creatingPlots = i18n("Creating plots");
            int count;
            int handled;

            kst->slotUpdateProgress( 0, 0, QString::null );

            SetCMDOptions(args, in, n_y);

            KstTopLevelViewPtr tlv = kst->activeView();

            if (!tlv) {
                // if there was no active view then we create one...
                kst->newWindow(false);
                tlv = kst->activeView();
            }

            if (!tlv) {
                kstdError() << i18n("Can't create a view.") << endl;
                return 0;
            }

            CreatePlots(in, tlv);
            Kst2DPlotList plist = kstObjectSubList<KstViewObject, Kst2DPlot>(tlv->children());

            i_plot = 0;
            Kst2DPlotPtr plot = *plist.at(i_plot);

            KstVCurveList vcurves = kstObjectSubList<KstBaseCurve,KstVCurve>(plot->Curves);

            // make stand alone equations if there are no files
            if (args->count() < 1) {
                if (!yEqList.isEmpty()) {
                    QString eqS;
                    double max, min;
                    int n;
                    bool xeq;

                    SetEqXRanges(args->getOption("xe"), &min, &max, &n, &xeq);
                    if (xeq) {
                        count = yEqList.size();
                        handled = 0;
                        kst->slotUpdateProgress( count, handled, creatingEquations );

                        for (eq_i = yEqList.begin(); eq_i != yEqList.end(); ++eq_i) {
                            eqS = *eq_i;
                            if (NoVectorEq(eqS)) {
                                KstEquationPtr eq = new KstEquation(KST::suggestEQName(eqS), eqS, min, max, n);
                                KstVCurvePtr vc = new KstVCurve(KST::suggestCurveName(eq->tag(), true),
                                                                eq->vX(), eq->vY(), 0L, 0L, 0L, 0L,
                                                                KstColorSequence::next(vcurves,plot->backgroundColor()));
                                KST::dataObjectList.lock().writeLock();
                                KST::dataObjectList.append(eq.data());
                                KST::dataObjectList.append(vc.data());
                                KST::dataObjectList.lock().unlock();
                                plot->addCurve(vc.data());

                                if (in.sep_plots) {
                                    i_plot++;
                                    if (i_plot < in.n_plots) {
                                        plot = *plist.at(i_plot);
                                    }
                                }
                            }

                            handled++;
                            kst->slotUpdateProgress( count, handled, creatingEquations );
                        }
                    }
                }
            }

            // make the requested curves for each data file
            count = args->count();
            handled = 0;
            kst->slotUpdateProgress( count, handled, creatingCurves );

            for (i_curve = i_v = 0, i_file = 0; i_file < args->count(); i_file++) {
                // make the file
                if (QFile::exists(args->arg(i_file))) {
                    fullPath = QFileInfo(args->arg(i_file)).absFilePath();
                } else {
                    fullPath = args->arg(i_file);
                }

                KstDataSourcePtr file = KstDataSource::loadSource(fullPath);

                if (file) {
                    if (!file->isValid() || file->isEmpty()) {
                        kstdError() << i18n("No data in file %1.  Trying to continue...").arg(args->arg(i_file)) << endl;
                        // The file might get data later!
                    }

                    KST::dataObjectList.lock().writeLock();
                    KST::dataSourceList.append(file);
                    KST::dataObjectList.lock().unlock();

                    KstRVectorPtr yvector;
                    KstRVectorPtr evector;
                    KstVCurvePtr curve;
                    KstPSDPtr psd;
                    KstHistogramPtr hs;
                    KstRVectorPtr xvector;

                    if (!ycolList.isEmpty()) { // if there are some xy plots
                        // make the x axis vector
                        xvector = GetOrCreateVector(args->getOption("x"), file, in);
                        if (xvector) {
                            // make the y axis vectors
                            for (i_ycol = 0; i_ycol < ycolList.count(); ++i_ycol ) {
                                yvector = GetOrCreateVector(*(ycolList.at(i_ycol)), file, in);
                                if (yvector) {
                                    // make the curves
                                    color = KstColorSequence::next(vcurves,plot->backgroundColor());
                                    curve = new KstVCurve(KST::suggestCurveName(yvector->tag(), false),
                                                          KstVectorPtr(xvector), KstVectorPtr(yvector),
                                                          0L, 0L, 0L, 0L, color);
                                    if (in.has_points) {
                                        curve->setHasPoints(true);
                                        curve->setHasLines(false);
                                    }

                                    if (i_ycol<errorList.count()) {
                                        evector = GetOrCreateVector(*(errorList.at(i_ycol)), file, in);
                                        if (evector) {
                                            curve->setYError(KstVectorPtr(evector));
                                            curve->setYMinusError(KstVectorPtr(evector));
                                        }
                                    }

                                    KST::dataObjectList.lock().writeLock();
                                    KST::dataObjectList.append(curve.data());
                                    KST::dataObjectList.lock().unlock();
                                    plot->addCurve(curve.data());

                                    if (in.sep_plots) {
                                        plot->setTagName(curve->tag());
                                        i_plot++;
                                        if (i_plot < in.n_plots) {
                                            plot = *plist.at(i_plot);
                                        }
                                    } // end (if they are separate plots)
                                }
                            } // next y col
                        }
                    } // end (if there are some xy plots)

                    if (!yEqList.isEmpty()) {
                        QString eqS;
                        double max, min;
                        int n;
                        bool xeq, eq_ok;

                        SetEqXRanges(args->getOption("xe"), &min, &max, &n, &xeq);
                        for (eq_i = yEqList.begin(); eq_i != yEqList.end(); ++eq_i) {
                            KstEquationPtr eq;

                            eqS = *eq_i;
                            ProcessEq(eqS, file, in, &eq_ok);

                            if (xeq) {
                                eq = new KstEquation(KST::suggestEQName(eqS), eqS, min,max,n);
                            } else {
                                if (!xvector) {
                                    xvector = GetOrCreateVector(args->getOption("x"), file, in);
                                }
                                if (xvector) {
                                    eq = new KstEquation(KST::suggestEQName(eqS), eqS, KstVectorPtr(xvector), true);
                                }
                            }

                            if (eq) {
                                KstVCurvePtr vc = new KstVCurve(KST::suggestCurveName(eq->tag(), true),
                                                                eq->vX(), eq->vY(), 0L, 0L, 0L, 0L,
                                                                KstColorSequence::next(vcurves,plot->backgroundColor()));
                                KST::dataObjectList.lock().writeLock();
                                KST::dataObjectList.append(eq.data());
                                KST::dataObjectList.append(vc.data());
                                KST::dataObjectList.lock().unlock();
                                plot->addCurve(vc.data());

                                if (in.sep_plots) {
                                    plot->setTagName(eq->tag());
                                    i_plot++;
                                    if (i_plot <in.n_plots) {
                                        plot = *plist.at(i_plot);
                                    }
                                }
                            }
                        }
                    }

                    if (psdList.count() > 0) { // if there are some psd plots
                        KstRVectorList rvl = kstObjectSubList<KstVector,KstRVector>(KST::vectorList);
                        for (QCStringList::ConstIterator it = psdList.begin(); it != psdList.end(); ++it) {

                            yvector = GetOrCreateVector(*it, file, in);
                            if (yvector) {
                                color = KstColorSequence::next(vcurves,plot->backgroundColor());

                                psd = new KstPSD( KST::suggestPSDName(yvector->tag()), // FIXME: this was yvector->field(), is this right?
                                                  KstVectorPtr(yvector), in.rate, true, in.len,
                                                  true, true, in.VUnits, in.RUnits, WindowOriginal);
                                KstVCurvePtr vc = new KstVCurve(KST::suggestCurveName(psd->tag(), true),
                                                                psd->vX(), psd->vY(), 0L, 0L, 0L, 0L, color);
                                if (in.has_points) {
                                    vc->setHasPoints(true);
                                    vc->setHasLines(false);
                                }
                                KST::dataObjectList.lock().writeLock();
                                KST::dataObjectList.append(psd.data());
                                KST::dataObjectList.append(vc.data());
                                KST::dataObjectList.lock().unlock();
                                plot->addCurve(vc.data());

                                if (in.sep_plots) {
                                    plot->setTagName(psd->tag());
                                    i_plot++;
                                    if (i_plot <in.n_plots) {
                                        plot = *plist.at(i_plot);
                                    }
                                }
                            }
                        } // next psd
                    } // end (if there are some psds)

                    if (hsList.count() > 0) { // if there are some histograms
                        double max, min;
                        int N;

                        KstRVectorList rvl = kstObjectSubList<KstVector,KstRVector>(KST::vectorList);
                        for (hs_string = hsList.begin(); hs_string != hsList.end(); ++hs_string) {
                            yvector = GetOrCreateVector(*hs_string, file, in);
                            if (yvector) {
                                color = KstColorSequence::next(vcurves,plot->backgroundColor());

                                KstHistogram::AutoBin(KstVectorPtr(yvector), &N, &max, &min);

                                hs = new KstHistogram(KST::suggestHistogramName(yvector->tag()),
                                                      KstVectorPtr(yvector), min, max, N, KST_HS_NUMBER);
                                KstVCurvePtr vc = new KstVCurve(KST::suggestCurveName(hs->tag(), true),
                                                                hs->vX(), hs->vY(),
                                                                0L, 0L, 0L, 0L, color);

                                vc->setHasPoints(false);
                                vc->setHasLines(false);
                                vc->setHasBars(true);
                                vc->setBarStyle(1);

                                KST::dataObjectList.lock().writeLock();
                                KST::dataObjectList.append(hs.data());
                                KST::dataObjectList.append(vc.data());
                                KST::dataObjectList.lock().unlock();
                                plot->addCurve(vc.data());

                                if (in.sep_plots) {
                                    plot->setTagName(hs->tag());
                                    i_plot++;
                                    if (i_plot < in.n_plots) {
                                        plot = *plist.at(i_plot);
                                    }
                                }
                            }
                        } // next histogram
                    } // end (if there are some histograms)

                    if (matrixList.count() > 0) { // if there are some matrixes
                        for (mat_i = matrixList.begin(); mat_i != matrixList.end(); ++mat_i) {
                            QString tag_name = KST::suggestMatrixName(*mat_i);
                            if (!file->isValidMatrix(*mat_i)) {
                                startupErrors.append(i18n("Failed to create matrix '%1' from file '%2'.").arg(*mat_i).arg(file->fileName()));
                            }
                            KstRMatrixPtr matrix = new KstRMatrix(file, *mat_i,
                                                                  KstObjectTag(tag_name, file->tag()),
                                                                  0,0,-1,-1,false,false,0);
                            // xStart, yStart, xNumSteps, yNumSteps,
                            //doAve, doSkip, skip);

                            // Time to create the image from the matrix
                            tag_name = KST::suggestImageName(matrix->tag());
                            QStringList palList = KPalette::getPaletteList();
                            QString pal;
                            if (palList.contains("IDL 13 RAINBOW")) {
                                pal = QString("IDL 13 RAINBOW");
                            } else {
                                pal = QString(*palList.at(0));
                            }

                            KPalette* newPal = new KPalette(pal);
                            KstImagePtr image = new KstImage(tag_name, KstMatrixPtr(matrix), 0.0, 1.0,
                                                             true, newPal);
                            plot->addCurve(KstBaseCurvePtr(image));
                            KST::dataObjectList.lock().writeLock();
                            KST::dataObjectList.append(image.data());
                            KST::dataObjectList.lock().unlock();
                            image = 0L; // drop the reference

                            if (in.sep_plots) {
                                plot->setTagName(matrix->tag());
                                i_plot++;
                                if (i_plot < in.n_plots) {
                                    plot = *plist.at(i_plot);
                                }
                            }
                        }
                    }
                } else {
                    startupErrors.append(i18n("Failed to load file '%1'.").arg(args->arg(i_file)));
                }
                handled++;
                kst->slotUpdateProgress( count, handled, creatingCurves );
            } // next data file

            count = in.n_plots;
            handled = 0;
            kst->slotUpdateProgress( count, handled, creatingPlots );
            for (i_plot = 0; i_plot < in.n_plots; i_plot++) {
                plot = *plist.at(i_plot);
                plot->generateDefaultLabels();

                // if we have only images in a plot then set the scale mode to AUTO (instead of AUTOBORDER)
                KstImageList images = kstObjectSubList<KstBaseCurve,KstImage>(plot->Curves);
                if (images.count() == plot->Curves.count()) {
                    plot->setXScaleMode(AUTO);
                    plot->setYScaleMode(AUTO);
                }

                if (plot->Curves.count() > 3 || in.dolegend) {
                    KstViewLegendPtr vl = plot->getOrCreateLegend();
                    vl->resizeFromAspect(0.1, 0.1, 0.2, 0.1);
                    vl->setBorderWidth(2);
                }
                handled++;
                kst->slotUpdateProgress( count, handled, creatingPlots );
            }

            kst->slotUpdateProgress( 0, 0, QString::null );
        } else if (args->count() > 0) { // open a kst file
            // some of the options can be overridden
            kst->openDocumentFile(args->arg(0),
                                  args->getOption("F"),             // override FileName
                                  args->getOption("n").toInt(&nOK), // override number of frames
                                  args->getOption("f").toInt(&nOK), // override starting frame
                                  args->getOption("s").toInt(&nOK), // override skip
                                  args->isSet("a"),                 // add averaging
                                  !print_and_exit);                 // delayed
        } else {
            //kst->openDocumentFile();
            showQuickStart = true;
        }

        if (args->isSet("nq")) {
            showQuickStart = false;
        }
        if (args->isSet("w")) {
            showDataWizard = true;
            showQuickStart = false;
        }

        if (printfile != "<none>") {
            kst->forceUpdate();
            kst->immediatePrintToFile(printfile, false);
        }

        if (pngfile != "<none>") {
            kst->forceUpdate();
            kst->immediatePrintToPng(pngfile);
        }

        kst->document()->setModified(false);

        if (print_and_exit) {
            delete kst;
            return 0;
        } else {
            kst->updateDialogs();

            if (showQuickStart) {
                kst->showQuickStartDialog();
            }
            if (showDataWizard) {
                kst->showDataWizardWithFile(wizardfile);
            }
            for (size_t i = 0; i < startupErrors.size(); ++i) {
                KstDebug::self()->log(startupErrors[i], KstDebug::Error);
            }
            startupErrors.clear();
        }

        // LEAVE THIS HERE - causes crashes otherwise!
        int rc = app.exec();
        delete kst;
        return rc;
    }

    return app.exec();
}
示例#16
0
void beamtest::writebinary()
	{

QString filename = QFileDialog::getOpenFileName ( this,tr("Import File"),
												 "",tr( "All point cloud formats (*.ptx);;"
												 "XYZ (*.xyz *XYZ);;"
												 "PTX (*.ptx *.PTX)"));

double chunksize= 5000000;
int count =0;
int debugcount = 0;
char buf[1024];
QFile file(filename);
qint64 lineLength=0;
QStringList linelist;

QString filename2 = QFileDialog::getSaveFileName(this, tr("SaveBinary"), " ",tr("dat (*.dat "));
QFile file2(filename2);
 file2.open(QIODevice::WriteOnly);
 QDataStream out(&file2);   // we will serialize the data into the file


 if (file.open(QFile::ReadOnly)) {
        do {

    lineLength = file.readLine(buf, sizeof(buf));
    if (lineLength != -1) {
        QString line(buf);

        linelist = line.split(tr(" "));

        if (linelist.size() == 4)
        {
			
			double x = linelist.at(0).toDouble();
            double y = linelist.at(1).toDouble();
            double z = linelist.at(2).toDouble();
			if(x != 0 && y != 0 && z != 0 )
			{
			count++;

			if (count % 100000 == 0) qDebug() << count;

			out << x << y << z;
			}

        }

   //if (count > 10000) break;


    }
        }while (lineLength != -1);
 }



file2.close();






	}
bool QLinuxFbScreen::connect(const QString &displaySpec)
{
    d_ptr->displaySpec = displaySpec;

    const QStringList args = displaySpec.split(QLatin1Char(':'));

    if (args.contains(QLatin1String("nographicsmodeswitch")))
        d_ptr->doGraphicsMode = false;

#ifdef QT_QWS_DEPTH_GENERIC
    if (args.contains(QLatin1String("genericcolors")))
        d_ptr->doGenericColors = true;
#endif

    QRegExp ttyRegExp(QLatin1String("tty=(.*)"));
    if (args.indexOf(ttyRegExp) != -1)
        d_ptr->ttyDevice = ttyRegExp.cap(1);

#if Q_BYTE_ORDER == Q_BIG_ENDIAN
#ifndef QT_QWS_FRAMEBUFFER_LITTLE_ENDIAN
    if (args.contains(QLatin1String("littleendian")))
#endif
        QScreen::setFrameBufferLittleEndian(true);
#endif

    QString dev = QLatin1String("/dev/fb0");
    foreach(QString d, args) {
	if (d.startsWith(QLatin1Char('/'))) {
	    dev = d;
	    break;
	}
    }

    if (access(dev.toLatin1().constData(), R_OK|W_OK) == 0)
        d_ptr->fd = QT_OPEN(dev.toLatin1().constData(), O_RDWR);
    if (d_ptr->fd == -1) {
        if (QApplication::type() == QApplication::GuiServer) {
            perror("QScreenLinuxFb::connect");
            qCritical("Error opening framebuffer device %s", qPrintable(dev));
            return false;
        }
        if (access(dev.toLatin1().constData(), R_OK) == 0)
            d_ptr->fd = QT_OPEN(dev.toLatin1().constData(), O_RDONLY);
    }

    ::fb_fix_screeninfo finfo;
    ::fb_var_screeninfo vinfo;
    //#######################
    // Shut up Valgrind
    memset(&vinfo, 0, sizeof(vinfo));
    memset(&finfo, 0, sizeof(finfo));
    //#######################

    /* Get fixed screen information */
    if (d_ptr->fd != -1 && ioctl(d_ptr->fd, FBIOGET_FSCREENINFO, &finfo)) {
        perror("QLinuxFbScreen::connect");
        qWarning("Error reading fixed information");
        return false;
    }

    d_ptr->driverType = strcmp(finfo.id, "8TRACKFB") ? GenericDriver : EInk8Track;

    if (finfo.type == FB_TYPE_VGA_PLANES) {
        qWarning("VGA16 video mode not supported");
        return false;
    }

    /* Get variable screen information */
    if (d_ptr->fd != -1 && ioctl(d_ptr->fd, FBIOGET_VSCREENINFO, &vinfo)) {
        perror("QLinuxFbScreen::connect");
        qWarning("Error reading variable information");
        return false;
    }

    fixupScreenInfo(finfo, vinfo);

    grayscale = vinfo.grayscale;
    d = vinfo.bits_per_pixel;
    if (d == 24) {
        d = vinfo.red.length + vinfo.green.length + vinfo.blue.length;
        if (d <= 0)
            d = 24; // reset if color component lengths are not reported
    } else if (d == 16) {
        d = vinfo.red.length + vinfo.green.length + vinfo.blue.length;
        if (d <= 0)
            d = 16;
    }
    lstep = finfo.line_length;

    int xoff = vinfo.xoffset;
    int yoff = vinfo.yoffset;
    const char* qwssize;
    if((qwssize=::getenv("QWS_SIZE")) && sscanf(qwssize,"%dx%d",&w,&h)==2) {
        if (d_ptr->fd != -1) {
            if ((uint)w > vinfo.xres) w = vinfo.xres;
            if ((uint)h > vinfo.yres) h = vinfo.yres;
        }
        dw=w;
        dh=h;
        int xxoff, yyoff;
        if (sscanf(qwssize, "%*dx%*d+%d+%d", &xxoff, &yyoff) == 2) {
            if (xxoff < 0 || xxoff + w > vinfo.xres)
                xxoff = vinfo.xres - w;
            if (yyoff < 0 || yyoff + h > vinfo.yres)
                yyoff = vinfo.yres - h;
            xoff += xxoff;
            yoff += yyoff;
        } else {
            xoff += (vinfo.xres - w)/2;
            yoff += (vinfo.yres - h)/2;
        }
    } else {
        dw=w=vinfo.xres;
        dh=h=vinfo.yres;
    }

    if (w == 0 || h == 0) {
        qWarning("QScreenLinuxFb::connect(): Unable to find screen geometry, "
                 "will use 320x240.");
        dw = w = 320;
        dh = h = 240;
    }

    setPixelFormat(vinfo);

    // Handle display physical size spec.
    QStringList displayArgs = displaySpec.split(QLatin1Char(':'));
    QRegExp mmWidthRx(QLatin1String("mmWidth=?(\\d+)"));
    int dimIdxW = displayArgs.indexOf(mmWidthRx);
    QRegExp mmHeightRx(QLatin1String("mmHeight=?(\\d+)"));
    int dimIdxH = displayArgs.indexOf(mmHeightRx);
    if (dimIdxW >= 0) {
        mmWidthRx.exactMatch(displayArgs.at(dimIdxW));
        physWidth = mmWidthRx.cap(1).toInt();
        if (dimIdxH < 0)
            physHeight = dh*physWidth/dw;
    }
    if (dimIdxH >= 0) {
        mmHeightRx.exactMatch(displayArgs.at(dimIdxH));
        physHeight = mmHeightRx.cap(1).toInt();
        if (dimIdxW < 0)
            physWidth = dw*physHeight/dh;
    }
    if (dimIdxW < 0 && dimIdxH < 0) {
        if (vinfo.width != 0 && vinfo.height != 0
            && vinfo.width != UINT_MAX && vinfo.height != UINT_MAX) {
            physWidth = vinfo.width;
            physHeight = vinfo.height;
        } else {
            const int dpi = 72;
            physWidth = qRound(dw * 25.4 / dpi);
            physHeight = qRound(dh * 25.4 / dpi);
        }
    }

    dataoffset = yoff * lstep + xoff * d / 8;
    //qDebug("Using %dx%dx%d screen",w,h,d);

    /* Figure out the size of the screen in bytes */
    size = h * lstep;

    mapsize = finfo.smem_len;

    data = (unsigned char *)-1;
    if (d_ptr->fd != -1)
        data = (unsigned char *)mmap(0, mapsize, PROT_READ | PROT_WRITE,
                                     MAP_SHARED, d_ptr->fd, 0);

    if ((long)data == -1) {
        if (QApplication::type() == QApplication::GuiServer) {
            perror("QLinuxFbScreen::connect");
            qWarning("Error: failed to map framebuffer device to memory.");
            return false;
        }
        data = 0;
    } else {
        data += dataoffset;
    }

    canaccel = useOffscreen();
    if(canaccel)
        setupOffScreen();

    // Now read in palette
    if((vinfo.bits_per_pixel==8) || (vinfo.bits_per_pixel==4)) {
        screencols= (vinfo.bits_per_pixel==8) ? 256 : 16;
        int loopc;
        ::fb_cmap startcmap;
        startcmap.start=0;
        startcmap.len=screencols;
        startcmap.red=(unsigned short int *)
                 malloc(sizeof(unsigned short int)*screencols);
        startcmap.green=(unsigned short int *)
                   malloc(sizeof(unsigned short int)*screencols);
        startcmap.blue=(unsigned short int *)
                  malloc(sizeof(unsigned short int)*screencols);
        startcmap.transp=(unsigned short int *)
                    malloc(sizeof(unsigned short int)*screencols);
        if (d_ptr->fd == -1 || ioctl(d_ptr->fd, FBIOGETCMAP, &startcmap)) {
            perror("QLinuxFbScreen::connect");
            qWarning("Error reading palette from framebuffer, using default palette");
            createPalette(startcmap, vinfo, finfo);
        }
        int bits_used = 0;
        for(loopc=0;loopc<screencols;loopc++) {
            screenclut[loopc]=qRgb(startcmap.red[loopc] >> 8,
                                   startcmap.green[loopc] >> 8,
                                   startcmap.blue[loopc] >> 8);
            bits_used |= startcmap.red[loopc]
                         | startcmap.green[loopc]
                         | startcmap.blue[loopc];
        }
        // WORKAROUND: Some framebuffer drivers only return 8 bit
        // color values, so we need to not bit shift them..
        if ((bits_used & 0x00ff) && !(bits_used & 0xff00)) {
            for(loopc=0;loopc<screencols;loopc++) {
                screenclut[loopc] = qRgb(startcmap.red[loopc],
                                         startcmap.green[loopc],
                                         startcmap.blue[loopc]);
            }
            qWarning("8 bits cmap returned due to faulty FB driver, colors corrected");
        }
        free(startcmap.red);
        free(startcmap.green);
        free(startcmap.blue);
        free(startcmap.transp);
    } else {
示例#18
0
void beamtest::readfile1()
{



QString filename = QFileDialog::getOpenFileName ( this,
                                                                                         tr("Import File"),
                                                                                        "",
                                                                                         tr( "All point cloud formats (*.ptx);;"
                                                                                             "XYZ (*.xyz *XYZ);;"
                                                                                       "PTX (*.ptx *.PTX)"));


int count =0;
int debugcount = 0;
char buf[1024];
QFile file(filename);
qint64 lineLength=0;
QStringList linelist;
double x,y,z;
TopoDS_Shape point;

QString filename2 = QFileDialog::getSaveFileName(this, tr("SaveTopology"), " ",tr("csv (*.csv "));

        QFile file2(filename2);
        if (!file2.open(QIODevice::WriteOnly | QIODevice::Text))
    return;





 if (file.open(QFile::ReadOnly)) {
        do {

    lineLength = file.readLine(buf, sizeof(buf));
    if (lineLength != -1) {
        QString line(buf);


                //qDebug() << line;

        linelist = line.split(tr(" "));

        if (linelist.size() == 4)
        {
           count++;
               debugcount++;
               if (debugcount > 100000){ qDebug() << count << ","  << line; debugcount = 0;}

               QString index = linelist.at(0) + "," + linelist.at(1) + "," +
linelist.at(2) +"\n" ;
               file2.write(index.toAscii().data());
               //x = linelist.at(0).toDouble();
               //y = linelist.at(1).toDouble();
               //z = linelist.at(2).toDouble();
               //
               ////QString index = linelist.at(0) + linelist.at(1) + linelist.at(2) ;

               ////double intensity = linelist.at(3).toDouble();

               //point =hsf::AddNewPoint(gp_Pnt(x,y,z));
               //vis(point)





        }

       // if (count > 10000) {file2.close(); break;}




    }
        }while (lineLength != -1);
 }



file2.close();






}
示例#19
0
void Optimization::createSubExecs(QList<QList<ModModelPlus*> > & subModels, QList<BlockSubstitutions*> & subBlocks)
{

    subModels.clear();
    subBlocks.clear();

    QMultiMap<QString,QString> map; // <orgComponent,subcomponent>
    QMap<QString,QString> mapModel; //<orgComponent,model>
    // fill map
    for(int i=0; i < _blockSubstitutions->getSize();i++)
    {
        BlockSubstitution *curBlockSub = _blockSubstitutions->getAt(i);
        if(!curBlockSub->_subComponent.isEmpty())
        {
            map.insert(curBlockSub->_orgComponent,curBlockSub->_subComponent);
            mapModel.insert(curBlockSub->_orgComponent,curBlockSub->_model);
        }
    }

    int nbOrgs = map.uniqueKeys().size();
    //adding non-moving cases for each orgComponent
    for(int i = 0; i<nbOrgs; i ++)
    {
        map.insert(map.uniqueKeys().at(i),map.uniqueKeys().at(i));
    }


    //build first index and maximum index
    QList<int> index, maxIndex;
    nbOrgs = map.uniqueKeys().size();
    for(int i = 0; i<nbOrgs; i ++)
    {
        index.push_back(0);
        QList<QString> subs = map.values(map.uniqueKeys().at(i));
        maxIndex.push_back(subs.size()-1);
    }


    QStringList models = mapModel.values();
    models.removeDuplicates();



    // storing genuine mo file paths
    QStringList oldMoFilePaths;
    for(int iM=0;iM<models.size();iM++)
    {
        oldMoFilePaths.push_back(_omProject->modModelPlus(models.at(iM))->moFilePath());
    }



    int iCase=0;
    bool oneChange;
    while(!index.isEmpty())
    {


        // Display case (for debug)
        QString msg = "CASE " + QString::number(iCase) + "\n";
        for(int i=0; i < index.size(); i++)
        {
            msg += map.uniqueKeys().at(i);
            msg += " -> ";
            msg += map.values(map.uniqueKeys().at(i)).at(index.at(i));
            msg+=",";
        }
        msg.remove(msg.size()-1,1);
        msg +="\n \n";
        InfoSender::instance()->debug(msg);


        // create folder
        QString newName = "case_"+QString::number(iCase);
        QString newFolder = saveFolder()+ QDir::separator() + "SubModels" + QDir::separator() + newName;
        QDir dir(saveFolder());
        dir.mkpath(newFolder);
        QDir newDir(newFolder);


        // clone mo files and load them
        // and create corresponding modmodelplus
        QStringList newMoPaths;
        QStringList newMmoPaths;
        QMap<QString,ModModelPlus*> newModModels;
        for(int iM=0;iM<oldMoFilePaths.size();iM++)
        {
            QFileInfo oldMoFileInfo(oldMoFilePaths.at(iM));
            QFile oldMoFile(oldMoFilePaths.at(iM));

            QString newMoPath = newDir.filePath(oldMoFileInfo.fileName());
            QString newMmoPath = newMoPath;
            newMmoPath = newMmoPath.replace(".mo",".mmo");

            newDir.remove(newMoPath);
            oldMoFile.copy(newMoPath);

            newMoPaths.append(newMoPath);
            newMmoPaths.append(newMmoPath);


            // load file (! will replace previously loaded)
            _omProject->loadMoFile(newMoPath,false,true);

            // create new modModelPlus
            ModModelPlus* newModModelPlus = new ModModelPlus(_omProject,models.at(iM));
            newModModelPlus->setMmoFilePath(newMmoPath);
            newModModels.insert(models.at(iM),newModModelPlus);
        }


        // apply blocksubs
        BlockSubstitutions *curSubBlocks = new BlockSubstitutions();

        QMap<QString,bool> changes; // <model,hasChanged>
        changes.clear();
        for(int i=0; i<index.size();i++)
        {
            QString replacedComp = map.uniqueKeys().at(i);
            QString replacingComp = map.values(map.uniqueKeys().at(i)).at(index.at(i));

            if(replacedComp != replacingComp)
            {
                BlockSubstitution* blockSub = _blockSubstitutions->find(replacedComp,replacingComp);
                if(blockSub)
                {
                    ModModelPlus* corrNewModModelPlus = newModModels.value(blockSub->_model);
                    oneChange =  corrNewModModelPlus->applyBlockSub(blockSub,true) || oneChange ;
                    curSubBlocks->push_back(blockSub);
                    changes.insert(blockSub->_model,true);
                }
            }
        }

        QStringList modelsToCompile = changes.keys(true);// those which have been modified
        bool compilationOk = true;
        for(int iM=0;iM<modelsToCompile.size();iM++)
        {
            ModModelPlus* modelPlus = newModModels.value(modelsToCompile.at(iM));
            compilationOk = modelPlus->compile(ctrl(modelsToCompile.at(iM))) && compilationOk;
        }

        if(compilationOk)
        {

            // store subModel and subBlocks
            subModels.push_back(newModModels.values());
            subBlocks.push_back(curSubBlocks);
            _foldersToCopy << newFolder;

            InfoSender::instance()->send( Info(ListInfo::SUBMODELADDED,newName));
        }
        else
        {
            InfoSender::instance()->send( Info(ListInfo::SUBMODELNOTADDED,newName));
        }


        iCase++;
        index = LowTools::nextIndex(index,maxIndex);
    }

    // reload genuine mo file
    if(iCase>0)
    {
        for(int i=0;i<oldMoFilePaths.size();i++)
            _omProject->loadMoFile(oldMoFilePaths.at(i),false,true);
    }
}
示例#20
0
void QWeekDisplaytextDlg::DoubleClickInit(QGraphicsItem *pItem)
{
    QStringList datalist;
    QString sTmp;
    int i = 0;
    int nTemp = 0;
    int index = 20;
    QColor mColor;

    if(pItem)
    {
        InitFlag = false;
        datalist = pItem->data(GROUP_DATALIST_KEY).toStringList();
        on_m_languagecmb_currentIndexChanged(0);
        nCurrentIndex  = datalist.at(190).toInt(); //当前状态
        for(i = 0; i < 7;i++)
        {
            TextProperty[i].sColor = datalist.at(index+i*4);   //字体颜色

            sTmp = datalist.at(index+1+i*4);
            TextProperty[i].nWordInterval = sTmp.toInt();//字距

            sTmp = datalist.at(index+2+i*4);
            TextProperty[i].nPosition = sTmp.toInt();   //文本位置

            sTmp = datalist.at(index+3+i*4);
            TextProperty[i].bIfFlick = sTmp.toInt();    //是否闪烁
        }

        nTemp = index+28;
        for(i = 0; i < 7;i++)
        {
            for(int j = 0; j < 5; j++)
            {
                sTmp = datalist.at(nTemp);
                TextProperty[i].nFontSize[j] = sTmp.toInt();  //字体大小
                nTemp++;

                TextProperty[i].sText[j] = datalist.at(nTemp);//文本
                nTemp++;

                TextProperty[i].sFont[j] = datalist.at(nTemp);//字体
                nTemp++;
            }
        }

        ui->m_check->setChecked(datalist.at(nTemp).toInt());
        on_m_check_clicked(datalist.at(nTemp).toInt());

        nTemp++;
        ui->checkBox->setChecked(datalist.at(nTemp).toInt());
        if(datalist.at(nTemp).toInt())
            ui->groupBox_3->setEnabled(false);
        else
            ui->groupBox_3->setEnabled(true);


        sTmp = QString("%1").arg(TextProperty[nCurrentIndex].nFontSize[0]);
        nTemp = ui->m_fontsizecmb->findText(sTmp);
        if(nTemp != -1)
            ui->m_fontsizecmb->setCurrentIndex(nTemp);                  //设置字体大小

        sTmp = TextProperty[nCurrentIndex].sFont[0];
        nTemp = ui->m_fontcmb->findText(sTmp);
        if(nTemp != -1)
            ui->m_fontcmb->setCurrentIndex(nTemp);

        mColor = pwnd->StringTOColor(TextProperty[nCurrentIndex].sColor);
        ui->Text_Color->setStyleSheet( QString("background:%1").arg(mColor.name()));

        ui->m_flickcheck->setCurrentIndex(TextProperty[nCurrentIndex].bIfFlick);

        ui->m_wordintervalspin->setValue(TextProperty[nCurrentIndex].nWordInterval);

        ui->m_radio1->setChecked(false); //nCurrentIndex
        ui->m_radio2->setChecked(false);
        ui->m_radio3->setChecked(false);
        ui->m_radio4->setChecked(false);
        ui->m_radio5->setChecked(false);
        ui->m_radio6->setChecked(false);
        ui->m_radio7->setChecked(false);
        ui->m_radio8->setChecked(false);
        ui->m_radio9->setChecked(false);

        switch(TextProperty[nCurrentIndex].nPosition)                    //文本位置
        {
            case 1:ui->m_radio1->setChecked(true);break;
            case 2:ui->m_radio2->setChecked(true);break;
            case 3:ui->m_radio3->setChecked(true);break;
            case 4:ui->m_radio4->setChecked(true);break;
            case 5:ui->m_radio5->setChecked(true);break;
            case 6:ui->m_radio6->setChecked(true);break;
            case 7:ui->m_radio7->setChecked(true);break;
            case 8:ui->m_radio8->setChecked(true);break;
            case 9:ui->m_radio9->setChecked(true);break;
            default:ui->m_radio5->setChecked(true);break;
        }

        for(i = 0; i < 7; i++)
        {
            ui->m_table->setItem(i,1,new QTableWidgetItem(TextProperty[i].sText[0]));
        }

        QTableWidgetItem *mItem;                     //设置指定项为选中状态
        mItem = ui->m_table->item(nCurrentIndex,0);
        ui->m_table->setItemSelected(mItem,true);

        InitFlag = true;
    }
}
void Qtilities::Testing::TestSubjectIterator::testIterationComplex() {
    TreeNode node;
    TreeNode* nodeA = node.addNode("A");
    TreeNode* nodeB = node.addNode("B");
    nodeA->addItem("1");
    TreeItem* shared_item = nodeA->addItem("2");
    nodeA->addItem("3");
    nodeB->addItem("4");
    nodeB->addItem("5");
    nodeB->attachSubject(shared_item);
    nodeB->addItem("6");

    // If we want to iterate through the subjects in nodeA:
    SubjectIterator<QObject> itrA(nodeA,SubjectIterator<QObject>::IterateChildren);
    QVERIFY(itrA.current() != 0);

    // In this case item1 will be skipped:
    QStringList testListA;
    testListA << itrA.current()->objectName();
    while (itrA.hasNext()) {
        testListA << itrA.next()->objectName();
    }

    QVERIFY(testListA.count() == 3);
    QVERIFY(testListA.at(0).compare("1") == 0);
    QVERIFY(testListA.at(1).compare("2") == 0);
    QVERIFY(testListA.at(2).compare("3") == 0);

    // If we want to iterate through the subjects in nodeB:
    SubjectIterator<QObject> itrB(nodeB,SubjectIterator<QObject>::IterateChildren);

    // In this case item1 will be skipped:
    QStringList testListB;
    testListB << itrB.current()->objectName();
    while (itrB.hasNext()) {
        testListB << itrB.next()->objectName();
    }

    QVERIFY(testListB.count() == 4);
    QVERIFY(testListB.at(0).compare("4") == 0);
    QVERIFY(testListB.at(1).compare("5") == 0);
    QVERIFY(testListB.at(2).compare("2") == 0);
    QVERIFY(testListB.at(3).compare("6") == 0);

    // If we want to iterate through the subjects in nodeB:
    SubjectIterator<QObject> itrC(shared_item,nodeB);

    // In this case item1 will be skipped:
    QStringList testListC;
    testListC << itrC.current()->objectName();
    while (itrC.hasNext()) {
        testListC << itrC.next()->objectName();
    }

    QVERIFY(testListC.count() == 2);
    QVERIFY(testListC.at(0).compare("2") == 0);
    QVERIFY(testListC.at(1).compare("6") == 0);

    // If we want to iterate through the subjects in nodeB:
    SubjectIterator<QObject> itrD(shared_item,nodeA);

    // In this case item1 will be skipped:
    QStringList testListD;
    testListD << itrD.current()->objectName();
    while (itrD.hasNext()) {
        testListD << itrD.next()->objectName();
    }

    QVERIFY(testListD.count() == 2);
    QVERIFY(testListD.at(0).compare("2") == 0);
    QVERIFY(testListD.at(1).compare("3") == 0);
}
示例#22
0
void QgsBrowserDockWidget::itemClicked( const QModelIndex& index )
{
  QgsDataItem *item = mModel->dataItem( index );
  if ( !item )
    return;

  QgsLayerItem *layerItem = qobject_cast<QgsLayerItem*>( mModel->dataItem( index ) );
  if ( layerItem == NULL )
    return;

  QString uri = layerItem->uri();
  if ( uri.isEmpty() )
    return;

  QgsMapLayer::LayerType type = layerItem->mapLayerType();
  QString providerKey = layerItem->providerKey();

  QgsDebugMsg( providerKey + " : " + uri );
  QgsMapLayer* layer = NULL;
  if ( type == QgsMapLayer::VectorLayer )
  {
    layer = new QgsVectorLayer( uri, layerItem->name(), providerKey );
  }
  if ( type == QgsMapLayer::RasterLayer )
  {
    // This should go to WMS provider
    QStringList URIParts = uri.split( "|" );
    QString rasterLayerPath = URIParts.at( 0 );
    QStringList layers;
    QStringList styles;
    QString format;
    QString crs;
    for ( int i = 1 ; i < URIParts.size(); i++ )
    {
      QString part = URIParts.at( i );
      int pos = part.indexOf( "=" );
      QString field = part.left( pos );
      QString value = part.mid( pos + 1 );

      if ( field == "layers" )
        layers = value.split( "," );
      if ( field == "styles" )
        styles = value.split( "," );
      if ( field == "format" )
        format = value;
      if ( field == "crs" )
        crs = value;
    }
    QgsDebugMsg( "rasterLayerPath = " + rasterLayerPath );
    QgsDebugMsg( "layers = " + layers.join( " " ) );

    layer = new QgsRasterLayer( 0, rasterLayerPath, layerItem->name(), providerKey, layers, styles, format, crs );
  }

  if ( !layer || !layer->isValid() )
  {
    qDebug( "No layer" );
    delete layer;
    return;
  }

  // add layer to the application
  QgsMapLayerRegistry::instance()->addMapLayer( layer );
}
示例#23
0
About::About(QWidget *parent, QString language) : QDialog(parent)
{
	_language = language;
	// Setup UI:
	setupUi(this);
#ifdef SMALL_RESOLUTION
	// https://bugreports.qt.io/browse/QTBUG-16034
	// Workaround for window not showing always fullscreen
	setWindowFlags( Qt::Window );
#endif
	// Display title/program version:
	progversion_label->setText(progversion_label->text() + " " + QApplication::applicationVersion());
	// Load licence text and changelog:
	QFile changelog_file;
	if (language == "de")
		changelog_file.setFileName(":/changelog_de.txt");
	else
		changelog_file.setFileName(":/changelog_en.txt");
	changelog_file.open(QIODevice::ReadOnly | QIODevice::Text);
	QString changelog_content = static_cast<QString>(changelog_file.readAll());
	changelog_textBrowser->setText(changelog_content);
	changelog_file.close();
	// *** Definitions:
	SSMprotocol2_def_en ssmp_defs;
	// Display number of supported DTCs:
	int nrofDTCs_SUB = ssmp_defs.SUBDTCrawDefs().size();
	int nrofDTCs_OBD = ssmp_defs.OBDDTCrawDefs().size();
	int nrofDTCs_CC = ssmp_defs.CCCCrawDefs().size();
	QString dtcstr = QString::number( nrofDTCs_SUB ) + " / " + QString::number( nrofDTCs_OBD ) + " / " + QString::number( nrofDTCs_CC );
	nrofsupportedDTCs_label->setText( dtcstr );
	// Display number of supported measuring blocks / switches:
	int nrofMBs = ssmp_defs.MBrawDefs().size();
	int nrofSWs = ssmp_defs.SWrawDefs().size();
	QString mbswstr = QString::number( nrofMBs ) + " / " + QString::number( nrofSWs );
	nrofsupportedMBsSWs_label->setText( mbswstr );
	// Display number of supported Adjustment values:
	int ecu_adjustments = 0;
	int tcu_adjustments = 0;
	QStringList adjustmentdefs = ssmp_defs.AdjustmentRawDefs();
	for (int k=0; k< adjustmentdefs.size(); k++)
	{
		if (adjustmentdefs.at(k).section(';', 1, 1).toInt() == 0)
		{
			ecu_adjustments++;
		}
		else if (adjustmentdefs.at(k).section(';', 1, 1).toInt() == 1)
		{
			tcu_adjustments++;
		}
	}
	QString adjustmentsstr = QString::number( ecu_adjustments ) + " / " + QString::number( tcu_adjustments );
	nrofadjustmentvalues_label->setText( adjustmentsstr );
	// Display number of supported system tests:
	int nrofSysTests = ssmp_defs.ActuatorRawDefs().size();
	QString systestsstr = QString::number( nrofSysTests ) + " / 1";
	nrofActuatortests_label->setText(systestsstr);
	// Display supported program languages:
	QString langstr;
	for (int k=0; k<__supportedLocales.size(); k++)
	{
		QLocale locale = __supportedLocales.at(k);
		QString langname = QLocale::languageToString( locale.language() );
		QString langname_tr = QCoreApplication::translate( "Language", langname.toUtf8() );
		if (k > 0)
			langstr.append(", ");
		langstr.append(langname_tr);
	}
	languages_label->setText( langstr );
	// Connect buttons:
	connect( showlicense_pushButton, SIGNAL( released() ), this, SLOT( showLicense() ) );
	connect( close_pushButton, SIGNAL( released() ), this, SLOT( close() ) );
}
示例#24
0
void PropertyEditorModel::setModelIndexes(const QModelIndex &logicalModelIndex
		, const QModelIndex &graphicalModelIndex)
{
	beginResetModel();
	mField.reset(new Field());
	endResetModel();

	mTargetLogicalObject = logicalModelIndex;
	mTargetGraphicalObject = graphicalModelIndex;

	if (!isValid()) {
		return;
	}

	const Id logicalId = mTargetLogicalObject.data(roles::idRole).value<Id>();
	const QString dynamicProperties = dynamic_cast<models::details::LogicalModel *>(mTargetLogicalModel)->
			logicalModelAssistApi().logicalRepoApi().stringProperty(logicalId, "dynamicProperties");

	if (logicalModelIndex != QModelIndex()) {
		const QStringList logicalProperties = mEditorManagerInterface.propertyNames(logicalId.type());

		int role = roles::customPropertiesBeginRole;
		QStringList cloneWithRoles;
		QStringList cloneWithPure;

		for (const QString &prop : logicalProperties) {
			if (prop.contains("!")) {
				cloneWithRoles.append(prop);
			} else {
				cloneWithPure.append(prop);
			}
		}

		int i = 0;
		role = roles::customPropertiesBeginRole;
		while (cloneWithRoles.size() > 0) {
			const QString roleName = cloneWithRoles.takeAt(0);
			const int first = roleName.indexOf("!");
			const QString beginPartName = roleName.mid(0, first);
			mField->appendChild(new Field(beginPartName));
			auto parent = mField->child(i);

			QString endPartName = roleName.mid(first + 1);
			mField->appendChild(
					new Field(
							endPartName
							, logicalAttribute
							, role
							, parent
							, mTargetLogicalObject
							, mTargetGraphicalObject)
						);
			++i;
			++role;

			int j = 0;
			while (j < cloneWithRoles.size()) {
				if (cloneWithRoles.at(j).mid(0, first) == beginPartName) {
					QString roleName = cloneWithRoles.takeAt(j);
					roleName = roleName.mid(first + 1);
					mField->appendChild(
							new Field(
									roleName
									, logicalAttribute
									, role
									, parent
									, mTargetLogicalObject
									, mTargetGraphicalObject)
								);
					++i;
					++role;
					j = 0;
				} else {
					++j;
				}
			}

			++i;
		}

		while (cloneWithPure.size()  > 0) {
			QString roleName = cloneWithPure.takeAt(0);
			mField->appendChild(
					new Field(
							roleName
							, logicalAttribute
							, role
							, nullptr
							, mTargetLogicalObject
							, mTargetGraphicalObject)
						);
			++i;
			++role;
		}

		if (!dynamicProperties.isEmpty()) {
			QDomDocument dynamProperties;
			dynamProperties.setContent(dynamicProperties);
			for (QDomElement element = dynamProperties.firstChildElement("properties").firstChildElement("property")
					; !element.isNull()
					; element = element.nextSiblingElement("property"))
			{
				mField->appendChild(
						new Field(
								element.attribute("displayedName")
								, logicalAttribute
								, role
								, nullptr
								, mTargetLogicalObject
								, mTargetGraphicalObject));
				++role;
			}
		}

		/*
		 * Uncomment to display block Ids in a property editor
		 *
		mField->appendChild(
				new Field(
						"logicalId"
						, logicalAttribute
						, roles::idRole
						, nullptr
						, mTargetLogicalObject
						, mTargetGraphicalObject
				)
		);

		mField->appendChild(
				new Field(
						"graphicalId"
						, graphicalAttribute
						, roles::idRole
						, nullptr
						, mTargetLogicalObject
						, mTargetGraphicalObject
				)
		);
		/**/
	}

	beginResetModel();
	endResetModel();
}
示例#25
0
bool CategoryServer::handleRequest(QHttpRequest *request, QHttpResponse *response) {
    const QStringList parts = request->path().split("/", QString::SkipEmptyParts);
    
    if ((parts.isEmpty()) || (parts.size() > 2) || (parts.first() != "categories")) {
        return false;
    }

    if (parts.size() == 1) {
        if (request->method() == QHttpRequest::HTTP_GET) {
            writeResponse(response, QHttpResponse::STATUS_OK, QtJson::Json::serialize(Qdl::getCategories()));
            return true;
        }

        if (request->method() == QHttpRequest::HTTP_POST) {
            const QVariantMap properties = QtJson::Json::parse(request->body()).toMap();
            const QString name = properties.value("name").toString();
            const QString path = properties.value("path").toString();

            if ((name.isEmpty()) || (path.isEmpty()) || (!Qdl::addCategory(name, path))) {
                writeResponse(response, QHttpResponse::STATUS_BAD_REQUEST);
            }
            else {
                writeResponse(response, QHttpResponse::STATUS_CREATED);
            }

            return true;
        }

        writeResponse(response, QHttpResponse::STATUS_METHOD_NOT_ALLOWED);
        return true;
    }

    if (request->method() == QHttpRequest::HTTP_GET) {
        const QVariantMap category = Qdl::getCategory(parts.at(1));

        if (category.isEmpty()) {
            return false;
        }

        writeResponse(response, QHttpResponse::STATUS_OK, QtJson::Json::serialize(category));
        return true;
    }

    if (request->method() == QHttpRequest::HTTP_PUT) {
        const QVariantMap properties = QtJson::Json::parse(request->body()).toMap();
        const QString path = properties.value("path").toString();

        if ((path.isEmpty()) || (!Qdl::addCategory(parts.at(1), path))) {
            writeResponse(response, QHttpResponse::STATUS_BAD_REQUEST);
        }
        else {
            writeResponse(response, QHttpResponse::STATUS_OK);
        }

        return true;
    }

    if (request->method() == QHttpRequest::HTTP_DELETE) {
        const QVariantMap properties = QtJson::Json::parse(request->body()).toMap();
        const QString name = properties.value("name").toString();

        if ((name.isEmpty()) || (!Qdl::removeCategory(name))) {
            writeResponse(response, QHttpResponse::STATUS_BAD_REQUEST);
        }
        else {
            writeResponse(response, QHttpResponse::STATUS_OK);
        }

        return true;
    }

    writeResponse(response, QHttpResponse::STATUS_METHOD_NOT_ALLOWED);
    return true;
}
示例#26
0
文件: main.cpp 项目: janisozaur/ro
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    if (a.arguments().size() < 3) {
        qCritical() << "this application requires more arguments!";
        return -1;
    }

    const QString trainDirName = a.arguments().at(1);
    const QString testDirName = a.arguments().at(2);
    const QString outputName = a.arguments().at(3);
    const QString extractorName = a.arguments().at(4);
    const QStringList extractorArgs = a.arguments().mid(5);
    ExtractorInterface *extractor =
            ExtractorFactory::getExtractor(extractorName, extractorArgs);
    if (extractor == NULL) {
        qCritical() << "failed to initialise extractor" << extractorName;
        return -2;
    }

    QDir trainDir(trainDirName);
    QStringList subdirs = QStringList() << "wood" << "straw" << "salt" << "linen";
    QList<quint8> labels = QList<quint8>() << 32 << 96 << 160 << 224;
    QVector<LabelledData> trainData;
#ifdef HAS_ELAPSED_TIMER
    QElapsedTimer extractionTimer;
#else
    QTime extractionTimer;
#endif

    int threadCount = 1;
#ifdef _OPENMP
#pragma omp parallel
    {
#pragma omp single
        {
            threadCount = omp_get_num_threads();
        }
    }
#endif
    qDebug() << "using" << threadCount << "threads.";

    extractionTimer.start();
    unsigned int imagesCount = 0;
    for (int j = 0; j < subdirs.size(); j++) {
        trainDir.cd(subdirs.at(j));
        const QFileInfoList fileList = trainDir.entryInfoList(QStringList() << "*.png");
#ifdef HAS_ELAPSED_TIMER
        QElapsedTimer extractorTimer;
#else
        QTime extractorTimer;
#endif
        extractorTimer.start();
        for (int i = 0; i < fileList.size(); i++) {
            imagesCount++;
            const QString filename = fileList.at(i).filePath();
            const QImage image(filename);
            if (image.format() != QImage::Format_Indexed8) {
                qCritical("Image is not greyscale!");
                return -1;
            }
            extractor->preprocess(image);
            if (extractor->extracts()) {
                unsigned int count = trainData.size();
                trainData.resize(trainData.size() + image.width() * image.height());
                LabelledData *trainDataPtr = trainData.data();
#pragma omp parallel for
                for (int x = 0; x < image.width(); x++) {
                    for (int y = 0; y < image.height(); y++) {
                        const QVector<nnreal> res = extractor->extract(image, x, y);
                        Q_ASSERT(res.size() == extractor->size());
                        LabelledData li(res, labels.at(j));
                        const unsigned int idx = count + x * image.height() + y;
                        trainDataPtr[idx] = li;
                    }
                }
            }
            const QVector<QVector<nnreal> > ppFeatures = extractor->postprocess(image);
            const int ppCount = ppFeatures.size();
            if (ppCount > 0) {
                const int count = trainData.size();
                trainData.resize(trainData.size() + ppFeatures.size());
                LabelledData *trainDataPtr = trainData.data();
#pragma omp parallel for
                for (int k = 0; k < ppCount; k++) {
                    Q_ASSERT(ppFeatures.at(k).size() == extractor->size());
                    LabelledData ld(ppFeatures.at(k), labels.at(j));
                    trainDataPtr[count + k] = ld;
                }
            }
            qDebug() << fileList.at(i).filePath() << extractorTimer.restart();
        }
        trainDir.cdUp();
    }

    const int msecs = extractionTimer.elapsed();
    qDebug() << "trainSize:" << trainData.size() << "extraction of "
             << imagesCount << "images took" << msecs << "msecs, average"
             << float(msecs) / imagesCount << "msecs per image";
    const QString trainOutFilename(outputName + "_" + extractorName + "_train.out");
    QFile trainOutput(trainOutFilename);
    if (!trainOutput.open(QIODevice::WriteOnly)) {
        qCritical() << "failed to open output file" << trainOutFilename;
        return -3;
    }
    {
#ifdef HAS_ELAPSED_TIMER
        QElapsedTimer saveTimer;
#else
        QTime saveTimer;
#endif
        saveTimer.start();
        QDataStream outstream(&trainOutput);
        saveFeatures(outstream, extractorName, extractorArgs, extractor->size(), trainData);
        int msecs = saveTimer.elapsed();
        qDebug() << "saving took" << msecs << "msecs";
    }
    trainOutput.close();
    trainData.clear();

    {
        QDir testDir(testDirName);
        const QFileInfoList dataFileList  = testDir.entryInfoList(QStringList() << "test*.png");
        const QFileInfoList labelFileList = testDir.entryInfoList(QStringList() << "label*.png");
        Q_ASSERT(dataFileList.size() == labelFileList.size());
#ifdef HAS_ELAPSED_TIMER
        QElapsedTimer extractorTimer;
#else
        QTime extractorTimer;
#endif
        extractorTimer.start();
        QTextStream out(stdout);
        for (int i = 0; i < dataFileList.size(); i++) {
            const QImage dataImage(dataFileList.at(i).filePath());
            const QImage labelImage(labelFileList.at(i).filePath());
            QVector<LabelledData> testData;
            extractor->preprocessTest(dataImage, labelImage);
            int cnt = 0;
            if (extractor->extracts()) {
                unsigned int count = testData.size();
                testData.resize(dataImage.width() * dataImage.height());
                LabelledData *testDataPtr = testData.data();
#pragma omp parallel for
                for (int x = 0; x < dataImage.width(); x++) {
#pragma omp critical
                    {
                        cnt++;
                        out << cnt * 100 / dataImage.width() << "%" << '\r';
                        out.flush();
                    }
                    for (int y = 0; y < dataImage.height(); y++) {
                        const QVector<nnreal> res = extractor->extract(dataImage, x, y);
                        const quint8 c = labelImage.pixelIndex(x, y);
                        LabelledData li(res, c);
                        li.squeeze();
                        const unsigned int idx = count + x * dataImage.height() + y;
                        testDataPtr[idx] = li;
                    }
                }
                out << endl;
            }
            const QVector<LabelledData> ppFeatures = extractor->postprocessTest(dataImage, labelImage);
            testData << ppFeatures;
            qDebug() << dataFileList.at(i).filePath() << extractorTimer.restart();
            const QString testOutFilename(outputName + "_" + extractorName + "_test" + QString::number(i) + ".out");
            QFile testOutput(testOutFilename);
            if (!testOutput.open(QIODevice::WriteOnly)) {
                qCritical() << "failed to open output file" << testOutFilename;
                return -3;
            }
            {
#ifdef HAS_ELAPSED_TIMER
                QElapsedTimer saveTimer;
#else
                QTime saveTimer;
#endif
                saveTimer.start();
                QDataStream outstream(&testOutput);
                saveFeatures(outstream, extractorName, extractorArgs, extractor->size(), testData);
                int msecs = saveTimer.elapsed();
                qDebug() << "saving took" << msecs << "msecs";
            }
            testOutput.close();
        }
    }

    delete extractor;

    return 0;
}
示例#27
0
/*! parses .cty file, makes country list

      -  lat=latitude of station +=N
   -  lon=longitude of station +=W
   -  ZoneType: 0: read CQ zones/countries  1: read ITU zones/ARRL countries

 */
void Cty::initialize(double la, double lo, int ZoneType)
{
/*! CTY file format

   Column   Length      Description

   -    1           26  country Name
   -    27          5   CQ Zone
   -    32          5   ITU Zone
   -    37          5   2-letter continent abbreviation
   -    42          9   Latitude in degrees, + for North
   -    51          10  Longitude in degrees, + for West
   -    61          9   Local time offset from GMT
   -    70          6   Primary DXCC Prefix (A "*" preceding this prefix indicates
                        that the country is on the DARC WAEDC list, and counts in
                        CQ-sponsored contests, but not ARRL-sponsored contests).
 */
    double mylat=la;
    double mylon=lo;

    QFile file(dataDirectory()+"/"+settings.value(c_cty,c_cty_def).toString());
    int   indx;

    // sunrise/sunset times for station
    sunTimes(mylat, mylon, mySun);

    // sunrise/sunset times and bearings for CQ or ITU zones. These are used for
    // certain countries that span many zones
    QString zoneFileName;
    switch (ZoneType) {
    case 0:zoneFileName=dataDirectory()+"/cq_zone_latlong.dat";break;
    case 1:zoneFileName=dataDirectory()+"/itu_zone_latlong.dat";break;
    }
    QFile file2(zoneFileName);
    if (file2.open(QIODevice::ReadOnly | QIODevice::Text)) {
        // add blank for 0, zones start with 1
        zoneBearing.append(0);
        zoneSun.append("");
        while (!file2.atEnd()) {
            QString buffer;
            buffer=file2.readLine(80);
            if (buffer.contains('#')) continue; // #=comment line

            buffer=buffer.trimmed();
            QStringList field = buffer.split(" ", QString::SkipEmptyParts);
            double lat=field.at(1).toDouble();
            double lon=field.at(2).toDouble();
            QString sunTime;
            QString set;
            sunTimes(lat, -lon, sunTime);
            zoneSun.append(sunTime);

            double dist;
            double head;
            qrb(mylon * -1.0, mylat, lon , lat, &dist, &head);
            zoneBearing.append(qRound(head));
        }
        file2.close();
    } else {
        // file missing, just make these blank
        int nz=40;
        if (ZoneType==1) nz=80;
        for (int i=0;i<nz;i++) {
            zoneBearing.append(0);
            zoneSun.append("ERR");
        }
    }
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QString tmp = "ERROR: can't open file " + settings.value(c_cty,c_cty_def).toString();
        emit(ctyError(tmp));
        return;
    }
    nARRLCty = 0;
    nCQCty   = 0;
    indx     = 0;

    while (!file.atEnd()) {
        QByteArray buffer, tmp, tmp2, buffer_a, buffer_e;
        int        i0, i1, i2, i3, i4, cqz, ituz;

        // get one record
        // all records are at least one line
        buffer = file.readLine();
        tmp    = file.readLine();
        buffer_e.clear();

        // zone exceptions for main pfx
        while (tmp.contains("#")) {
            buffer_e.append(tmp);
            while (!tmp.contains(";")) {
                tmp = file.readLine();
                buffer_e.append(tmp);
            }
            tmp = file.readLine();
        }

        // alias pfx; may include zone exceptions as well
        buffer_a = tmp;
        while (!tmp.contains(";")) {
            tmp = file.readLine();
            buffer_a.append(tmp);
        }
        buffer   = buffer.trimmed();
        buffer_a = buffer_a.trimmed();
        buffer_e = buffer_e.trimmed();

        // now process parts
        // main line
        Country* new_country = new Country;
        new_country->multipleZones = false;
        new_country->indx          = indx;

        i1                = buffer.indexOf(":", 0);
        new_country->name = buffer.mid(0, i1);

        // insert some common abbrieviations (I=Island,...)
        // to save screen space
        if (new_country->name.contains("Island")) {
            new_country->name.replace("Island", "I");
        }
        i2 = buffer.indexOf(":", i1 + 1);
        int cqzone = buffer.mid(i1 + 1, i2 - i1 - 1).toInt();

        i1 = buffer.indexOf(":", i2 + 1);
        int ituzone = buffer.mid(i2 + 1, i1 - i2 - 1).toInt();
        if (ZoneType) {
            new_country->Zone = ituzone;
        } else {
            new_country->Zone = cqzone;
        }
        i2  = buffer.indexOf(":", i1 + 1);
        tmp = buffer.mid(i1 + 1, i2 - i1 - 1);

        tmp = tmp.trimmed();
        if (tmp == "NA") {
            new_country->Continent = NA;
        } else if (tmp == "SA") {
            new_country->Continent = SA;
        } else if (tmp == "EU") {
            new_country->Continent = EU;
        } else if (tmp == "AF") {
            new_country->Continent = AF;
        } else if (tmp == "AS") {
            new_country->Continent = AS;
        } else if (tmp == "OC") {
            new_country->Continent = OC;
        }
        i1 = buffer.indexOf(":", i2 + 1);
        double lat = buffer.mid(i2 + 1, i1 - i2 - 1).trimmed().toFloat();

        i2 = buffer.indexOf(":", i1 + 1);
        double lon = buffer.mid(i1 + 1, i2 - i1 - 1).trimmed().toFloat();

        double dist;
        double head;
        qrb(mylon * -1.0, mylat, lon * -1.0, lat, &dist, &head);
        new_country->bearing = qRound(head); // round azimuth to nearest degree
        sunTimes(lat, lon, new_country->sun);

        i1                   = buffer.indexOf(":", i2 + 1);
        new_country->delta_t = buffer.mid(i2 + 1, i1 - i2 - 1).trimmed().toFloat();

        i2                   = buffer.indexOf(":", i1 + 1);
        new_country->MainPfx = buffer.mid(i1 + 1, i2 - i1 - 1);
        new_country->MainPfx = new_country->MainPfx.trimmed();

        if (new_country->MainPfx.contains("*")) {
            if (ZoneType == 0) {
                // CQ country
                new_country->MainPfx.replace("*", "");
                nCQCty++;
            } else {
                // only keeping ARRL countries, skip this one
                delete new_country;
                continue;
            }
        } else {
            nARRLCty++;
        }

        // country has multiple zones?
        if (buffer_e != "") {
            new_country->multipleZones = true;
            QList<QByteArray> tmpl = buffer_e.split(';');
            tmpl.removeLast();  // for some reason get 1 too many here
            for (int i = 0; i < tmpl.size(); i++) {
                i1 = tmpl[i].indexOf("#");
                i2 = tmpl[i].indexOf(":");
                QByteArray pf = tmpl[i].mid(i1 + 1, i2 - i1 - 1);
                pf = pf.trimmed();

                // remove any final digit in the prefix
                if (isDigit(pf.at(pf.size() - 1))) {
                    pf.chop(1);
                }

                // remove initial pfx and final ;
                tmpl[i] = tmpl[i].mid(i2 + 1, tmpl[i].size() - 2);
                QList<QByteArray> tmpl2 = tmpl[i].split(',');  // separate
                for (int j = 0; j < tmpl2.size(); j++) {
                    tmpl2[j] = tmpl2[j].trimmed();
                    tmpl2[j].replace(pf, "");

                    // does it have a ITU zone exception?
                    ituz = 0;
                    if (tmpl2[j].contains("[")) {
                        i3 = tmpl2[j].indexOf("[");
                        i4 = tmpl2[j].indexOf("]");
                        if (i3 != -1 && i4 != -1) {
                            tmp2     = tmpl2[j].mid(i3 + 1, i4 - i3 - 1);
                            ituz     = tmp2.toInt();
                            tmp2     = tmpl2[j].mid(i3, i4 - i3 + 1);
                            tmpl2[j] = tmpl2[j].replace(tmp2, "");
                        }
                    }
                    cqz = 0;

                    // does it have a CQ zone exception?
                    if (tmpl2[j].contains("(")) {
                        i3 = tmpl2[j].indexOf("(");
                        i4 = tmpl2[j].indexOf(")");
                        if (i3 != -1 && i4 != -1) {
                            tmp2     = tmpl2[j].mid(i3 + 1, i4 - i3 - 1);
                            cqz      = tmp2.toInt();
                            tmp2     = tmpl2[j].mid(i3, i4 - i3 + 1);
                            tmpl2[j] = tmpl2[j].replace(tmp2, "");
                        }
                    }
                    new_country->zonePfx.append(tmpl2[j]);
                    if (ZoneType) {
                        if (ituz) {
                            new_country->zones.append(ituz);
                        } else {
                            new_country->zones.append(ituzone);
                        }
                    } else {
                        if (cqz) {
                            new_country->zones.append(cqz);
                        } else {
                            new_country->zones.append(cqzone);
                        }
                    }
                }
            }
        }

        // alias prefixes, may include zone exceptions
        i1 = 0;
        i2 = buffer_a.indexOf(",", i1 + 1);
        if (i2 == -1) i2 = buffer_a.size() - 1;
        int nalias = 0;
        while (i1 < (buffer_a.size() - 1)) {
            tmp = buffer_a.mid(i1, i2 - i1);
            tmp = tmp.trimmed();
            if (tmp.startsWith("=")) {
                i0 = 1; // call exception
            } else {
                i0 = 0; // alias prefix
                nalias++;
            }
            ituz = -1; // -1 is marker to use regular zone in pfx list
            cqz  = -1;

            // does it have a ITU zone exception?
            if (tmp.contains("[")) {
                i3 = tmp.indexOf("[");
                i4 = tmp.indexOf("]");
                if (i3 != -1 && i4 != -1) {
                    tmp2 = tmp.mid(i3 + 1, i4 - i3 - 1);
                    ituz = tmp2.toInt();
                    tmp2 = tmp.mid(i3, i4 - i3 + 1);
                    tmp  = tmp.replace(tmp2, "");
                }
            }

            // does it have a CQ zone exception?
            if (tmp.contains("(")) {
                i3 = tmp.indexOf("(");
                i4 = tmp.indexOf(")");
                if (i3 != -1 && i4 != -1) {
                    tmp2 = tmp.mid(i3 + 1, i4 - i3 - 1);
                    cqz  = tmp2.toInt();
                    tmp2 = tmp.mid(i3, i4 - i3 + 1);
                    tmp  = tmp.replace(tmp2, "");
                }
            }

            if (!i0) {
                // new alias prefix
                Pfx* new_pfx = new Pfx;
                new_pfx->CtyIndx      = indx;
                new_pfx->zoneOverride = true;
                if (ZoneType) {
                    new_pfx->Zone = ituz;
                } else {
                    new_pfx->Zone = cqz;
                }
                if (new_pfx->Zone == -1) {
                    new_pfx->Zone         = new_country->Zone;
                    new_pfx->zoneOverride = false;
                }

                new_pfx->prefix = tmp;
                pfxList.append(new_pfx);
            } else {
                // new exception call
                CtyCall* new_call = new CtyCall;
                new_call->call = tmp.right(tmp.size() - 1);
                if (ZoneType) {
                    if (ituz != -1) {
                        new_call->Zone = ituz;
                    } else {
                        new_call->Zone = new_country->Zone;
                    }
                } else {
                    if (cqz != -1) {
                        new_call->Zone = cqz;
                    } else {
                        new_call->Zone = new_country->Zone;
                    }
                }
                if (cqz == -1 && ituz == -1) {
                    // it NEITHER zone was defined, add call to exception list
                    // (with default zones set above). This is mostly for weird/unexpected calls
                    new_call->CtyIndx = indx;
                    new_call->sun=new_country->sun;
                    CallE.append(new_call);
                } else if ((!ZoneType && cqz == -1) || (ZoneType && ituz == -1)) {
                    // the exception doesn't have ONE of the zones defined, remove it
                    // (some entries in cty file only have CQ or ITU zones defined, but
                    // not both. In IARU contest for example, do not want CQ zone exceptions
                    // to be kept
                    delete new_call;
                } else {
                    new_call->CtyIndx = indx;
                    new_call->sun=zoneSun.at(new_call->Zone);
                    CallE.append(new_call);
                }
            }

            i1 = i2 + 1;
            i2 = buffer_a.indexOf(",", i1 + 1);
            if (i2 == -1) {
                i2 = buffer_a.size() - 1;
            }
        }
        countryList.append(new_country);

        // special case: some countries (4U1U, ...) have no alias prefixes listed, only exception calls.
        // make sure to add to main pfx list!
        if (nalias == 0) {
            Pfx* new_pfx = new Pfx;
            new_pfx->zoneOverride = false;
            new_pfx->CtyIndx      = indx;
            if (ZoneType) {
                new_pfx->Zone = ituz;
            } else {
                new_pfx->Zone = cqz;
            }
            if (new_pfx->Zone == -1) {
                new_pfx->Zone = new_country->Zone;
            }
            new_pfx->prefix = new_country->MainPfx;
            pfxList.append(new_pfx);
        }

        indx++;
    }

    /*!
       @todo define < operator so qsort can be used sort prefix and call exception lists
     */

    // prefix
    for (int i = 1; i < pfxList.size(); i++) {
        QByteArray tmp = pfxList[i]->prefix;
        int        i0  = pfxList[i]->Zone;
        int        i1  = pfxList[i]->CtyIndx;
        bool       i2  = pfxList[i]->zoneOverride;
        int        j   = i - 1;
        while (j >= 0 && pfxList[j]->prefix > tmp) {
            pfxList[j + 1]->prefix       = pfxList[j]->prefix;
            pfxList[j + 1]->Zone         = pfxList[j]->Zone;
            pfxList[j + 1]->CtyIndx      = pfxList[j]->CtyIndx;
            pfxList[j + 1]->zoneOverride = pfxList[j]->zoneOverride;
            j--;
        }
        pfxList[j + 1]->prefix       = tmp;
        pfxList[j + 1]->Zone         = i0;
        pfxList[j + 1]->CtyIndx      = i1;
        pfxList[j + 1]->zoneOverride = i2;
    }

    // exception
    for (int i = 1; i < CallE.size(); i++) {
        QByteArray tmp = CallE[i]->call;
        QString suntmp= CallE[i]->sun;
        int        i0  = CallE[i]->Zone;
        int        i1  = CallE[i]->CtyIndx;
        int        j   = i - 1;
        while (j >= 0 && CallE[j]->call > tmp) {
            CallE[j + 1]->call    = CallE[j]->call;
            CallE[j + 1]->sun    = CallE[j]->sun;
            CallE[j + 1]->Zone    = CallE[j]->Zone;
            CallE[j + 1]->CtyIndx = CallE[j]->CtyIndx;
            j--;
        }
        CallE[j + 1]->call    = tmp;
        CallE[j + 1]->sun    = suntmp;
        CallE[j + 1]->Zone    = i0;
        CallE[j + 1]->CtyIndx = i1;
    }

    // save index for US
    Qso  tmpqso;
    tmpqso.call = "W1AW";
    bool b;
    usaIndx = idPfx(&tmpqso, b);
}
示例#28
0
void UciWorker::processCommands() {
    if(this->process->state() == QProcess::NotRunning &&
            !this->cmd_queue->isEmpty()) {
        QString msg = this->cmd_queue->dequeue();
        if(msg.startsWith("start_engine?")) {
            QString path = msg.split("?")[1];
            //qDebug() << "path: " << path;
            this->process->start(path.append("\n"));
            this->engine_info->strength = -1;
        }
    }
    else if(this->process->state() == QProcess::Running) {
        QString output = QString(this->process->readAllStandardOutput());
        if(!output.isEmpty()) {
            //qDebug() << "RECEIVING: " << output;
            this->engine_info->update(output, this->current_fen);
            if(this->engine_info->seesMate[0]) {
                emit(mateDetected(this->engine_info->mate[0]));
            }
            if(!this->engine_info->pv.isEmpty()) {
                emit(bestPv(this->engine_info->pv));
            }
            emit(eval(this->engine_info->score[0]));
            emit(info(this->engine_info->toString()));
            QStringList lines = output.split("\n");
            for(int i=0;i<lines.count();i++) {
                QString line = lines.at(i);
                QRegularExpressionMatch bm_match = REG_BESTMOVE.match(line);
                if (bm_match.hasMatch() && bm_match.captured(1) != 0) {
                    QString uci_move = bm_match.captured(1);
                    emit(bestmove(uci_move));
                }
            }
        }
        if(!this->cmd_queue->isEmpty()) {
            // first check if we are in go infinite mode
            // if so, first send a stop command to the engine
            // before processing further commands from the queue
            if(this->go_infinite) {
                this->process->write("stop\n");
                this->process->waitForBytesWritten();
            }
            QString msg = this->cmd_queue->dequeue();
            //qDebug() << "SENDING: " << msg;
            this->go_infinite = false;
            // if the command is "position fen moves", first count the
            // numbers of moves so far to generate move numbers in engine info
            if(msg.startsWith("position")) {
                QRegularExpressionMatch mv_match = REG_MOVES.match(msg);
                int cnt = mv_match.lastCapturedIndex();
                if(cnt > 0) {
                    this->engine_info->halfmoves = cnt;
                }
            }
            if(msg.startsWith("quit")) {
                this->process->write("quit\n");
                this->process->waitForBytesWritten();
                this->process->waitForFinished();
            }
            else if(msg.startsWith("go infinite")) {
                //QThread::sleep(10);
                this->go_infinite = true;
                this->process->write("go infinite\n");
                this->process->waitForBytesWritten();
                //QThread::sleep(1);
            }
            else if(msg.startsWith("setoption name Skill Level")) {                
                QRegularExpressionMatch strength_match = REG_STRENGTH.match(msg);
                if(strength_match.hasMatch()) {
                    int val_i = strength_match.captured(0).remove(0,18).toInt();
                    this->engine_info->strength = val_i;
                }
                this->process->write(msg.append("\n").toLatin1());
                this->process->waitForBytesWritten();
            } else if(msg.startsWith("setoption name MultiPV value")) {
                int nrLines = msg.mid(29,30).toInt();
                this->engine_info->nrPvLines = nrLines;
                this->process->write(msg.append("\n").toLatin1());
                this->process->waitForBytesWritten();
            } else {
                this->process->write(msg.append("\n").toLatin1());
                this->process->waitForBytesWritten();
            }
        }
    }
}
示例#29
0
void picPunto::processFilePic(QFile* file)
{
    //    QString outname, sep;
    QString sep = " ";
    QString::SplitBehavior skip = QString::KeepEmptyParts;
    QStringList data;
    QString cmd;
    pointData *pd;
    while (!file->atEnd()) {
        int i = 2;
        QString line = file->readLine();
        line.remove ( line.size()-1, 1);
        // printf("process line: %s\n",line.toStdString().c_str() );
        data = line.split(sep, skip);
        if (data.size() < 4 ) continue;
        cmd = data.at(0);
        if (cmd == "line" ) {
                if (data.at(2) == "from"){
                    i++; // dashed line
                }
                for (;i <  data.size(); i += 2) {
                    pd = new pointData;
                    pd->x = data.at(i).split(',').at(0);
                    pd->y = data.at(i).split(',').at(1);
                    dataList.append(pd);
                    if ( i < data.size()-1 and data.at(i+1) != "to") {
                        QMessageBox::critical ( this, "picPunto", QString(tr("format error in %1")).arg(line) );
                        return;
                    }
                }
                if (dataList.size() > 0 )
                    drawLine();
        } else {
            if (cmd == "circle") { // circle at 7.935,3.643 rad 0.035
                if ( data.size() != 5 ) {
                    QMessageBox::critical ( this, "picPunto", QString(tr("format error in %1")).arg(line) );
                    return;
                }
                drawCircle(data.at(2).split(',').at(0), data.at(2).split(',').at(1), data.at(4));
            } else {
                if (cmd == "box") { // box invis fill 0.000 with .sw at (7.480,6.917) width 0.079 height 0.157
                    if ( data.size() < 11 ) {
                        // QMessageBox::critical ( this, "picPunto", QString(tr("format error in %1")).arg(line) );
                        continue;
                    }
                    QString posx = data.at(7).split(',').at(0);
                    QString posy = data.at(7).split(',').at(1);
                    drawBox(posx.remove(0,1), posy.remove(posy.size()-1,1), data.at(9), data.at(11));
                } else {
                    if ( cmd.startsWith("\"\\s") and data.size() > 3 ) { // "\s5\fRAbstell fläche\fP" at 8.132,7.456 ljust
                        QString txt = line.split("\"", skip).at(1);
                        QStringList rline = line.split("\"", skip).at(2).split(" ",skip);
                        txt.remove ( txt.size()-3, 3);
                        txt.remove (QRegExp("^.*fR"));
                        // printf("process line: %s: %s\n",rline.at(2).toStdString().c_str(),txt.toStdString().c_str() );
                        drawText(rline.at(2).split(',').at(0), rline.at(2).split(',').at(1), txt, rline.at(3));
                    }
                }
            }
        } 
    }
}
示例#30
0
void MiningPage::readProcessOutput()
{
    QByteArray output;

    minerProcess->reset();

    output = minerProcess->readAll();

    QString outputString(output);

    if (!outputString.isEmpty())
    {
        QStringList list = outputString.split("\n", QString::SkipEmptyParts);
        int i;
        for (i=0; i<list.size(); i++)
        {
            QString line = list.at(i);

            // Ignore protocol dump
            if (!line.startsWith("[") || line.contains("JSON protocol") || line.contains("HTTP hdr"))
                continue;

            if (ui->debugCheckBox->isChecked())
            {
                ui->list->addItem(line.trimmed());
                ui->list->scrollToBottom();
            }

            if (line.contains("(yay!!!)"))
                reportToList("Share accepted", SHARE_SUCCESS, getTime(line));
            else if (line.contains("(booooo)"))
                reportToList("Share rejected", SHARE_FAIL, getTime(line));
            else if (line.contains("LONGPOLL detected new block"))
                reportToList("LONGPOLL detected a new block", LONGPOLL, getTime(line));
            else if (line.contains("Supported options:"))
                reportToList("Miner didn't start properly. Try checking your settings.", ERROR, NULL);
            else if (line.contains("The requested URL returned error: 403"))
                reportToList("Couldn't connect. Please check your username and password.", ERROR, NULL);
            else if (line.contains("HTTP request failed"))
                reportToList("Couldn't connect. Please check pool server and port.", ERROR, NULL);
            else if (line.contains("JSON-RPC call failed"))
                reportToList("Couldn't communicate with server. Retrying in 30 seconds.", ERROR, NULL);
            else if (line.contains("thread ") && line.contains("khash/s"))
            {
                QString threadIDstr = line.at(line.indexOf("thread ")+7);
                int threadID = threadIDstr.toInt();

                int threadSpeedindx = line.indexOf(",");
                QString threadSpeedstr = line.mid(threadSpeedindx);
                threadSpeedstr.chop(8);
                threadSpeedstr.remove(", ");
                threadSpeedstr.remove(" ");
                threadSpeedstr.remove('\n');
                double speed=0;
                speed = threadSpeedstr.toDouble();

                threadSpeed[threadID] = speed;

                updateSpeed();
            }
        }
    }
}