示例#1
0
TQString TDEStorageDevice::mountDevice(TQString mediaName, TDEStorageMountOptions mountOptions, TQString* errRet, int* retcode) {
	int internal_retcode;
	if (!retcode) {
		retcode = &internal_retcode;
	}

	TQString ret = mountPath();

	// Device is already mounted
	if (!ret.isNull()) {
		return ret;
	}

	TQString command;
	TQString devNode = deviceNode();
	devNode.replace("'", "'\\''");
	mediaName.replace("'", "'\\''");

#if defined(WITH_UDISKS2) || defined(WITH_UDISKS)
	// Prepare filesystem options for mount
	TQStringList udisksOptions;
	TQString optionString;

	if (mountOptions["ro"] == "true") {
		udisksOptions.append("ro");
	}

	if (mountOptions["atime"] != "true") {
		udisksOptions.append("noatime");
	}

	if (mountOptions["sync"] == "true") {
		udisksOptions.append("sync");
	}

	if(  (mountOptions["filesystem"] == "fat")
	  || (mountOptions["filesystem"] == "vfat")
	  || (mountOptions["filesystem"] == "msdos")
	  || (mountOptions["filesystem"] == "umsdos")
	) {
		if (mountOptions.contains("shortname")) {
			udisksOptions.append(TQString("shortname=%1").arg(mountOptions["shortname"]));
		}
	}

	if( (mountOptions["filesystem"] == "jfs")) {
		if (mountOptions["utf8"] == "true") {
			// udisks/udisks2 for now does not support option iocharset= for jfs
			// udisksOptions.append("iocharset=utf8");
		}
	}

	if( (mountOptions["filesystem"] == "ntfs-3g") ) {
		if (mountOptions.contains("locale")) {
			udisksOptions.append(TQString("locale=%1").arg(mountOptions["locale"]));
		}
	}

	if(  (mountOptions["filesystem"] == "ext3")
	  || (mountOptions["filesystem"] == "ext4")
	) {
		if (mountOptions.contains("journaling")) {
			// udisks/udisks2 for now does not support option data= for ext3/ext4
			// udisksOptions.append(TQString("data=%1").arg(mountOptions["journaling"]));
		}
	}

	for (TQStringList::Iterator it = udisksOptions.begin(); it != udisksOptions.end(); ++it) {
		optionString.append(",");
		optionString.append(*it);
	}

	if (!optionString.isEmpty()) {
		optionString.remove(0, 1);
	}
#endif // defined(WITH_UDISKS2) || defined(WITH_UDISKS)

#ifdef WITH_UDISKS2
	if(command.isEmpty()) {
		// Try to use UDISKS v2 via DBUS, if available
		TQString errorString;
		TQString fileSystemType;

		if (mountOptions.contains("filesystem") && !mountOptions["filesystem"].isEmpty()) {
			fileSystemType = mountOptions["filesystem"];
		}

		int uDisks2Ret = mountDriveUDisks2(devNode, fileSystemType, optionString, &errorString);
		if (uDisks2Ret == 0) {
			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			ret = mountPath();
			return ret;
		}
		else if (uDisks2Ret == -1) {
			if (errRet) {
				*errRet = errorString;
			}

			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			ret = mountPath();
			return ret;
		}
		else {
			// The UDISKS v2 DBUS service was either not available or was unusable; try another method...
			command = TQString::null;
		}
	}
#endif // WITH_UDISKS2

#ifdef WITH_UDISKS
	if(command.isEmpty()) {
		// Try to use UDISKS v1 via DBUS, if available
		TQString errorString;
		TQString fileSystemType;

		if (mountOptions.contains("filesystem") && !mountOptions["filesystem"].isEmpty()) {
			fileSystemType = mountOptions["filesystem"];
		}

		int uDisksRet = mountDriveUDisks(devNode, fileSystemType, udisksOptions, &errorString);
		if (uDisksRet == 0) {
			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			ret = mountPath();
			return ret;
		}
		else if (uDisksRet == -1) {
			if (errRet) {
				*errRet = errorString;
			}

			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			ret = mountPath();
			return ret;
		}
		else {
			// The UDISKS v1 DBUS service was either not available or was unusable; try another method...
			command = TQString::null;
		}
	}
#endif // WITH_UDISKS

	if(command.isEmpty()) {
		// Use 'pmount' command, if available
		TQString pmountProg = TDEGlobal::dirs()->findExe("pmount");
		if (!pmountProg.isEmpty()) {
			// Create dummy password file
			KTempFile passwordFile(TQString::null, "tmp", 0600);
			passwordFile.setAutoDelete(true);

			TQString optionString;
			if (mountOptions["ro"] == "true") {
				optionString.append(" -r");
			}

			if (mountOptions["atime"] != "true") {
				optionString.append(" -A");
			}

			if (mountOptions["utf8"] == "true") {
				optionString.append(" -c utf8");
			}

			if (mountOptions["sync"] == "true") {
				optionString.append(" -s");
			}

			if (mountOptions.contains("filesystem") && !mountOptions["filesystem"].isEmpty()) {
				optionString.append(TQString(" -t %1").arg(mountOptions["filesystem"]));
			}

			if (mountOptions.contains("locale")) {
				optionString.append(TQString(" -c %1").arg(mountOptions["locale"]));
			}

			TQString passFileName = passwordFile.name();
			passFileName.replace("'", "'\\''");

			command = TQString("pmount -p '%1' %2 '%3' '%4' 2>&1").arg(passFileName).arg(optionString).arg(devNode).arg(mediaName);
		}
	}

	if(command.isEmpty()) {
		if (errRet) {
			*errRet = i18n("No supported mounting methods were detected on your system");
		}
		return ret;
	}

	FILE *exepipe = popen(command.local8Bit(), "r");
	if (exepipe) {
		TQString mount_output;
		TQTextStream ts(exepipe, IO_ReadOnly);
		mount_output = ts.read();
		*retcode = pclose(exepipe);
		if (errRet) {
			*errRet = mount_output;
		}
	}

	// Update internal mount data
	TDEGlobal::hardwareDevices()->processModifiedMounts();

	ret = mountPath();

	return ret;
}
RTC::ReturnCode_t ControlEducatorVehicle::onExecute(RTC::UniqueId ec_id)
{
	if (m_target_velocity_inIn.isNew())
	{
		m_target_velocity_inIn.read();
		vx = m_target_velocity_in.data.vx;
		vy = m_target_velocity_in.data.vy;
		va = m_target_velocity_in.data.va;
	}
	if (m_touchIn.isNew())
	{
		while(m_touchIn.isNew())m_touchIn.read();
		if (m_touch.data.length() >= 2)
		{
			touch_r = m_touch.data[0];
			touch_l = m_touch.data[1];
			if (vx > 0)
			{
				if (m_touch.data[0])
				{
					stop_robot();
					back_move();
					rotate_move(true);

				}
				else if (m_touch.data[1])
				{
					stop_robot();
					back_move();
					rotate_move(false);

				}

			}
		}

	}
	if (m_ultrasonicIn.isNew())
	{
		while(m_ultrasonicIn.isNew())m_ultrasonicIn.read();
		if (m_ultrasonic.ranges.length() >= 1)
		{
			range = m_ultrasonic.ranges[0];
			if (vx > 0)
			{
				if (m_ultrasonic.ranges[0] > m_sensor_height)
				{
					stop_flag = true;
					
					stop_robot();
					m_angle.data = 0;
					setTimestamp(m_angle);
					m_angleOut.write();

					double a = 0;
					bool ret = search_ground(a);
					m_angle.data = 0;
					setTimestamp(m_angle);
					m_angleOut.write();
					

					
					
					if (ret)
					{
						turn_move(a);
					}
					coil::TimeValue ts(2, 0);
					coil::sleep(ts);
					
				}
				else
				{
					stop_flag = false;
				}
			}
		}
	}

	if(m_light_reflectIn.isNew())
	{
		while(m_light_reflectIn.isNew())m_light_reflectIn.read();
		
		if(m_light_reflect.data < 1)
		{
			stop_flag = true;
		}
		else
		{
			stop_flag = false;
		}

	}

	if (vx <= 0)
	{
		stop_flag = false;
	
	}
	if (stop_flag)
	{
		m_target_velocity_out.data.vx = 0;
		m_target_velocity_out.data.vy = 0;
		m_target_velocity_out.data.va = 0;
	}
	else
	{
		m_target_velocity_out.data.vx = vx;
		m_target_velocity_out.data.vy = vy;
		m_target_velocity_out.data.va = va;
	}
	
	
	setTimestamp(m_target_velocity_out);
	m_target_velocity_outOut.write();
	
  return RTC::RTC_OK;
}
示例#3
0
void ConvToMDEventsWS::runConversion(API::Progress *pProgress) {

  // Get the box controller
  Mantid::API::BoxController_sptr bc =
      m_OutWSWrapper->pWorkspace()->getBoxController();
  size_t lastNumBoxes = bc->getTotalNumMDBoxes();
  size_t nEventsInWS = m_OutWSWrapper->pWorkspace()->getNPoints();
  // Is the access to input events thread-safe?
  // bool MultiThreadedAdding = m_EventWS->threadSafe();
  // preprocessed detectors insure that each detector has its own spectra
  size_t nValidSpectra = m_NSpectra;

  //--->>> Thread control stuff
  Kernel::ThreadSchedulerFIFO *ts(nullptr);

  int nThreads(m_NumThreads);
  if (nThreads < 0)
    nThreads = 0; // negative m_NumThreads correspond to all cores used, 0 no
                  // threads and positive number -- nThreads requested;
  bool runMultithreaded = false;
  if (m_NumThreads != 0) {
    runMultithreaded = true;
    // Create the thread pool that will run all of these. It will be deleted by
    // the threadpool
    ts = new Kernel::ThreadSchedulerFIFO();
    // it will initiate thread pool with number threads or machine's cores (0 in
    // tp constructor)
    pProgress->resetNumSteps(nValidSpectra, 0, 1);
  }
  Kernel::ThreadPool tp(ts, nThreads, new API::Progress(*pProgress));
  //<<<--  Thread control stuff

  // if any property dimension is outside of the data range requested, the job
  // is done;
  if (!m_QConverter->calcGenericVariables(m_Coord, m_NDims))
    return;

  size_t eventsAdded = 0;
  for (size_t wi = 0; wi < nValidSpectra; wi++) {

    size_t nConverted = this->conversionChunk(wi);
    eventsAdded += nConverted;
    nEventsInWS += nConverted;
    // Keep a running total of how many events we've added
    if (bc->shouldSplitBoxes(nEventsInWS, eventsAdded, lastNumBoxes)) {
      if (runMultithreaded) {
        // Now do all the splitting tasks
        m_OutWSWrapper->pWorkspace()->splitAllIfNeeded(ts);
        if (ts->size() > 0)
          tp.joinAll();
      } else {
        m_OutWSWrapper->pWorkspace()->splitAllIfNeeded(
            nullptr); // it is done this way as it is possible trying to do
                      // single
                      // threaded split more efficiently
      }
      // Count the new # of boxes.
      lastNumBoxes = m_OutWSWrapper->pWorkspace()
                         ->getBoxController()
                         ->getTotalNumMDBoxes();
      eventsAdded = 0;
      pProgress->report(wi);
    }
  }
  // Do a final splitting of everything
  if (runMultithreaded) {
    m_OutWSWrapper->pWorkspace()->splitAllIfNeeded(ts);
    tp.joinAll();
  } else {
    m_OutWSWrapper->pWorkspace()->splitAllIfNeeded(nullptr);
  }

  // Recount totals at the end.
  m_OutWSWrapper->pWorkspace()->refreshCache();
  // m_OutWSWrapper->refreshCentroid();
  pProgress->report();

  /// Set the special coordinate system flag on the output workspace.
  m_OutWSWrapper->pWorkspace()->setCoordinateSystem(m_coordinateSystem);
}
示例#4
0
void tst_Q3CString::acc_01()
{
    Q3CString a;
    Q3CString b; //b(10);
    Q3CString bb; //bb((int)0);
    Q3CString c("String C");
    char tmp[10];
    tmp[0] = 'S';
    tmp[1] = 't';
    tmp[2] = 'r';
    tmp[3] = 'i';
    tmp[4] = 'n';
    tmp[5] = 'g';
    tmp[6] = ' ';
    tmp[7] = 'D';
    tmp[8] = 'X';
    tmp[9] = '\0';
    Q3CString d(tmp,8);
    Q3CString ca(a);
    Q3CString cb(b);
    Q3CString cc(c);
    Q3CString n;
    Q3CString e("String E");
    Q3CString f;
    f = e;
    f.detach();
    f[7]='F';
    QCOMPARE(e,(Q3CString)"String E");
    char text[]="String f";
    f = text;
    text[7]='!';
    QCOMPARE(f,(Q3CString)"String f");
    f[7]='F';
    QCOMPARE(text[7],'!');

#if 0
    a="";
    a[0]='A';
    Q3CString res = "A";
    QCOMPARE(a,res);
    QCOMPARE(a.length(),(uint)1);
    compare(a.length(),(uint)1);
    a[1]='B';
    QCOMPARE(a,(Q3CString)"AB");
    QCOMPARE(a.length(),(uint)2);
    a[2]='C';
    QCOMPARE(a,(Q3CString)"ABC");
    QCOMPARE(a.length(),(uint)3);
    a = Q3CString();
    QVERIFY(a.isNull());
    a[0]='A';
    QCOMPARE(a,(Q3CString)"A");
    QCOMPARE(a.length(),(uint)1);
    a[1]='B';
    QCOMPARE(a,(Q3CString)"AB");
    QCOMPARE(a.length(),(uint)2);
    a[2]='C';
    QCOMPARE(a,(Q3CString)"ABC");
    QCOMPARE(a.length(),(uint)3);
#endif
    a="123";
    b="456";
    a[0]=a[1];
    QCOMPARE(a,(Q3CString)"223");
    a[1]=b[1];
    QCOMPARE(b,(Q3CString)"456");
    QCOMPARE(a,(Q3CString)"253");

    char t[]="TEXT";
    a="A";
    a=t;
    QCOMPARE(a,(Q3CString)"TEXT");
    QCOMPARE(a,(Q3CString)t);
    a[0]='X';
    QCOMPARE(a,(Q3CString)"XEXT");
    QCOMPARE(t[0],'T');
    t[0]='Z';
    QCOMPARE(a,(Q3CString)"XEXT");

    a="ABC";
    QCOMPARE(((const char*)a)[1],'B');
    QCOMPARE(strcmp(a,(Q3CString)"ABC"),0);
    a += "DEF";
    QCOMPARE(a, (Q3CString)"ABCDEF");
    a += 'G';
    QCOMPARE(a, (Q3CString)"ABCDEFG");
    a += ((const char*)(0));
    QCOMPARE(a, (Q3CString)"ABCDEFG");

    // non-member operators

    a="ABC";
    b="ABC";
    c="ACB";
    d="ABCD";
    QVERIFY(a==b);
    QVERIFY(!(a==d));
    QVERIFY(!(a!=b));
    QVERIFY(a!=d);
    QVERIFY(!(a<b));
    QVERIFY(a<c);
    QVERIFY(a<d);
    QVERIFY(!(d<a));
    QVERIFY(!(c<a));
    QVERIFY(a<=b);
    QVERIFY(a<=d);
    QVERIFY(a<=c);
    QVERIFY(!(c<=a));
    QVERIFY(!(d<=a));
    QCOMPARE(a+b,(Q3CString)"ABCABC");
    QCOMPARE(a	+"XXXX",(Q3CString)"ABCXXXX");
    QCOMPARE(a+'X',(Q3CString)"ABCX");
    QCOMPARE("XXXX"+a,(Q3CString)"XXXXABC");
    QCOMPARE('X'+a,(Q3CString)"XABC");
    a = (const char*)0;
    QVERIFY(a.isNull());
    QVERIFY(*((const char *)a) == 0);

    {
	QFile f("COMPARE.txt");
	f.open( QIODevice::WriteOnly );
	QTextStream ts( &f );
	ts.setEncoding(QTextStream::Unicode);
	ts << "Abc";
    }
}
/**
* @brief 超音波センサで走行できる地面が存在するかを探索する
* @param a 地面が存在する方向
* @return 走行できる地面が探索範囲に存在した場合はtrue、存在しない場合はfalse
*/
bool ControlEducatorVehicle::search_ground(double &a)
{
	m_angle.data = (-1)*m_medium_motor_range;
	setTimestamp(m_angle);
	m_angleOut.write();
	coil::TimeValue ts(2, 0);
	coil::sleep(ts);
	




	if (m_ultrasonicIn.isNew())
	{
		while(m_ultrasonicIn.isNew())m_ultrasonicIn.read();
		if (m_ultrasonic.ranges.length() >= 1)
		{
			
			if (m_ultrasonic.ranges[0] < m_sensor_height)
			{
				a = m_medium_motor_range;
				return true;
			}
		}
	}
	

	m_angle.data = (-1)*-m_medium_motor_range;
	setTimestamp(m_angle);
	m_angleOut.write();
	ts = coil::TimeValue(4, 0);
	coil::sleep(ts);


	if (m_ultrasonicIn.isNew())
	{
		while(m_ultrasonicIn.isNew())m_ultrasonicIn.read();
		if (m_ultrasonic.ranges.length() >= 1)
			{
			
			if (m_ultrasonic.ranges[0] < m_sensor_height)
			{
				a = -m_medium_motor_range;
				return true;
			}
				
		}
	}
	

	m_angle.data = 0;
	setTimestamp(m_angle);
	m_angleOut.write();
	
	/*if (rotate_sensor(0, m_medium_motor_range, a))
	{
		return true;
	}
	
	if (rotate_sensor(m_medium_motor_range, -m_medium_motor_range, a))
	{
		return true;
	}
	
	if (rotate_sensor(-m_medium_motor_range, 0, a))
	{
		return true;
	}*/
	
	return false;
}
示例#6
0
void Project::save( bool onlyProjectFile )
{
    bool anythingModified = FALSE;

    //  save sources and forms
    if ( !onlyProjectFile ) {

	saveConnections();

	for ( SourceFile *sf = sourcefiles.first(); sf; sf = sourcefiles.next() ) {
	    anythingModified = anythingModified || sf->isModified();
	    if ( !sf->save() )
		return;
	}

	for ( FormFile *ff = formfiles.first(); ff; ff = formfiles.next() ) {
	    anythingModified = anythingModified || ff->isModified();
	    if ( !ff->save() )
		return;
	}
    }

    if ( isDummy() || filename.isEmpty() )
	return;

    if ( !modified ) {
	if ( singleProjectMode() ) {
	    LanguageInterface *iface = MetaDataBase::languageInterface( language() );
	    if ( iface && iface->supports( LanguageInterface::CompressProject ) )
		iface->compressProject( makeAbsolute( filename ), singleProFileName, anythingModified );
	}
 	return;
    }

    QFile f( filename );
    QString original = "";

    // read the existing file
    bool hasPreviousContents = FALSE;
    if ( f.open( IO_ReadOnly ) ) {
	QTextStream ts( &f );
	original = ts.read();
	f.close();
        hasPreviousContents = TRUE;
	remove_contents( original, "{SOURCES+=" ); // ### compatibility with early 3.0 betas
	remove_contents( original, "DBFILE" );
	remove_contents( original, "LANGUAGE" );
	remove_contents( original, "TEMPLATE" );
	removePlatformSettings( original, "CONFIG" );
	removePlatformSettings( original, "DEFINES" );
	removePlatformSettings( original, "LIBS" );
	removePlatformSettings( original, "INCLUDEPATH" );
	removePlatformSettings( original, "SOURCES" );
	removePlatformSettings( original, "HEADERS" );
	remove_multiline_contents( original, "FORMS" );
	remove_multiline_contents( original, "INTERFACES" ); // compatibility
	remove_multiline_contents( original, "IMAGES" );
	for ( QStringList::Iterator it = csList.begin(); it != csList.end(); ++it )
	    remove_contents( original, *it );
    }

    if (!original.isEmpty()) {
	// Removes any new lines at the beginning of the file
	while (original.startsWith("\n"))
	    original.remove(0, 1);
    }

    // the contents of the saved file
    QString contents;

    // template
    contents += "TEMPLATE\t= " + templ + "\n";

    // language
    contents += "LANGUAGE\t= " + lang + "\n";
    contents += "\n";

    // config
    writePlatformSettings( contents, "CONFIG", cfg );
    LanguageInterface *iface = MetaDataBase::languageInterface( lang );
    if ( iface ) {
	QStringList sourceKeys;
	iface->sourceProjectKeys( sourceKeys );
	for ( QStringList::Iterator spit = sourceKeys.begin(); spit != sourceKeys.end(); ++spit )
	    remove_multiline_contents( contents, *spit );
    }

    // libs, defines, includes
    writePlatformSettings( contents, "LIBS", lbs );
    writePlatformSettings( contents, "DEFINES", defs );
    writePlatformSettings( contents, "INCLUDEPATH", inclPath );
    writePlatformSettings( contents, "SOURCES", sources );
    writePlatformSettings( contents, "HEADERS", headers );

    // unix
    if ( !hasPreviousContents ) {
 	contents +=
 	    "unix|os2 {\n"
 	    "  UI_DIR = .ui\n"
 	    "  MOC_DIR = .moc\n"
 	    "  OBJECTS_DIR = .obj\n"
 	    "}\n\n";
    }

    // sources
    if ( !sourcefiles.isEmpty() && iface ) {
	QMap<QString, QStringList> sourceToKey;
	for ( SourceFile *f = sourcefiles.first(); f; f = sourcefiles.next() ) {
	    QString key = iface->projectKeyForExtension( QFileInfo( f->fileName() ).extension() );
	    QStringList lst = sourceToKey[ key ];
	    lst << makeRelative( f->fileName() );
	    sourceToKey.replace( key, lst );
	}

	for ( QMap<QString, QStringList>::Iterator skit = sourceToKey.begin();
	      skit != sourceToKey.end(); ++skit ) {
	    QString part = skit.key() + "\t+= ";
	    QStringList lst = *skit;
	    for ( QStringList::Iterator sit = lst.begin(); sit != lst.end(); ++sit ) {
		part += *sit;
		part += ++sit != lst.end() ? " \\\n\t" : "";
		--sit;
	    }
	    part += "\n\n";
	    contents += part;
	}
    }

    // forms and interfaces
    if ( !formfiles.isEmpty() ) {
	contents += "FORMS\t= ";
	for ( QPtrListIterator<FormFile> fit = formfiles; fit.current(); ++fit ) {
	    contents += fit.current()->fileName() +
		 (fit != formfiles.last() ? " \\\n\t" : "");
	}
	contents += "\n\n";
    }

    // images
     if ( !pixCollection->isEmpty() ) {
	contents += "IMAGES\t= ";
	QValueList<PixmapCollection::Pixmap> pixmaps = pixCollection->pixmaps();
	for ( QValueList<PixmapCollection::Pixmap>::Iterator it = pixmaps.begin();
	      it != pixmaps.end(); ++it ) {
		  contents += makeRelative( (*it).absname );
		  contents += ++it != pixmaps.end() ? " \\\n\t" : "";
		  --it;
	}
	contents += "\n\n";
    }

    // database
    if ( !dbFile.isEmpty() )
	contents += "DBFILE\t= " + dbFile + "\n";

    // custom settings
    for ( QStringList::Iterator it = csList.begin(); it != csList.end(); ++it ) {
	QString val = *customSettings.find( *it );
	if ( !val.isEmpty() )
	    contents += *it + "\t= " + val + "\n";
    }

    if ( !f.open( IO_WriteOnly | IO_Translate ) ) {
	QMessageBox::warning( messageBoxParent(),
			      "Save Project Failed", "Couldn't write project file " + filename );
	return;
    }

    QTextStream os( &f );
    os << contents;
    if (hasPreviousContents)
        os << original;

    f.close();

    setModified( FALSE );

    if ( singleProjectMode() ) {
	LanguageInterface *iface = MetaDataBase::languageInterface( language() );
	if ( iface && iface->supports( LanguageInterface::CompressProject ) )
	    iface->compressProject( makeAbsolute( filename ), singleProFileName, TRUE );
    }
}
示例#7
0
void CTTypes::RunTestCaseL(TInt aCurTestCase)
	{
	switch(aCurTestCase)
		{
	case 1:
		{
		__UHEAP_MARK;
		TestRgb tr1(0,0,0, this);
		TestRgb tr2(100,100,100, this);
		TestRgb tr3(10,20,30, this);
		TestRgb tr4(110,160,210, this);
		TestRgb tr5(255,255,255, this);
		INFO_PRINTF1(_L("TRgb"));
		tr1.Test();
		tr2.Test();
		tr3.Test();
		tr4.Test();
		tr5.Test();
		((CTTypesStep*)iStep)->CloseTMSGraphicsStep();
		__UHEAP_MARKEND;
		}
		break;
	case 2:
		{
		INFO_PRINTF1(_L("TTypeface"));
		TestTypeface ttf1(_L(""), 0, this);
		TestTypeface ttf2(_L("Font name"), 1, this);
		TestTypeface ttf3(_L("Font name"), 2, this);
		TestTypeface ttf4(_L("Font name"), 3, this);
		TestTypeface ttf5(_L("Font name"), 4, this);
		TestTypeface ttf6(_L("Font name"), 5, this);
		TestTypeface ttf7(_L("Font name"), 6, this);
		TestTypeface ttf8(_L("Another font name"), 7, this);
		ttf1.Test();
		ttf2.Test();
		ttf3.Test();
		ttf4.Test();
		ttf5.Test();
		ttf6.Test();
		ttf7.Test();
		ttf8.Test();
		}
		break;
	case 3:
		{
		TestMargins tm1(0,0,0,0, this);
		TestMargins tm2(10,20,30,40, this);
		TestMargins tm3(-10,-20,-30,-40, this);
		INFO_PRINTF1(_L("TMargins"));
		tm1.Test();
		tm2.Test();
		tm3.Test();
		}
		break;
	case 4:
		{
		TestPageSpec tps1(TPageSpec::EPortrait,TSize(0,0), this);
		TestPageSpec tps2(TPageSpec::ELandscape,TSize(0,0), this);
		TestPageSpec tps3(TPageSpec::EPortrait,TSize(10,-5), this);
		TestPageSpec tps4(TPageSpec::ELandscape,TSize(15,-20), this);
		TestPageSpec tps5(TPageSpec::EPortrait,TSize(1000,1500), this);
		TestPageSpec tps6(TPageSpec::ELandscape,TSize(2000,500), this);
		INFO_PRINTF1(_L("TPageSpec"));
		tps1.Test();
		tps2.Test();
		tps3.Test();
		tps4.Test();
		tps5.Test();
		tps6.Test();
		}
		break;
	case 5:
		{
		INFO_PRINTF1(_L("FontEffect"));
        	((CTTypesStep*)iStep)->SetTestStepID(_L("GRAPHICS-GDI-0002"));
		TestFontEffect te(this); 
		((CTTypesStep*)iStep)->RecordTestResultL();
		te.Test();
		}
		break;
	case 6:
		{
		INFO_PRINTF1(_L("TFontSyle"));
		TestTFontStyle ts(this);
		ts.Test();
		}
		break;
	case 7:
		{
		TTypeface typeface;
		typeface.iName=_L("Font name");
		TFontStyle fontstyle;
		TestFontSpec tfspec(typeface,200,fontstyle, this);
		INFO_PRINTF1(_L("TFontSpec"));
		tfspec.Test();
		}
		break;
	case 8:
		{
/*
		TestLine tl1(TPoint(10,10),TPoint(90,90), this);
		TestLine tl2(TPoint(100,150),TPoint(50,-50), this);
		TestLine tl3(TPoint(-50,50),TPoint(60,-40), this);
		TestLine tl4(TPoint(-100,0),TPoint(0,200), this);
		TestLine tl5(TPoint(150,-50),TPoint(50,75), this);
		TestLine tl6(TPoint(0,-100),TPoint(-50,-150), this);
		TestLine tl7(TPoint(-1000,-1000),TPoint(1000,1000), this);
		TestLine tl8(TPoint(1000,-1000),TPoint(-1000,1000), this);
		TestLine tl9(TPoint(500,-1000),TPoint(-500,1000), this);
		TestLine tl10(TPoint(-500,-1000),TPoint(500,1000), this);
		TestLine tl11(TPoint(1000,-500),TPoint(-1000,500), this);
		TestLine tl12(TPoint(1000,500),TPoint(-1000,-500), this);
		INFO_PRINTF1(_L("TLinearDDA"));
		tl1.Test();
		tl2.Test();
		tl3.Test();
		tl4.Test();
		tl5.Test();
		tl6.Test();
		tl7.Test();
		tl8.Test();
		tl9.Test();
		tl10.Test();
		tl11.Test();
		tl12.Test();
*/
		INFO_PRINTF1(_L("TLinearDDA is only for Graphics team. Removed."));
		}
		break;
	case 9:
		{
		INFO_PRINTF1(_L("CTypefaceStore"));
		TestTFStore ttfs(this);
		ttfs.Test();
		}
		break;
	case 10:
		{
		INFO_PRINTF1(_L("CFontCache"));
		TestFontCache tfc(this);
		tfc.Test();
		}
		break;
	case 11:
		{
/*
		INFO_PRINTF1(_L("CScaleCropPicture"));
		TestPicture tp(this);
		tp.Test();
*/
		INFO_PRINTF1(_L("CScaleCropPicture is only for Graphics team. Removed."));
		}
		break;
	case 12:
		{
/*
		INFO_PRINTF1(_L("CPalette"));
		TestPalette tpal(this);
		tpal.Test();
*/
		INFO_PRINTF1(_L("CPalette is only for Graphics team. Removed."));
		}
		break;
	case 13:
		{
		INFO_PRINTF1(_L("TDisplayModeUtils"));
		TestDisplayModeUtils tdmu(this);
		tdmu.Test();
		}
		break;
	case 14:
        	((CTTypesStep*)iStep)->SetOverallTestStepID(_L("GRAPHICS-GDI-0001"));
		((CTTypesStep*)iStep)->RecordTestResultL();
		((CTTypesStep*)iStep)->CloseTMSGraphicsStep();
		TestComplete();		
		break;
		}
	}
QString ModelGenerator::generateSqlObject() const
{
    TableSchema ts(tableName);
    QList<QPair<QString, QString> > fieldList = ts.getFieldList();
    if (fieldList.isEmpty()) {
        qCritical("table not found, %s", qPrintable(tableName));
        return QString();
    }

    QString output;

    // Header part
    output += QString(SQLOBJECT_HEADER_TEMPLATE).arg(modelName.toUpper(), modelName);
    QListIterator<QPair<QString, QString> > it(fieldList);
    while (it.hasNext()) {
        const QPair<QString, QString> &p = it.next();
        output += QString("    %1 %2;\n").arg(p.second, p.first);
    }

    // enum part
    output += QLatin1String("\n    enum PropertyIndex {\n");
    it.toFront();
    const QPair<QString, QString> &p = it.next();
    output += QString("        %1 = 0,\n").arg(fieldNameToEnumName(p.first));
    while (it.hasNext()) {
        const QPair<QString, QString> &p = it.next();
        output += QString("        %1,\n").arg(fieldNameToEnumName(p.first));
    }
    output += QLatin1String("    };\n\n");
    
    // primaryKeyIndex() method
    output += QLatin1String("    int primaryKeyIndex() const { return ");
    QString pkName = ts.primaryKeyFieldName();
    if (pkName.isEmpty()) {
        output += QLatin1String("-1; }\n");
    } else {
        output += fieldNameToEnumName(pkName);
        output += QLatin1String("; }\n");
    }

    // auto-value field, for example auto-increment value
    output += QLatin1String("    int autoValueIndex() const { return ");
    QString autoValue = ts.autoValueFieldName();
    if (autoValue.isEmpty()) {
        output += QLatin1String("-1; }\n");
    } else {
        output += fieldNameToEnumName(autoValue);
        output += QLatin1String("; }\n"); 
    }

    // tableName() method
    if (fieldNameToEnumName(tableName) != modelName) {
        output += QLatin1String("    QString tableName() const { return QLatin1String(\"");
        output += tableName;
        output += QLatin1String("\"); }\n\n");
    } else {
        output += "\n";
    }
    
    // Property macros part
    output += QLatin1String("private:    /*** Don't modify below this line ***/\n    Q_OBJECT\n");
    it.toFront();
    while (it.hasNext()) {
        const QPair<QString, QString> &p = it.next();
        output += QString(SQLOBJECT_PROPERTY_TEMPLATE).arg(p.second, p.first);
    }

    // Footer part
    output += QString(SQLOBJECT_FOOTER_TEMPLATE).arg(modelName.toUpper());

    // Writes to a file
    QDir dst(dstDir.filePath("sqlobjects"));
    FileWriter fw(dst.filePath(modelName.toLower() + "object.h"));
    fw.write(output, false);
    return QLatin1String("sqlobjects/") + fw.fileName();
}
QPair<QStringList, QStringList> ModelGenerator::createModelParams() const
{
    QString setgetDecl;
    QString setgetImpl;
    QString crtparams;
    QString getOptDecl;
    QString getOptImpl;
    QString initParams;
    QList<QPair<QString, QString> > writableFields;
    bool optlockMethod = false;
    TableSchema ts(tableName);
    QList<QPair<QString, QString> > fieldList = ts.getFieldList();
    QString autoFieldName = ts.autoValueFieldName();

    for (QListIterator<QPair<QString, QString> > it(fieldList); it.hasNext(); ) {
        const QPair<QString, QString> &p = it.next();
        QString var = fieldNameToVariableName(p.first);

        // Getter method
        setgetDecl += QString("    %1 %2() const;\n").arg(p.second, var);
        setgetImpl += QString("%1 %2::%3() const\n{\n    return d->%4;\n}\n\n").arg(p.second, modelName, var, p.first);

        if (!excludedSetter()->contains(p.first, Qt::CaseInsensitive) && p.first != autoFieldName) {
            // Setter method
            QString str = fieldNameToEnumName(p.first);         
            setgetDecl += QString("    void set%1(%2);\n").arg(str, createParam(p.second, p.first));
            setgetImpl += QString("void %1::set%2(%3)\n{\n    d->%4 = %5;\n}\n\n").arg(modelName, str, createParam(p.second, p.first), p.first, var);

            // Appends to crtparams-string
            crtparams += createParam(p.second, p.first);
            crtparams += ", ";

            writableFields << QPair<QString, QString>(p.first, p.second);

            if (p.second == "int" || p.second == "float" || p.second == "double") {
                initParams += QString("\n    d->") + p.first + " = 0;";
            }
        }
        
        if (p.first == LOCK_REVISION_FIELD) 
            optlockMethod = true;
    }
    crtparams.chop(2);

    initParams += (initParams.isEmpty()) ? ' ' : '\n';

    // Creates parameters of get() method
    int idx = ts.primaryKeyIndex();
    QString getparams;
    if (idx < 0) {
        getparams = crtparams;
    } else {
        const QPair<QString, QString> &pair = fieldList[idx];
        getparams = createParam(pair.second, pair.first);
    }

    // Creates a declaration and a implementation of 'get' method for optimistic lock
    if (idx >= 0 &&optlockMethod) {
        const QPair<QString, QString> &pair = fieldList[idx];
        getOptDecl = QString("    static %1 get(%2, int lockRevision);\n").arg(modelName, createParam(pair.second, pair.first));

        getOptImpl = QString("%1 %1::get(%2, int lockRevision)\n"       \
                             "{\n"                                      \
                             "    TSqlORMapper<%1Object> mapper;\n"     \
                             "    TCriteria cri;\n"                     \
                             "    cri.add(%1Object::%3, %4);\n"         \
                             "    cri.add(%1Object::LockRevision, lockRevision);\n" \
                             "    return %1(mapper.findFirst(cri));\n"  \
                             "}\n\n").arg(modelName, createParam(pair.second, pair.first), fieldNameToEnumName(pair.first), fieldNameToVariableName(pair.first));
    }

    QStringList headerArgs;
    headerArgs << modelName.toUpper() << modelName << setgetDecl << crtparams << getparams << getOptDecl;

    // Creates a model implementation
    QString createImpl;
    createImpl += QString("    %1Object obj;\n").arg(modelName);

    QListIterator<QPair<QString, QString> > fi(writableFields);
    while (fi.hasNext()) {
        const QPair<QString, QString> &p = fi.next();
        createImpl += QString("    obj.%1 = %2;\n").arg(p.first, fieldNameToVariableName(p.first));
    }
    createImpl += "    if (!obj.create()) {\n";
    createImpl += "        obj.clear();\n";
    createImpl += "    }\n";
    createImpl += QString("    return %1(obj);\n").arg(modelName);

    // Creates a implementation of get() method
    QString getImpl;
    if (idx < 0) {
        // If no primary index exists
        getImpl += QString("    TCriteria cri;\n");
        fi.toFront();
        while (fi.hasNext()) {
            const QPair<QString, QString> &p = fi.next();
            getImpl += QString("    cri.add(%1Object::%2, %3);\n").arg(modelName, fieldNameToEnumName(p.first), fieldNameToVariableName(p.first));
        }
    }
    
    getImpl += QString("    TSqlORMapper<%1Object> mapper;\n").arg(modelName);
    getImpl += QString("    return %1(mapper.").arg(modelName);

    if (idx < 0) {
        getImpl += "findFirst(cri));\n";
    } else {
        const QPair<QString, QString> &pair = fieldList[idx];
        getImpl += QString("findByPrimaryKey(%1));\n").arg(fieldNameToVariableName(pair.first));
    }

    QStringList implArgs;
    implArgs << modelName.toLower() << modelName << initParams << setgetImpl << crtparams << createImpl << getparams << getImpl << getOptImpl;

    return QPair<QStringList, QStringList>(headerArgs, implArgs);
}
示例#10
0
    static void _logOpRS(OperationContext* txn,
                         const char *opstr,
                         const char *ns,
                         const char *logNS,
                         const BSONObj& obj,
                         BSONObj *o2,
                         bool *bb,
                         bool fromMigrate ) {
        Lock::DBWrite lk1(txn->lockState(), "local");

        if ( strncmp(ns, "local.", 6) == 0 ) {
            if ( strncmp(ns, "local.slaves", 12) == 0 )
                resetSlaveCache();
            return;
        }

        mutex::scoped_lock lk2(newOpMutex);

        OpTime ts(getNextGlobalOptime());
        newOptimeNotifier.notify_all();

        long long hashNew;
        if( theReplSet ) {
            if (!theReplSet->box.getState().primary()) {
                log() << "replSet error : logOp() but not primary";
                fassertFailed(17405);
            }
            hashNew = (theReplSet->lastH * 131 + ts.asLL()) * 17 + theReplSet->selfId();
        }
        else {
            // must be initiation
            verify( *ns == 0 );
            hashNew = 0;
        }

        /* we jump through a bunch of hoops here to avoid copying the obj buffer twice --
           instead we do a single copy to the destination position in the memory mapped file.
        */

        logopbufbuilder.reset();
        BSONObjBuilder b(logopbufbuilder);
        b.appendTimestamp("ts", ts.asDate());
        b.append("h", hashNew);
        b.append("v", OPLOG_VERSION);
        b.append("op", opstr);
        b.append("ns", ns);
        if (fromMigrate) 
            b.appendBool("fromMigrate", true);
        if ( bb )
            b.appendBool("b", *bb);
        if ( o2 )
            b.append("o2", *o2);
        BSONObj partial = b.done();

        DEV verify( logNS == 0 ); // check this was never a master/slave master

        if ( localOplogRSCollection == 0 ) {
            Client::Context ctx(rsoplog, storageGlobalParams.dbpath);
            localDB = ctx.db();
            verify( localDB );
            localOplogRSCollection = localDB->getCollection( txn, rsoplog );
            massert(13347, "local.oplog.rs missing. did you drop it? if so restart server", localOplogRSCollection);
        }

        Client::Context ctx(rsoplog, localDB);
        OplogDocWriter writer( partial, obj );
        checkOplogInsert( localOplogRSCollection->insertDocument( txn, &writer, false ) );

        /* todo: now() has code to handle clock skew.  but if the skew server to server is large it will get unhappy.
           this code (or code in now() maybe) should be improved.
        */
        if( theReplSet ) {
            if( !(theReplSet->lastOpTimeWritten<ts) ) {
                log() << "replication oplog stream went back in time. previous timestamp: "
                      << theReplSet->lastOpTimeWritten << " newest timestamp: " << ts
                      << ". attempting to sync directly from primary." << endl;
                std::string errmsg;
                BSONObjBuilder result;
                if (!theReplSet->forceSyncFrom(theReplSet->box.getPrimary()->fullName(),
                                               errmsg, result)) {
                    log() << "Can't sync from primary: " << errmsg << endl;
                }
            }
            theReplSet->lastOpTimeWritten = ts;
            theReplSet->lastH = hashNew;
            ctx.getClient()->setLastOp( ts );
        }

    }
void test_assign (charT, const char *cname)
{
    _RWSTD_UNUSED (cname);

    rw_info (0, 0, 0, "Assign member with string parameter");

    typedef std::char_traits<charT>                     Traits;
    typedef std::allocator<charT>                       Allocator;
    typedef std::basic_string<charT, Traits, Allocator> String;

    typedef typename String::size_type size_type;

#ifndef _RWSTD_NO_EXCEPTIONS

    {
        bool threw_error = false;
        String ts(Lit<charT>::testString), nl(Lit<charT>::abc);
        try { ts.assign(nl, nl.length() + 1, String::npos); }
        catch (std::out_of_range) { threw_error = true; }
        
        if(!(threw_error==true))
        {
         failures++;
            std_log(LOG_FILENAME_LINE,"Reason: pos is too large");  
            }
        
        // Threw exception when pos too large
        rw_assert ((threw_error==true), 0, __LINE__, "A1");
    }

#endif   // _RWSTD_NO_EXCEPTIONS

  /*{                 
   String s1, s2, s3, nl;

    s1.assign(nl);
    s2.assign(nl, 0, 5);
    s3.assign(nl, 0, 0);

    // Assigned nullString to nullString
   #ifndef __SYMBIAN32__
    rw_assert ((s1==nl) && (s2==nl) && (s3==nl), 0, __LINE__, "A2");
    rw_assert (   String ().data () == s1.data ()
               && String ().data () == s2.data ()
               && String ().data () == s3.data (),
                  0, __LINE__, "A3");
   #else if
    if(!((s1==nl) && (s2==nl) && (s3==nl))) 
    {
     failures++;
        std_log(LOG_FILENAME_LINE,"Reason: Failing");  
        }
    // Correctly references nullString
         if(!(String ().data () == s1.data ()           //Result is same on linux
               && String ().data () == s2.data ()
               && String ().data () == s3.data ()))
      {
        failures++;
        std_log(LOG_FILENAME_LINE,"Reason: Failing");  
        }
   #endif
                 
  }*/
  {
    String s1, s2, s3, s4, s5, ts(Lit<charT>::testString);

    s1.assign (ts);              // Whole string
    s2.assign (ts, 0, 0);        // None of the string
    s3.assign (ts, 0, 3);        // First three letters
    s4.assign (ts, 5, 6);        // Second word
    s5.assign (ts, 2, 2);        // Middle

    // General Assignments
    
    rw_assert (s1 == ts, 0, __LINE__, "A4.1");
    
    if(!(s1 == ts)) 
    {
     failures++;
        std_log(LOG_FILENAME_LINE,"Reason: Failing");  
        }

    rw_assert (s2 == Lit<charT>::null, 0, __LINE__, "A4.2");
    if(!(s2 == Lit<charT>::null))
    {
     failures++;
        std_log(LOG_FILENAME_LINE,"Reason: Failing");  
        }

    rw_assert (s3 == Lit<charT>::tes, 0, __LINE__, "A4.3");
    if(!(s3 == Lit<charT>::tes)) 
    {
     failures++;
        std_log(LOG_FILENAME_LINE,"Reason: Failing");  
        }

    rw_assert (s4 == Lit<charT>::string, 0, __LINE__, "A4.4");
    if(!(s4 == Lit<charT>::string) )
    {
     failures++;
        std_log(LOG_FILENAME_LINE,"Reason: Failing");  
        }
    
    rw_assert (s5 == Lit<charT>::st, 0, __LINE__, "A4.5");
    if(!(s5 == Lit<charT>::st) )
    {
     failures++;
        std_log(LOG_FILENAME_LINE,"Reason: Failing");  
        }

  }

  rw_info (0, 0, 0, "Assign member with char pointer and maybe count");

  {
    String s1, s2, s3;
    s1.assign (Lit<charT>::null);
    s2.assign (Lit<charT>::null, 0, 5);
    s3.assign (Lit<charT>::null, 0, 0);

    // Assigned nullString to nullString
    rw_assert (   (s1==Lit<charT>::null)
               && (s2==Lit<charT>::null)
               && (s3==Lit<charT>::null),
               0, __LINE__, "A5");

    if(!((s1==Lit<charT>::null)&& (s2==Lit<charT>::null)&& (s3==Lit<charT>::null))) 
    {
     failures++;
        std_log(LOG_FILENAME_LINE,"Reason: Failing");  
        }

    // Correctly references nullString
    rw_assert (   String ().data () == s1.data ()
               && String ().data () == s2.data ()
               && String ().data () == s3.data (),
               0, __LINE__, "A6");
    if(( String ().data () == s1.data ()
               && String ().data () == s2.data ()
               && String ().data () == s3.data ()))
    {
     failures++;
        std_log(LOG_FILENAME_LINE,"Reason: Failing");  
        }
   
 
  }
  {
    const charT * ts = Lit<charT>::testString;
    String s1, s2, s3;
    s1.assign(ts);            // Whole string
    s2.assign(ts, 0, 0);         // None of the string
    s3.assign(ts, 0, 3);         // First three letters

    // General Assignments
    rw_assert (s1 == ts && s2 == Lit<charT>::null && s3 == Lit<charT>::tes,
               0, __LINE__, "A7");
    if(!(s1 == ts && s2 == Lit<charT>::null && s3 == Lit<charT>::tes))
    {
      failures++;
      std_log(LOG_FILENAME_LINE,"Reason: Failing");
      }

  rw_info (0, 0, 0, "Assign member with char and repetition count");

  {
    String s1;
    s1.assign(0, Lit<charT>::space[0]);

    // Assigned nullString to nullString
    rw_assert ((s1==Lit<charT>::null), 0, __LINE__, "A8");
  if(!(s1==Lit<charT>::null))
    {
      failures++;
      std_log(LOG_FILENAME_LINE,"Reason: Failing");
      }

    // Correctly references nullString
    rw_assert (String ().data () == s1.data (), 0, __LINE__, "A9");
   if((String ().data () == s1.data ()))
    {
      failures++;
      std_log(LOG_FILENAME_LINE,"Reason: Failing");
      }

  }
  {
    String s1, s2, s3;
    s1.assign(1, Lit<charT>::x[0]);
    s2.assign(0, Lit<charT>::x[0]);
    s3.assign(3, Lit<charT>::x[0]);

    // General Assignments
    rw_assert (   (s1 == Lit<charT>::x)
               && (s2 == Lit<charT>::null)
               && (s3 == Lit<charT>::xxx),
               0, __LINE__, "A10");
   if(!((s1 == Lit<charT>::x) && (s2 == Lit<charT>::null) && (s3 == Lit<charT>::xxx)))
    {
      failures++;
      std_log(LOG_FILENAME_LINE,"Reason: Failing");
      }

  }
}
}
/*
 *	Measure the time it takes for the logd posting call to make it into
 * the logs. Expect this to be less than double the process wakeup time (2ms).
 */
static void BM_log_delay(int iters) {
    pid_t pid = getpid();

    struct logger_list * logger_list = android_logger_list_open(LOG_ID_EVENTS,
        ANDROID_LOG_RDONLY, 0, pid);

    if (!logger_list) {
        fprintf(stderr, "Unable to open events log: %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    signal(SIGALRM, caught_delay);
    alarm(alarm_time);

    StartBenchmarkTiming();

    for (int i = 0; i < iters; ++i) {
        log_time ts(CLOCK_REALTIME);

        LOG_FAILURE_RETRY(
            android_btWriteLog(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));

        for (;;) {
            log_msg log_msg;
            int ret = android_logger_list_read(logger_list, &log_msg);
            alarm(alarm_time);

            if (ret <= 0) {
                iters = i;
                break;
            }
            if ((log_msg.entry.len != (4 + 1 + 8))
             || (log_msg.id() != LOG_ID_EVENTS)) {
                continue;
            }

            char* eventData = log_msg.msg();

            if (eventData[4] != EVENT_TYPE_LONG) {
                continue;
            }
            log_time tx(eventData + 4 + 1);
            if (ts != tx) {
                if (0xDEADBEEFA55A5AA6ULL == caught_convert(eventData + 4 + 1)) {
                    iters = i;
                    break;
                }
                continue;
            }

            break;
        }
    }

    signal(SIGALRM, SIG_DFL);
    alarm(0);

    StopBenchmarkTiming();

    android_logger_list_free(logger_list);
}
示例#13
0
void Utility::setLaunchOnStartup(const QString &appName, const QString& guiName, bool enable)
{
#if defined(Q_OS_WIN)
    Q_UNUSED(guiName)
    QString runPath = QLatin1String(runPathC);
    QSettings settings(runPath, QSettings::NativeFormat);
    if (enable) {
        settings.setValue(appName, QCoreApplication::applicationFilePath().replace('/','\\'));
    } else {
        settings.remove(appName);
    }
#elif defined(Q_OS_MAC)
    Q_UNUSED(guiName)
    QString filePath = QDir(QCoreApplication::applicationDirPath()+QLatin1String("/../..")).absolutePath();
    CFStringRef folderCFStr = CFStringCreateWithCString(0, filePath.toUtf8().data(), kCFStringEncodingUTF8);
    CFURLRef urlRef = CFURLCreateWithFileSystemPath (0, folderCFStr, kCFURLPOSIXPathStyle, true);
    LSSharedFileListRef loginItems = LSSharedFileListCreate(0, kLSSharedFileListSessionLoginItems, 0);

    if (loginItems && enable) {
        //Insert an item to the list.
        LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(loginItems,
                                                                     kLSSharedFileListItemLast, 0, 0,
                                                                     urlRef, 0, 0);
        if (item)
            CFRelease(item);
        CFRelease(loginItems);
    } else if (loginItems && !enable){
        // We need to iterate over the items and check which one is "ours".
        UInt32 seedValue;
        CFArrayRef itemsArray = LSSharedFileListCopySnapshot(loginItems, &seedValue);
        CFStringRef appUrlRefString = CFURLGetString(urlRef);
        for (int i = 0; i < CFArrayGetCount(itemsArray); i++) {
            LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(itemsArray, i);
            CFURLRef itemUrlRef = NULL;

            if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr) {
                CFStringRef itemUrlString = CFURLGetString(itemUrlRef);
                if (CFStringCompare(itemUrlString,appUrlRefString,0) == kCFCompareEqualTo) {
                    LSSharedFileListItemRemove(loginItems,item); // remove it!
                }
                CFRelease(itemUrlRef);
            }
        }
        CFRelease(itemsArray);
        CFRelease(loginItems);
    };

    CFRelease(folderCFStr);
    CFRelease(urlRef);
#elif defined(Q_OS_UNIX)
    QString userAutoStartPath = QDir::homePath()+QLatin1String("/.config/autostart/");
    QString desktopFileLocation = userAutoStartPath+appName+QLatin1String(".desktop");
    if (enable) {
        if (!QDir().exists(userAutoStartPath) && !QDir().mkdir(userAutoStartPath)) {
            qDebug() << "Could not create autostart directory";
            return;
        }
        QFile iniFile(desktopFileLocation);
        if (!iniFile.open(QIODevice::WriteOnly)) {
            qDebug() << "Could not write auto start entry" << desktopFileLocation;
            return;
        }
        QTextStream ts(&iniFile);
        ts.setCodec("UTF-8");
        ts << QLatin1String("[Desktop Entry]") << endl
           << QLatin1String("Name=") << guiName << endl
           << QLatin1String("GenericName=") << QLatin1String("File Synchronizer") << endl
           << QLatin1String("Exec=") << QCoreApplication::applicationFilePath() << endl
           << QLatin1String("Terminal=") << "false" << endl
           << QLatin1String("Icon=") << appName << endl
           << QLatin1String("Categories=") << QLatin1String("Network") << endl
           << QLatin1String("Type=") << QLatin1String("Application") << endl
           << QLatin1String("StartupNotify=") << "false" << endl
           << QLatin1String("X-GNOME-Autostart-enabled=") << "true" << endl
            ;
    } else {
        if (!QFile::remove(desktopFileLocation)) {
            qDebug() << "Could not remove autostart desktop file";
        }
    }

#endif
}
示例#14
0
TQString TDEStorageDevice::mountEncryptedDevice(TQString passphrase, TQString mediaName, TDEStorageMountOptions mountOptions, TQString* errRet, int* retcode) {
	int internal_retcode;
	if (!retcode) {
		retcode = &internal_retcode;
	}

	TQString ret = mountPath();

	if (!ret.isNull()) {
		return ret;
	}

	// Create dummy password file
	KTempFile passwordFile(TQString::null, "tmp", 0600);
	passwordFile.setAutoDelete(true);
	TQFile* pwFile = passwordFile.file();
	if (!pwFile) {
		return TQString::null;
	}

	pwFile->writeBlock(passphrase.ascii(), passphrase.length());
	pwFile->flush();

	TQString optionString;
	if (mountOptions["ro"] == "true") {
		optionString.append(" -r");
	}
	
	if (mountOptions["atime"] != "true") {
		optionString.append(" -A");
	}
	
	if (mountOptions["utf8"] == "true") {
		optionString.append(" -c utf8");
	}
	
	if (mountOptions["sync"] == "true") {
		optionString.append(" -s");
	}

	if (mountOptions.contains("filesystem") && !mountOptions["filesystem"].isEmpty()) {
		optionString.append(TQString(" -t %1").arg(mountOptions["filesystem"]));
	}

	if (mountOptions.contains("locale")) {
		optionString.append(TQString(" -c %1").arg(mountOptions["locale"]));
	}

	TQString passFileName = passwordFile.name();
	TQString devNode = deviceNode();
	passFileName.replace("'", "'\\''");
	devNode.replace("'", "'\\''");
	mediaName.replace("'", "'\\''");
	TQString command = TQString("pmount -p '%1' %2 '%3' '%4' 2>&1").arg(passFileName).arg(optionString).arg(devNode).arg(mediaName);

	FILE *exepipe = popen(command.local8Bit(), "r");
	if (exepipe) {
		TQString mount_output;
		TQTextStream ts(exepipe, IO_ReadOnly);
		mount_output = ts.read();
		*retcode = pclose(exepipe);
		if (errRet) {
			*errRet = mount_output;
		}
	}

	// Update internal mount data
	TDEGlobal::hardwareDevices()->processModifiedMounts();

	ret = mountPath();

	return ret;
}
示例#15
0
bool Dymola::compile(QFileInfo moPath,QString modelToConsider,QDir storeFolder,QFileInfo logFile,
                      const QFileInfoList & moDeps, QFileInfoList neededFiles)
{
    // Create Dymola script
    QString filePath = storeFolder.absoluteFilePath("MOFirstRun.mos");
    QFile file(filePath);
    if(file.exists())
    {
        file.remove();
    }
    file.open(QIODevice::WriteOnly);

    QString scriptText;
    QString curPath;

    // load dependencies and model
    QFileInfoList moToLoad;
    moToLoad.append(moDeps);
    moToLoad.push_back(moPath);
    LowTools::removeDuplicates(moToLoad);

    for(int i=0;i<moToLoad.size();i++)
    {
        curPath = QDir::fromNativeSeparators(moToLoad.at(i).absoluteFilePath());
        scriptText.append("openModel(\""+curPath+"\",false)\n");
    }


    QString strFolder = QDir::fromNativeSeparators(storeFolder.absolutePath());
    QString logFilePath = QDir::fromNativeSeparators(logFile.absoluteFilePath());

    scriptText.append("cd "+strFolder+"\n");
    scriptText.append("experimentSetupOutput(textual=true)\n");
    scriptText.append("Advanced.StoreProtectedVariables:=true;\n");
    //scriptText.append("checkModel(\""+modelToConsider+"\",simulate=true)\n");
    scriptText.append("translateModel(\""+modelToConsider+"\")\n");
    scriptText.append("compile()\n");
    scriptText.append("savelog(\""+logFilePath+"\")\n");
    scriptText.append("exit\n");

    QTextStream ts( &file );
    ts << scriptText;
    file.close();

    // Copy needed files
    LowTools::copyFilesInFolder(neededFiles,storeFolder);

    // Run script
    QString dymolaPath = MOSettings::value("dymolaExe").toString();
    QFileInfo dymolaBin(dymolaPath);
    if(!dymolaBin.exists())
    {
        InfoSender::instance()->send(Info("Dymola executable not found. Please verify path in Settings",ListInfo::ERROR2));
        return false;
    }
    else
    {
        // delete previous dymosim.exe
        QFile dymoFile(storeFolder.absoluteFilePath("dymosim.exe"));
        if(dymoFile.exists())
            dymoFile.remove();

        // delete previous dsin file
        QFile dsinFile(storeFolder.absoluteFilePath("dsin.txt"));
        if(dsinFile.exists())
            dsinFile.remove();

        // launch script
        QProcess scriptProcess;
        QStringList args;
        args.push_back(filePath);

        //start process
        InfoSender::sendCurrentTask("Launching Dymola...");
        scriptProcess.start(dymolaPath,args);
        bool ok = scriptProcess.waitForFinished(-1);
        if(!ok)
        {
            QString msg("CreateProcess failed");
            InfoSender::instance()->debug(msg);
            return false;
        }

        //look if it succeed
        bool success = dymoFile.exists();
        InfoSender::eraseCurrentTask();
        return success;
    }
}
示例#16
0
 forceinline typename Incremental<View>::SupportEntry*
 Incremental<View>::support(int i, int n) {
   return support_data[(i*(ts()->domsize)) + (n - ts()->min)];
 }
示例#17
0
void Project::parse()
{
    QFile f( filename );
    if ( !f.exists() || !f.open( IO_ReadOnly ) )
	return;
    QTextStream ts( &f );
    QString contents = ts.read();
    f.close();

    proName = QFileInfo( filename ).baseName();

    QStringList::ConstIterator it;

    int i = contents.find( "LANGUAGE" );
    if ( i != -1 ) {
	lang = "";
	is_cpp = FALSE;
	QString part = contents.mid( i + QString( "LANGUAGE" ).length() );
	lang = parse_part( part );
	is_cpp = lang == "C++";
    }

    i = contents.find( "DBFILE" );
    if ( i != -1 ) {
	dbFile = "";
	QString part = contents.mid( i + QString( "DBFILE" ).length() );
	dbFile = parse_part( part );
    }

    QStringList uifiles = parse_multiline_part( contents, "FORMS" );
    uifiles += parse_multiline_part( contents, "INTERFACES" ); // compatibility
    for ( it = uifiles.begin(); it != uifiles.end(); ++it ) {
	if ( (*it).startsWith( "__APPOBJ" ) )
	    continue;
	(void) new FormFile( *it, FALSE, this );
    }


    i = contents.find( "TEMPLATE" );
    if ( i != -1 ) {
	templ = "";
	QString part = contents.mid( i + QString( "TEMPLATE" ).length() );
	templ = parse_part( part );
    }

    readPlatformSettings( contents, "CONFIG", cfg );
    readPlatformSettings( contents, "LIBS", lbs );
    readPlatformSettings( contents, "INCLUDEPATH", inclPath );
    readPlatformSettings( contents, "DEFINES", defs );
    readPlatformSettings( contents, "SOURCES", sources );
    readPlatformSettings( contents, "HEADERS", headers );

    LanguageInterface *iface = MetaDataBase::languageInterface( lang );
    if ( iface ) {
	QStringList sourceKeys;
	iface->sourceProjectKeys( sourceKeys );
	for ( QStringList::Iterator it = sourceKeys.begin(); it != sourceKeys.end(); ++it ) {
	    QStringList lst = parse_multiline_part( contents, *it );
	    for ( QStringList::Iterator it = lst.begin(); it != lst.end(); ++it )
		(void) new SourceFile( *it, FALSE, this );
	}
    }

    updateCustomSettings();

    for ( it = csList.begin(); it != csList.end(); ++it ) {
	i = contents.find( *it );
	if ( i != -1 ) {
	    QString val = "";
	    QString part = contents.mid( i + QString( *it ).length() );
	    val = parse_part( part );
	    customSettings.replace( *it, val );
	}
    }

    loadConnections();

    QStringList images = parse_multiline_part( contents, "IMAGES" );

    // ### remove that for the final - this is beta-compatibility
    if ( images.isEmpty() && QDir( QFileInfo( filename ).dirPath( TRUE ) + "/images" ).exists() ) {
	    images = QDir( QFileInfo( filename ).dirPath( TRUE ) + "/images" ).entryList();
	    for ( int i = 0; i < (int)images.count(); ++i )
		images[ i ].prepend( "images/" );
	    modified = TRUE;
    }

    for ( QStringList::ConstIterator pit = images.begin(); pit != images.end(); ++pit )
	pixCollection->load( *pit );
}
示例#18
0
// File load method.
bool qtractorInstrumentList::load ( const QString& sFilename )
{
	// Open and read from real file.
	QFile file(sFilename);
	if (!file.open(QIODevice::ReadOnly))
		return false;

	// Check for a soundfont...
	if (loadSoundFont(&file)) {
		file.close();
		appendFile(sFilename);
		return true;
	}

	// Check for a MIDINameDocument...
	if (loadMidiNameDocument(&file)) {
		file.close();
		appendFile(sFilename);
		return true;
	}

	// Proceed with regulat Cakewalk .ins file...
	file.seek(0);

	enum FileSection {
		None       = 0,
		PatchNames = 1,
		NoteNames  = 2,
		ControllerNames = 3,
		RpnNames   = 4,
		NrpnNames  = 5,
		InstrDefs  = 6
	} sect = None;

	qtractorInstrument     *pInstrument = NULL;
	qtractorInstrumentData *pData = NULL;

	QRegExp rxTitle   ("^\\[([^\\]]+)\\]$");
	QRegExp rxData    ("^([0-9]+)=(.+)$");
	QRegExp rxBasedOn ("^BasedOn=(.+)$");
	QRegExp rxBankSel ("^BankSelMethod=(0|1|2|3)$");
	QRegExp rxUseNotes("^UsesNotesAsControllers=(0|1)$");
	QRegExp rxControl ("^Control=(.+)$");
	QRegExp rxRpn     ("^RPN=(.+)$");
	QRegExp rxNrpn    ("^NRPN=(.+)$");
	QRegExp rxPatch   ("^Patch\\[([0-9]+|\\*)\\]=(.+)$");
	QRegExp rxKey     ("^Key\\[([0-9]+|\\*),([0-9]+|\\*)\\]=(.+)$");
	QRegExp rxDrum    ("^Drum\\[([0-9]+|\\*),([0-9]+|\\*)\\]=(0|1)$");
	
	const QString s0_127    = "0..127";
	const QString s1_128    = "1..128";
	const QString s0_16383  = "0..16383";
	const QString sAsterisk = "*";

	// Read the file.
	unsigned int iLine = 0;
	QTextStream ts(&file);

	while (!ts.atEnd()) {

		// Read the line.
		++iLine;
		const QString& sLine = ts.readLine().simplified();
		// If not empty, nor a comment, call the server...
		if (sLine.isEmpty() || sLine[0] == ';')
			continue;

		// Check for section intro line...
		if (sLine[0] == '.') {
			if (sLine == ".Patch Names") {
				sect = PatchNames;
			//	m_patches.clear();
				m_patches[s0_127].setName(s0_127);
				m_patches[s1_128].setName(s1_128);
			}
			else if (sLine == ".Note Names") {
				sect = NoteNames;
			//	m_notes.clear();
				m_notes[s0_127].setName(s0_127);
			}
			else if (sLine == ".Controller Names") {
				sect = ControllerNames;
			//	m_controllers.clear();
				m_controllers[s0_127].setName(s0_127);
			}
			else if (sLine == ".RPN Names") {
				sect = RpnNames;
			//	m_rpns.clear();
				m_rpns[s0_16383].setName(s0_16383);
			}
			else if (sLine == ".NRPN Names") {
				sect = NrpnNames;
			//	m_nrpns.clear();
				m_nrpns[s0_16383].setName(s0_16383);
			}
			else if (sLine == ".Instrument Definitions") {
				sect = InstrDefs;
			//  clear();
			}
			else {
				// Unknown section found...
				qWarning("%s(%d): %s: Unknown section.",
					sFilename.toUtf8().constData(), iLine, sLine.toUtf8().constData());
			}
			// Go on...
			continue;
		}

		// Now it depends on the section...
		switch (sect) {
			case PatchNames: {
				if (rxTitle.exactMatch(sLine)) {
					// New patch name...
					const QString& sTitle = rxTitle.cap(1);
					pData = &(m_patches[sTitle]);
					pData->setName(sTitle);
				} else if (rxBasedOn.exactMatch(sLine)) {
					pData->setBasedOn(rxBasedOn.cap(1));
				} else if (rxData.exactMatch(sLine)) {
					(*pData)[rxData.cap(1).toInt()] = rxData.cap(2);
				} else {
					qWarning("%s(%d): %s: Unknown .Patch Names entry.",
						sFilename.toUtf8().constData(), iLine, sLine.toUtf8().constData());
				}
				break;
			}
			case NoteNames: {
				if (rxTitle.exactMatch(sLine)) {
					// New note name...
					const QString& sTitle = rxTitle.cap(1);
					pData = &(m_notes[sTitle]);
					pData->setName(sTitle);
				} else if (rxBasedOn.exactMatch(sLine)) {
					pData->setBasedOn(rxBasedOn.cap(1));
				} else if (rxData.exactMatch(sLine)) {
					(*pData)[rxData.cap(1).toInt()] = rxData.cap(2);
				} else {
					qWarning("%s(%d): %s: Unknown .Note Names entry.",
						sFilename.toUtf8().constData(), iLine, sLine.toUtf8().constData());
				}
				break;
			}
			case ControllerNames: {
				if (rxTitle.exactMatch(sLine)) {
					// New controller name...
					const QString& sTitle = rxTitle.cap(1);
					pData = &(m_controllers[sTitle]);
					pData->setName(sTitle);
				} else if (rxBasedOn.exactMatch(sLine)) {
					pData->setBasedOn(rxBasedOn.cap(1));
				} else if (rxData.exactMatch(sLine)) {
					(*pData)[rxData.cap(1).toInt()] = rxData.cap(2);
				} else {
					qWarning("%s(%d): %s: Unknown .Controller Names entry.",
						sFilename.toUtf8().constData(), iLine, sLine.toUtf8().constData());
				}
				break;
			}
			case RpnNames: {
				if (rxTitle.exactMatch(sLine)) {
					// New RPN name...
					const QString& sTitle = rxTitle.cap(1);
					pData = &(m_rpns[sTitle]);
					pData->setName(sTitle);
				} else if (rxBasedOn.exactMatch(sLine)) {
					pData->setBasedOn(rxBasedOn.cap(1));
				} else if (rxData.exactMatch(sLine)) {
					(*pData)[rxData.cap(1).toInt()] = rxData.cap(2);
				} else {
					qWarning("%s(%d): %s: Unknown .RPN Names entry.",
						sFilename.toUtf8().constData(), iLine, sLine.toUtf8().constData());
				}
				break;
			}
			case NrpnNames: {
				if (rxTitle.exactMatch(sLine)) {
					// New NRPN name...
					const QString& sTitle = rxTitle.cap(1);
					pData = &(m_nrpns[sTitle]);
					pData->setName(sTitle);
				} else if (rxBasedOn.exactMatch(sLine)) {
					pData->setBasedOn(rxBasedOn.cap(1));
				} else if (rxData.exactMatch(sLine)) {
					(*pData)[rxData.cap(1).toInt()] = rxData.cap(2);
				} else {
					qWarning("%s(%d): %s: Unknown .NRPN Names entry.",
						sFilename.toUtf8().constData(), iLine, sLine.toUtf8().constData());
				}
				break;
			}
			case InstrDefs: {
				if (rxTitle.exactMatch(sLine)) {
					// New instrument definition...
					const QString& sTitle = rxTitle.cap(1);
					pInstrument = &((*this)[sTitle]);
					pInstrument->setInstrumentName(sTitle);
				} else if (rxBankSel.exactMatch(sLine)) {
					pInstrument->setBankSelMethod(
						rxBankSel.cap(1).toInt());
				} else if (rxUseNotes.exactMatch(sLine)) {
					pInstrument->setUsesNotesAsControllers(
						(bool) rxBankSel.cap(1).toInt());
				} else if (rxPatch.exactMatch(sLine)) {
					int iBank = (rxPatch.cap(1) == sAsterisk
						? -1 : rxPatch.cap(1).toInt());
					pInstrument->setPatch(iBank, m_patches[rxPatch.cap(2)]);
				} else if (rxControl.exactMatch(sLine)) {
					pInstrument->setControllers(m_controllers[rxControl.cap(1)]);
				} else if (rxRpn.exactMatch(sLine)) {
					pInstrument->setRpns(m_rpns[rxRpn.cap(1)]);
				} else if (rxNrpn.exactMatch(sLine)) {
					pInstrument->setNrpns(m_nrpns[rxNrpn.cap(1)]);
				} else if (rxKey.exactMatch(sLine)) {
					int iBank = (rxKey.cap(1) == sAsterisk
						? -1 : rxKey.cap(1).toInt());
					int iProg = (rxKey.cap(2) == sAsterisk
						? -1 : rxKey.cap(2).toInt());
					pInstrument->setNotes(iBank, iProg,	m_notes[rxKey.cap(3)]);
				} else if (rxDrum.exactMatch(sLine)) {
					const int iBank = (rxDrum.cap(1) == sAsterisk
						? -1 : rxDrum.cap(1).toInt());
					const int iProg = (rxDrum.cap(2) == sAsterisk
						? -1 : rxKey.cap(2).toInt());
					pInstrument->setDrum(iBank, iProg,
						(bool) rxDrum.cap(3).toInt());
				} else {
					qWarning("%s(%d): %s: Unknown .Instrument Definitions entry.",
						sFilename.toUtf8().constData(), iLine, sLine.toUtf8().constData());
				}
				break;
			}
			default:
				break;
		}
	}

	// Ok. We've read it all.
	file.close();

	// We're in business...
	appendFile(sFilename);

	return true;
}
示例#19
0
void Project::saveConnections()
{
#ifndef QT_NO_SQL
    if ( dbFile.isEmpty() ) {
	QFileInfo fi( fileName() );
	setDatabaseDescription( fi.baseName() + ".db" );
    }

    QFile f( makeAbsolute( dbFile ) );

    if ( dbConnections.isEmpty() ) {
	if ( f.exists() )
	    f.remove();
	setDatabaseDescription( "" );
	modified = TRUE;
	return;
    }

    /* .db xml */
    if ( f.open( IO_WriteOnly | IO_Translate ) ) {
	QTextStream ts( &f );
	ts.setCodec( QTextCodec::codecForName( "UTF-8" ) );
	ts << "<!DOCTYPE DB><DB version=\"1.0\">" << endl;

	/* db connections */
	int indent = 0;
	for ( DatabaseConnection *conn = dbConnections.first(); conn; conn = dbConnections.next() ) {
	    ts << makeIndent( indent ) << "<connection>" << endl;
	    ++indent;
	    saveSingleProperty( ts, "name", conn->name(), indent );
	    saveSingleProperty( ts, "driver", conn->driver(), indent );
	    saveSingleProperty( ts, "database", conn->database(), indent );
	    saveSingleProperty( ts, "username", conn->username(), indent );
	    saveSingleProperty( ts, "hostname", conn->hostname(), indent );
	    saveSingleProperty( ts, "port", QString::number( conn->port() ), indent );

	    /* connection tables */
	    QStringList tables = conn->tables();
	    for ( QStringList::Iterator it = tables.begin();
		  it != tables.end(); ++it ) {
		ts << makeIndent( indent ) << "<table>" << endl;
		++indent;
		saveSingleProperty( ts, "name", (*it), indent );

		/* tables fields */
		QStringList fields = conn->fields( *it );
		for ( QStringList::Iterator it2 = fields.begin();
		      it2 != fields.end(); ++it2 ) {
		    ts << makeIndent( indent ) << "<field>" << endl;
		    ++indent;
		    saveSingleProperty( ts, "name", (*it2), indent );
		    --indent;
		    ts << makeIndent( indent ) << "</field>" << endl;
		}

		--indent;
		ts << makeIndent( indent ) << "</table>" << endl;
	    }

	    --indent;
	    ts << makeIndent( indent ) << "</connection>" << endl;
	}

	ts << "</DB>" << endl;
	f.close();
    }
#endif
}
示例#20
0
// File save method.
bool qtractorInstrumentList::save ( const QString& sFilename ) const
{
    // Open and write into real file.
    QFile file(sFilename);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate))
        return false;

	// A visula separator line.
	const QString sepl = "; -----------------------------"
		"------------------------------------------------";

    // Write the file.
    QTextStream ts(&file);

    ts << sepl << endl;
	ts << "; " << QObject::tr("Cakewalk Instrument Definition File") << endl;
/*
    ts << ";"  << endl;
    ts << "; " << QTRACTOR_TITLE " - " << QObject::tr(QTRACTOR_SUBTITLE) << endl;
    ts << "; " << QObject::tr("Version")
       << ": " QTRACTOR_VERSION << endl;
    ts << "; " << QObject::tr("Build")
       << ": " __DATE__ " " __TIME__ << endl;
*/
    ts << ";"  << endl;
    ts << "; " << QObject::tr("File")
       << ": " << QFileInfo(sFilename).fileName() << endl;
    ts << "; " << QObject::tr("Date")
       << ": " << QDate::currentDate().toString("MMM dd yyyy")
       << " "  << QTime::currentTime().toString("hh:mm:ss") << endl;
    ts << ";"  << endl;

	// - Patch Names...
    ts << sepl << endl << endl;
	ts << ".Patch Names" << endl;
	saveDataList(ts, m_patches);

	// - Note Names...
    ts << sepl << endl << endl;
	ts << ".Note Names" << endl;
	saveDataList(ts, m_notes);

	// - Controller Names...
    ts << sepl << endl << endl;
	ts << ".Controller Names" << endl;
	saveDataList(ts, m_controllers);

	// - RPN Names...
    ts << sepl << endl << endl;
	ts << ".RPN Names" << endl;
	saveDataList(ts, m_rpns);

	// - NRPN Names...
    ts << sepl << endl << endl;
	ts << ".NRPN Names" << endl;
	saveDataList(ts, m_nrpns);

	// - Instrument Definitions...
    ts << sepl << endl << endl;
	ts << ".Instrument Definitions" << endl;
    ts << endl;
	qtractorInstrumentList::ConstIterator iter = constBegin();
	const qtractorInstrumentList::ConstIterator& iter_end = constEnd();
	for ( ; iter != iter_end; ++iter) {
		const qtractorInstrument& instr = *iter;
		ts << "[" << instr.instrumentName() << "]" << endl;
		if (instr.bankSelMethod() > 0)
		    ts << "BankSelMethod=" << instr.bankSelMethod() << endl;
		if (!instr.controllers().name().isEmpty())
			ts << "Control=" << instr.controllers().name() << endl;
		if (!instr.rpns().name().isEmpty())
			ts << "RPN=" << instr.rpns().name() << endl;
		if (!instr.nrpns().name().isEmpty())
			ts << "NRPN=" << instr.nrpns().name() << endl;
		// - Patches...
		const qtractorInstrumentPatches& patches = instr.patches();
		qtractorInstrumentPatches::ConstIterator pit = patches.constBegin();
		const qtractorInstrumentPatches::ConstIterator& pit_end = patches.constEnd();
		for ( ;	pit != pit_end; ++pit) {
			const QString& sPatch = pit.value().name();
			if (!sPatch.isEmpty()) {
				int iBank = pit.key();
				const QString& sBank = (iBank < 0
					? QString("*") : QString::number(iBank));
				ts << "Patch[" << sBank << "]="
				   << sPatch << endl;
			}
		}
		// - Keys...
		const qtractorInstrumentKeys& keys = instr.keys();
		qtractorInstrumentKeys::ConstIterator kit = keys.constBegin();
		const qtractorInstrumentKeys::ConstIterator kit_end = keys.constEnd();
		for ( ; kit != kit_end; ++kit) {
			const int iBank = kit.key();
			const QString& sBank = (iBank < 0
				? QString("*") : QString::number(iBank));
			const qtractorInstrumentNotes& notes = kit.value();
			qtractorInstrumentNotes::ConstIterator nit = notes.constBegin();
			const qtractorInstrumentNotes::ConstIterator& nit_end = notes.constEnd();
			for ( ; nit != nit_end; ++nit) {
				const QString& sKey = nit.value().name();
				if (!sKey.isEmpty()) {
					const int iProg = nit.key();
					const QString& sProg = (iProg < 0
						? QString("*") : QString::number(iProg));
					ts << "Key[" << sBank << "," << sProg << "]="
					   << sKey << endl;
				}
			}
		}
		// - Drums...
		const qtractorInstrumentDrums& drums = instr.drums();
		qtractorInstrumentDrums::ConstIterator dit = drums.constBegin();
		const qtractorInstrumentDrums::ConstIterator& dit_end = drums.constEnd();
		for ( ; dit != dit_end; ++dit) {
			const int iBank = dit.key();
			const QString& sBank = (iBank < 0
				? QString("*") : QString::number(iBank));
			const qtractorInstrumentDrumFlags& flags = dit.value();
			qtractorInstrumentDrumFlags::ConstIterator fit = flags.constBegin();
			const qtractorInstrumentDrumFlags::ConstIterator& fit_end = flags.constEnd();
			for ( ; fit != fit_end; ++fit) {
				const int iProg = fit.key();
				const QString& sProg = (iProg < 0
					? QString("*") : QString::number(iProg));
				ts << "Drum[" << sBank << "," << sProg << "]="
				   << fit.value() << endl;
			}
		}
		ts << endl;
	}

	// Done.
    file.close();

	return true;
}
示例#21
0
int main( int argc, char * * argv )
{
	// initialize memory managers
	MemoryManager::init();
	NotePlayHandleManager::init();

	// intialize RNG
	srand( getpid() + time( 0 ) );

	disable_denormals();

	bool coreOnly = false;
	bool fullscreen = true;
	bool exitAfterImport = false;
	bool allowRoot = false;
	bool renderLoop = false;
	bool renderTracks = false;
	QString fileToLoad, fileToImport, renderOut, profilerOutputFile, configFile;

	// first of two command-line parsing stages
	for( int i = 1; i < argc; ++i )
	{
		QString arg = argv[i];

		if( arg == "--help"    || arg == "-h" ||
		    arg == "--version" || arg == "-v" ||
		    arg == "--render"  || arg == "-r" )
		{
			coreOnly = true;
		}
		else if( arg == "--rendertracks" )
		{
			coreOnly = true;
			renderTracks = true;
		}
		else if( arg == "--allowroot" )
		{
			allowRoot = true;
		}
		else if( arg == "--geometry" || arg == "-geometry")
		{
			if( arg == "--geometry" )
			{
				// Delete the first "-" so Qt recognize the option
				strcpy(argv[i], "-geometry");
			}
			// option -geometry is filtered by Qt later,
			// so we need to check its presence now to
			// determine, if the application should run in
			// fullscreen mode (default, no -geometry given).
			fullscreen = false;
		}
	}

#ifndef LMMS_BUILD_WIN32
	if ( ( getuid() == 0 || geteuid() == 0 ) && !allowRoot )
	{
		printf( "LMMS cannot be run as root.\nUse \"--allowroot\" to override.\n\n" );
		return EXIT_FAILURE;
	}	
#endif

	QCoreApplication * app = coreOnly ?
			new QCoreApplication( argc, argv ) :
					new QApplication( argc, argv ) ;

	Mixer::qualitySettings qs( Mixer::qualitySettings::Mode_HighQuality );
	ProjectRenderer::OutputSettings os( 44100, false, 160,
						ProjectRenderer::Depth_16Bit );
	ProjectRenderer::ExportFileFormats eff = ProjectRenderer::WaveFile;

	// second of two command-line parsing stages
	for( int i = 1; i < argc; ++i )
	{
		QString arg = argv[i];

		if( arg == "--version" || arg == "-v" )
		{
			printVersion( argv[0] );
			return EXIT_SUCCESS;
		}
		else if( arg == "--help" || arg  == "-h" )
		{
			printHelp();
			return EXIT_SUCCESS;
		}
		else if( arg == "--upgrade" || arg == "-u" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo input file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			DataFile dataFile( QString::fromLocal8Bit( argv[i] ) );

			if( argc > i+1 ) // output file specified
			{
				dataFile.writeFile( QString::fromLocal8Bit( argv[i+1] ) );
			}
			else // no output file specified; use stdout
			{
				QTextStream ts( stdout );
				dataFile.write( ts );
				fflush( stdout );
			}

			return EXIT_SUCCESS;
		}
		else if( arg == "--allowroot" )
		{
			// Ignore, processed earlier
#ifdef LMMS_BUILD_WIN32
			if( allowRoot )
			{
				printf( "\nOption \"--allowroot\" will be ignored on this platform.\n\n" );
			}
#endif
			
		}
		else if( arg == "--dump" || arg == "-d" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo input file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			QFile f( QString::fromLocal8Bit( argv[i] ) );
			f.open( QIODevice::ReadOnly );
			QString d = qUncompress( f.readAll() );
			printf( "%s\n", d.toUtf8().constData() );

			return EXIT_SUCCESS;
		}
		else if( arg == "--render" || arg == "-r" || arg == "--rendertracks" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo input file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			fileToLoad = QString::fromLocal8Bit( argv[i] );
			renderOut = fileToLoad;
		}
		else if( arg == "--loop" || arg == "-l" )
		{
			renderLoop = true;
		}
		else if( arg == "--output" || arg == "-o" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo output file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			renderOut = QString::fromLocal8Bit( argv[i] );
		}
		else if( arg == "--format" || arg == "-f" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo output format specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			const QString ext = QString( argv[i] );

			if( ext == "wav" )
			{
				eff = ProjectRenderer::WaveFile;
			}
#ifdef LMMS_HAVE_OGGVORBIS
			else if( ext == "ogg" )
			{
				eff = ProjectRenderer::OggFile;
			}
#endif
			else
			{
				printf( "\nInvalid output format %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--samplerate" || arg == "-s" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo samplerate specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			sample_rate_t sr = QString( argv[i] ).toUInt();
			if( sr >= 44100 && sr <= 192000 )
			{
				os.samplerate = sr;
			}
			else
			{
				printf( "\nInvalid samplerate %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--bitrate" || arg == "-b" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo bitrate specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			int br = QString( argv[i] ).toUInt();

			if( br >= 64 && br <= 384 )
			{
				os.bitrate = br;
			}
			else
			{
				printf( "\nInvalid bitrate %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg =="--float" || arg == "-a" )
		{
			os.depth = ProjectRenderer::Depth_32Bit;
		}
		else if( arg == "--interpolation" || arg == "-i" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo interpolation method specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			const QString ip = QString( argv[i] );

			if( ip == "linear" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_Linear;
			}
			else if( ip == "sincfastest" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincFastest;
			}
			else if( ip == "sincmedium" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincMedium;
			}
			else if( ip == "sincbest" )
			{
		qs.interpolation = Mixer::qualitySettings::Interpolation_SincBest;
			}
			else
			{
				printf( "\nInvalid interpolation method %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--oversampling" || arg == "-x" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo oversampling specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			int o = QString( argv[i] ).toUInt();

			switch( o )
			{
				case 1:
		qs.oversampling = Mixer::qualitySettings::Oversampling_None;
		break;
				case 2:
		qs.oversampling = Mixer::qualitySettings::Oversampling_2x;
		break;
				case 4:
		qs.oversampling = Mixer::qualitySettings::Oversampling_4x;
		break;
				case 8:
		qs.oversampling = Mixer::qualitySettings::Oversampling_8x;
		break;
				default:
				printf( "\nInvalid oversampling %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
		}
		else if( arg == "--import" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo file specified for importing.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			fileToImport = QString::fromLocal8Bit( argv[i] );

			// exit after import? (only for debugging)
			if( QString( argv[i + 1] ) == "-e" )
			{
				exitAfterImport = true;
				++i;
			}
		}
		else if( arg == "--profile" || arg == "-p" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo profile specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}


			profilerOutputFile = QString::fromLocal8Bit( argv[i] );
		}
		else if( arg == "--config" || arg == "-c" )
		{
			++i;

			if( i == argc )
			{
				printf( "\nNo configuration file specified.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[0] );
				return EXIT_FAILURE;
			}

			configFile = QString::fromLocal8Bit( argv[i] );
		}
		else
		{
			if( argv[i][0] == '-' )
			{
				printf( "\nInvalid option %s.\n\n"
	"Try \"%s --help\" for more information.\n\n", argv[i], argv[0] );
				return EXIT_FAILURE;
			}
			fileToLoad = QString::fromLocal8Bit( argv[i] );
		}
	}

	// Test file argument before continuing
	if( !fileToLoad.isEmpty() )
	{
		fileCheck( fileToLoad );
	}
	else if( !fileToImport.isEmpty() )
	{
		fileCheck( fileToImport );
	}

	ConfigManager::inst()->loadConfigFile(configFile);

	// set language
	QString pos = ConfigManager::inst()->value( "app", "language" );
	if( pos.isEmpty() )
	{
		pos = QLocale::system().name().left( 2 );
	}

#ifdef LMMS_BUILD_WIN32
#undef QT_TRANSLATIONS_DIR
#define QT_TRANSLATIONS_DIR ConfigManager::inst()->localeDir()
#endif

#ifdef QT_TRANSLATIONS_DIR
	// load translation for Qt-widgets/-dialogs
	loadTranslation( QString( "qt_" ) + pos,
					QString( QT_TRANSLATIONS_DIR ) );
#endif
	// load actual translation for LMMS
	loadTranslation( pos );


	// try to set realtime priority
#ifdef LMMS_BUILD_LINUX
#ifdef LMMS_HAVE_SCHED_H
#ifndef __OpenBSD__
	struct sched_param sparam;
	sparam.sched_priority = ( sched_get_priority_max( SCHED_FIFO ) +
				sched_get_priority_min( SCHED_FIFO ) ) / 2;
	if( sched_setscheduler( 0, SCHED_FIFO, &sparam ) == -1 )
	{
		printf( "Notice: could not set realtime priority.\n" );
	}
#endif
#endif
#endif

#ifdef LMMS_BUILD_WIN32
	if( !SetPriorityClass( GetCurrentProcess(), HIGH_PRIORITY_CLASS ) )
	{
		printf( "Notice: could not set high priority.\n" );
	}
#endif

#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
	struct sigaction sa;
	sa.sa_handler = SIG_IGN;
	sa.sa_flags = SA_SIGINFO;
	if ( sigemptyset( &sa.sa_mask ) )
	{
		fprintf( stderr, "Signal initialization failed.\n" );
	}
	if ( sigaction( SIGPIPE, &sa, NULL ) )
	{
		fprintf( stderr, "Signal initialization failed.\n" );
	}
#endif

	bool destroyEngine = false;

	// if we have an output file for rendering, just render the song
	// without starting the GUI
	if( !renderOut.isEmpty() )
	{
		Engine::init( true );
		destroyEngine = true;

		printf( "Loading project...\n" );
		Engine::getSong()->loadProject( fileToLoad );
		if( Engine::getSong()->isEmpty() )
		{
			printf("The project %s is empty, aborting!\n", fileToLoad.toUtf8().constData() );
			exit( EXIT_FAILURE );
		}
		printf( "Done\n" );

		Engine::getSong()->setExportLoop( renderLoop );

		// when rendering multiple tracks, renderOut is a directory
		// otherwise, it is a file, so we need to append the file extension
		if ( !renderTracks )
		{
			renderOut = baseName( renderOut ) +
				ProjectRenderer::getFileExtensionFromFormat(eff);
		}

		// create renderer
		RenderManager * r = new RenderManager( qs, os, eff, renderOut );
		QCoreApplication::instance()->connect( r,
				SIGNAL( finished() ), SLOT( quit() ) );

		// timer for progress-updates
		QTimer * t = new QTimer( r );
		r->connect( t, SIGNAL( timeout() ),
				SLOT( updateConsoleProgress() ) );
		t->start( 200 );

		if( profilerOutputFile.isEmpty() == false )
		{
			Engine::mixer()->profiler().setOutputFile( profilerOutputFile );
		}

		// start now!
		if ( renderTracks )
		{
			r->renderTracks();
		}
		else
		{
			r->renderProject();
		}
	}
	else // otherwise, start the GUI
	{
		new GuiApplication();

		// re-intialize RNG - shared libraries might have srand() or
		// srandom() calls in their init procedure
		srand( getpid() + time( 0 ) );

		// recover a file?
		QString recoveryFile = ConfigManager::inst()->recoveryFile();

		bool recoveryFilePresent = QFileInfo( recoveryFile ).exists() &&
				QFileInfo( recoveryFile ).isFile();
		bool autoSaveEnabled =
			!ConfigManager::inst()->value( "ui", "disableautosave" ).toInt();
		if( recoveryFilePresent )
		{
			QMessageBox mb;
			mb.setWindowTitle( MainWindow::tr( "Project recovery" ) );
			mb.setText( QString(
				"<html>"
				"<p style=\"margin-left:6\">%1</p>"
				"<table cellpadding=\"3\">"
				"  <tr>"
				"    <td><b>%2</b></td>"
				"    <td>%3</td>"
				"  </tr>"
				"  <tr>"
				"    <td><b>%4</b></td>"
				"    <td>%5</td>"
				"  </tr>"
				"  <tr>"
				"    <td><b>%6</b></td>"
				"    <td>%7</td>"
				"  </tr>"
				"</table>"
				"</html>" ).arg(
				MainWindow::tr( "There is a recovery file present. "
					"It looks like the last session did not end "
					"properly or another instance of LMMS is "
					"already running. Do you want to recover the "
					"project of this session?" ),
				MainWindow::tr( "Recover" ),
				MainWindow::tr( "Recover the file. Please don't run "
					"multiple instances of LMMS when you do this." ),
				MainWindow::tr( "Ignore" ),
				MainWindow::tr( "Launch LMMS as usual but with "
					"automatic backup disabled to prevent the "
					"present recover file from being overwritten." ),
				MainWindow::tr( "Discard" ),
				MainWindow::tr( "Launch a default session and delete "
					"the restored files. This is not reversible." )
							) );

			mb.setIcon( QMessageBox::Warning );
			mb.setWindowIcon( embed::getIconPixmap( "icon" ) );
			mb.setWindowFlags( Qt::WindowCloseButtonHint );

			QPushButton * recover;
			QPushButton * discard;
			QPushButton * ignore;
			QPushButton * exit;
			
			#if QT_VERSION >= 0x050000
				// setting all buttons to the same roles allows us 
				// to have a custom layout
				discard = mb.addButton( MainWindow::tr( "Discard" ),
									QMessageBox::AcceptRole );
				ignore = mb.addButton( MainWindow::tr( "Ignore" ),
									QMessageBox::AcceptRole );
				recover = mb.addButton( MainWindow::tr( "Recover" ),
									QMessageBox::AcceptRole );

			# else 
				// in qt4 the button order is reversed
				recover = mb.addButton( MainWindow::tr( "Recover" ),
									QMessageBox::AcceptRole );
				ignore = mb.addButton( MainWindow::tr( "Ignore" ),
									QMessageBox::AcceptRole );
				discard = mb.addButton( MainWindow::tr( "Discard" ),
									QMessageBox::AcceptRole );

			#endif
			
			// have a hidden exit button
			exit = mb.addButton( "", QMessageBox::RejectRole);
			exit->setVisible(false);
			
			// set icons
			recover->setIcon( embed::getIconPixmap( "recover" ) );
			discard->setIcon( embed::getIconPixmap( "discard" ) );
			ignore->setIcon( embed::getIconPixmap( "ignore" ) );

			mb.setDefaultButton( recover );
			mb.setEscapeButton( exit );

			mb.exec();
			if( mb.clickedButton() == discard )
			{
				gui->mainWindow()->sessionCleanup();
			}
			else if( mb.clickedButton() == recover ) // Recover
			{
				fileToLoad = recoveryFile;
				gui->mainWindow()->setSession( MainWindow::SessionState::Recover );
			}
			else if( mb.clickedButton() == ignore )
			{
				if( autoSaveEnabled )
				{
					gui->mainWindow()->setSession( MainWindow::SessionState::Limited );
				}
			}
			else // Exit
			{
				return 0;
			}
		}

		// first show the Main Window and then try to load given file

		// [Settel] workaround: showMaximized() doesn't work with
		// FVWM2 unless the window is already visible -> show() first
		gui->mainWindow()->show();
		if( fullscreen )
		{
			gui->mainWindow()->showMaximized();
		}

		if( !fileToLoad.isEmpty() )
		{
			if( fileToLoad == recoveryFile )
			{
				Engine::getSong()->createNewProjectFromTemplate( fileToLoad );
			}
			else
			{
				Engine::getSong()->loadProject( fileToLoad );
			}
		}
		else if( !fileToImport.isEmpty() )
		{
			ImportFilter::import( fileToImport, Engine::getSong() );
			if( exitAfterImport )
			{
				return EXIT_SUCCESS;
			}
		}
		// If enabled, open last project if there is one. Else, create
		// a new one. Also skip recently opened file if limited session to
		// lower the chance of opening an already opened file.
		else if( ConfigManager::inst()->
				value( "app", "openlastproject" ).toInt() &&
			!ConfigManager::inst()->
				recentlyOpenedProjects().isEmpty() &&
			gui->mainWindow()->getSession() !=
				MainWindow::SessionState::Limited )
		{
			QString f = ConfigManager::inst()->
					recentlyOpenedProjects().first();
			QFileInfo recentFile( f );

			if ( recentFile.exists() )
			{
				Engine::getSong()->loadProject( f );
			}
			else
			{
				Engine::getSong()->createNewProject();
			}
		}
		else
		{
			Engine::getSong()->createNewProject();
		}

		// Finally we start the auto save timer and also trigger the
		// autosave one time as recover.mmp is a signal to possible other
		// instances of LMMS.
		if( autoSaveEnabled &&
			gui->mainWindow()->getSession() != MainWindow::SessionState::Limited )
		{
			gui->mainWindow()->autoSaveTimerReset();
			gui->mainWindow()->autoSave();
		}
	}

	const int ret = app->exec();
	delete app;

	if( destroyEngine )
	{
		Engine::destroy();
	}

	// cleanup memory managers
	MemoryManager::cleanup();

	// ProjectRenderer::updateConsoleProgress() doesn't return line after render
	if( coreOnly )
	{
		printf( "\n" );
	}

	return ret;
}
示例#22
0
bool
DspMakefileGenerator::writeDspParts(QTextStream &t)
{
    QString dspfile;
    if ( !project->variables()["DSP_TEMPLATE"].isEmpty() ) {
	dspfile = project->first("DSP_TEMPLATE");
    } else {
	dspfile = project->first("MSVCDSP_TEMPLATE");
    }
    if (dspfile.startsWith("\"") && dspfile.endsWith("\""))
	dspfile = dspfile.mid(1, dspfile.length() - 2);
    QString dspfile_loc = findTemplate(dspfile);

    QFile file(dspfile_loc);
    if(!file.open(IO_ReadOnly)) {
	fprintf(stderr, "Cannot open dsp file: %s\n", dspfile.latin1());
	return FALSE;
    }
    QTextStream dsp(&file);

    QString platform = "Win32";
    if ( !project->variables()["QMAKE_PLATFORM"].isEmpty() )
	platform = varGlue("QMAKE_PLATFORM", "", " ", "");

    // Setup PCH variables
    precompH = project->first("PRECOMPILED_HEADER");
    QString namePCH = QFileInfo(precompH).fileName();
    usePCH = !precompH.isEmpty() && project->isActiveConfig("precompile_header");
    if (usePCH) {
	// Created files
	QString origTarget = project->first("QMAKE_ORIG_TARGET");
	origTarget.replace(QRegExp("-"), "_");
	precompObj = "\"$(IntDir)\\" + origTarget + Option::obj_ext + "\"";
	precompPch = "\"$(IntDir)\\" + origTarget + ".pch\"";
	// Add PRECOMPILED_HEADER to HEADERS
	if (!project->variables()["HEADERS"].contains(precompH))
	    project->variables()["HEADERS"] += precompH;
	// Add precompile compiler options
	project->variables()["PRECOMPILED_FLAGS_REL"]  = "/Yu\"" + namePCH + "\" /FI\"" + namePCH + "\" ";
	project->variables()["PRECOMPILED_FLAGS_DEB"]  = "/Yu\"" + namePCH + "\" /FI\"" + namePCH + "\" ";
	// Return to variable pool
	project->variables()["PRECOMPILED_OBJECT"] = precompObj;
	project->variables()["PRECOMPILED_PCH"]    = precompPch;
    }
    int rep;
    QString line;
    while ( !dsp.eof() ) {
	line = dsp.readLine();
	while((rep = line.find(QRegExp("\\$\\$[a-zA-Z0-9_-]*"))) != -1) {
	    QString torep = line.mid(rep, line.find(QRegExp("[^\\$a-zA-Z0-9_-]"), rep) - rep);
	    QString variable = torep.right(torep.length()-2);

	    t << line.left(rep); //output the left side
	    line = line.right(line.length() - (rep + torep.length())); //now past the variable
	    if(variable == "MSVCDSP_SOURCES") {
		if(project->variables()["SOURCES"].isEmpty())
		    continue;

		QString mocpath = var( "QMAKE_MOC" );
		mocpath = mocpath.replace( QRegExp( "\\..*$" ), "" ) + " ";

		QStringList list = project->variables()["SOURCES"] + project->variables()["DEF_FILE"];
		if(!project->isActiveConfig("flat"))
		    list.sort();
		QStringList::Iterator it;
		for( it = list.begin(); it != list.end(); ++it) {
		    beginGroupForFile((*it), t);
		    t << "# Begin Source File\n\nSOURCE=" << (*it) << endl;
		    if (usePCH && (*it).endsWith(".c"))
			t << "# SUBTRACT CPP /FI\"" << namePCH << "\" /Yu\"" << namePCH << "\" /Fp" << endl;
		    if ( project->isActiveConfig("moc") && (*it).endsWith(Option::cpp_moc_ext)) {
			QString base = (*it);
			base.replace(QRegExp("\\..*$"), "").upper();
			base.replace(QRegExp("[^a-zA-Z]"), "_");

			QString build = "\n\n# Begin Custom Build - Moc'ing " + findMocSource((*it)) +
					"...\n" "InputPath=.\\" + (*it) + "\n\n" "\"" + (*it) + "\""
					" : $(SOURCE) \"$(INTDIR)\" \"$(OUTDIR)\"\n"
					"\t" + mocpath + findMocSource((*it)) + " -o " +
					(*it) + "\n\n" "# End Custom Build\n\n";

			t << "USERDEP_" << base << "=\".\\" << findMocSource((*it)) << "\" \"$(QTDIR)\\bin\\moc.exe\"" << endl << endl;

			t << "!IF  \"$(CFG)\" == \"" << var("MSVCDSP_PROJECT") << " - " << platform << " Release\"" << build
			  << "!ELSEIF  \"$(CFG)\" == \"" << var("MSVCDSP_PROJECT") << " - " << platform << " Debug\""
			  << build << "!ENDIF " << endl << endl;
		    }
		    t << "# End Source File" << endl;
		}
		endGroups(t);
	    } else if(variable == "MSVCDSP_IMAGES") {
		if(project->variables()["IMAGES"].isEmpty())
		    continue;
		t << "# Begin Source File\n\nSOURCE=" << project->first("QMAKE_IMAGE_COLLECTION") << endl;
		t << "# End Source File" << endl;
	    } else if(variable == "MSVCDSP_HEADERS") {
		if(project->variables()["HEADERS"].isEmpty())
		    continue;

		QStringList list = project->variables()["HEADERS"];
		if(!project->isActiveConfig("flat"))
		    list.sort();
		for(QStringList::Iterator it = list.begin(); it != list.end(); ++it) {
//		    beginGroupForFile((*it), t);
		    t << "# Begin Source File\n\nSOURCE=" << (*it) << endl << endl;
		    QString compilePCH;
		    QStringList customDependencies;
		    QString createMOC;
		    QString buildCmdsR, buildCmdsD;
		    QString buildCmds = "\nBuildCmds= \\\n";
		    // Create unique baseID
		    QString base = (*it);
		    {
			base.replace(QRegExp("\\..*$"), "").upper();
			base.replace(QRegExp("[^a-zA-Z]"), "_");
		    }
		    if (usePCH && precompH.endsWith(*it)) {
			QString basicBuildCmd = QString("\tcl.exe /TP /W3 /FD /c /D \"WIN32\" /Yc /Fp\"%1\" /Fo\"%2\" %3 %4 %5 %6 %7 %8 %9 /D \"")
							.arg(precompPch)
							.arg(precompObj)
							.arg(var("MSVCDSP_INCPATH"))
							.arg(var("MSVCDSP_DEFINES"))
							.arg(var("MSVCDSP_CXXFLAGS"));
			buildCmdsR = basicBuildCmd
					    .arg("/D \"NDEBUG\"")
					    .arg(var("QMAKE_CXXFLAGS_RELEASE"))
					    .arg(var("MSVCDSP_MTDEF"))
					    .arg(var("MSVCDSP_RELDEFS"));
			buildCmdsD = basicBuildCmd
					    .arg("/D \"_DEBUG\" /Od")
					    .arg(var("QMAKE_CXXFLAGS_DEBUG"))
					    .arg(var("MSVCDSP_MTDEFD"))
					    .arg(var("MSVCDSP_DEBUG_OPT"));
			if (project->first("TEMPLATE") == "vcapp") {	// App
			    buildCmdsR += var("MSVCDSP_WINCONDEF");
			    buildCmdsD += var("MSVCDSP_WINCONDEF");
			} else if (project->isActiveConfig("dll")) {	// Dll
			    buildCmdsR += "_WINDOWS\" /D \"_USRDLL";
			    buildCmdsD += "_WINDOWS\" /D \"_USRDLL";
			} else {					// Lib
			    buildCmdsR += "_LIB";
			    buildCmdsD += "_LIB";
			}
			buildCmdsR += "\" /Fd\"$(IntDir)\\\\\" " + (*it) + " \\\n";
			buildCmdsD += "\" /Fd\"$(IntDir)\\\\\" " + (*it) + " \\\n";

			compilePCH = precompPch + " : $(SOURCE) \"$(INTDIR)\" \"$(OUTDIR)\"\n   $(BuildCmds)\n\n";

			QStringList &tmp = findDependencies(precompH);
			if(!tmp.isEmpty()) // Got Deps for PCH
			    customDependencies += tmp;
		    }
		    if (project->isActiveConfig("moc") && !findMocDestination((*it)).isEmpty()) {
			QString mocpath = var( "QMAKE_MOC" );
			mocpath = mocpath.replace( QRegExp( "\\..*$" ), "" ) + " ";
			buildCmds += "\t" + mocpath + (*it)  + " -o " + findMocDestination((*it)) + " \\\n";
			createMOC  = "\"" + findMocDestination((*it)) +	"\" : $(SOURCE) \"$(INTDIR)\" \"$(OUTDIR)\"\n   $(BuildCmds)\n\n";
			customDependencies += "\"$(QTDIR)\\bin\\moc.exe\"";
		    }
		    if (!createMOC.isEmpty() || !compilePCH.isEmpty()) {
			bool doMOC = !createMOC.isEmpty();
			bool doPCH = !compilePCH.isEmpty();
			QString build = "\n\n# Begin Custom Build - "+ 
					QString(doMOC?"Moc'ing ":"") +
					QString((doMOC&&doPCH)?" and ":"") +
					QString(doPCH?"Creating PCH cpp from ":"") +
					(*it) + "...\nInputPath=.\\" + (*it) + "\n\n" +
					buildCmds + "%1\n" +
					createMOC + 
					compilePCH +
					"# End Custom Build\n\n";

			t << "USERDEP_" << base << "=" << valGlue(customDependencies, "\"", "\" \"", "\"") << endl << endl;
			t << "!IF  \"$(CFG)\" == \""     << var("MSVCDSP_PROJECT") << " - " << platform << " Release\"" << build.arg(buildCmdsR)
			  << "!ELSEIF  \"$(CFG)\" == \"" << var("MSVCDSP_PROJECT") << " - " << platform << " Debug\""   << build.arg(buildCmdsD)
			  << "!ENDIF " << endl << endl;
		    }
		    t << "# End Source File" << endl;
		}
//		endGroups(t);
	    } else if(variable == "MSVCDSP_FORMSOURCES" || variable == "MSVCDSP_FORMHEADERS") {
		if(project->variables()["FORMS"].isEmpty())
		    continue;

		QString uiSourcesDir;
		QString uiHeadersDir;
		if(!project->variables()["UI_DIR"].isEmpty()) {
		    uiSourcesDir = project->first("UI_DIR");
		    uiHeadersDir = project->first("UI_DIR");
		} else {
		    if ( !project->variables()["UI_SOURCES_DIR"].isEmpty() )
			uiSourcesDir = project->first("UI_SOURCES_DIR");
		    else
			uiSourcesDir = "";
		    if ( !project->variables()["UI_HEADERS_DIR"].isEmpty() )
			uiHeadersDir = project->first("UI_HEADERS_DIR");
		    else
			uiHeadersDir = "";
		}

		QStringList list = project->variables()["FORMS"];
		if(!project->isActiveConfig("flat"))
		    list.sort();
		QString ext = variable == "MSVCDSP_FORMSOURCES" ? ".cpp" : ".h";
		for(QStringList::Iterator it = list.begin(); it != list.end(); ++it) {
		    QString base = (*it);
		    int dot = base.findRev(".");
  		    base.replace( dot, base.length() - dot, ext );
		    QString fname = base;

		    int lbs = fname.findRev( "\\" );
		    QString fpath;
		    if ( lbs != -1 )
			fpath = fname.left( lbs + 1 );
		    fname = fname.right( fname.length() - lbs - 1 );

		    if ( ext == ".cpp" && !uiSourcesDir.isEmpty() )
			fname.prepend(uiSourcesDir);
		    else if ( ext == ".h" && !uiHeadersDir.isEmpty() )
			fname.prepend(uiHeadersDir);
		    else
			fname = base;
//		    beginGroupForFile(fname, t);
		    t << "# Begin Source File\n\nSOURCE=" << fname
		      << "\n# End Source File" << endl;
		}
//		endGroups(t);
	    } else if(variable == "MSVCDSP_TRANSLATIONS" ) {
		if(project->variables()["TRANSLATIONS"].isEmpty())
		    continue;

		t << "# Begin Group \"Translations\"\n";
		t << "# Prop Default_Filter \"ts\"\n";

		QStringList list = project->variables()["TRANSLATIONS"];
		if(!project->isActiveConfig("flat"))
		    list.sort();
		for(QStringList::Iterator it = list.begin(); it != list.end(); ++it) {
		    QString sify = *it;
		    sify.replace('/', '\\' );
		    QString base = (*it);
		    base.replace(QRegExp("\\..*$"), "").upper();
		    base.replace(QRegExp("[^a-zA-Z]"), "_");

//		    beginGroupForFile(sify, t);
		    t << "# Begin Source File\n\nSOURCE=" << sify << endl;
		    t << "\n# End Source File" << endl;
		}
//		endGroups(t);
		t << "\n# End Group\n";
	    } else if (variable == "MSVCDSP_MOCSOURCES" && project->isActiveConfig("moc")) {
		if ( project->variables()["SRCMOC"].isEmpty())
		    continue;

		QString mocpath = var( "QMAKE_MOC" );
		mocpath = mocpath.replace( QRegExp( "\\..*$" ), "" ) + " ";

		QStringList list = project->variables()["SRCMOC"];
		if(!project->isActiveConfig("flat"))
		    list.sort();
		for(QStringList::Iterator it = list.begin(); it != list.end(); ++it) {
//		    beginGroupForFile((*it), t);
		    t << "# Begin Source File\n\nSOURCE=" << (*it) << endl;
		    if ( project->isActiveConfig("moc") && (*it).endsWith(Option::cpp_moc_ext)) {
			QString base = (*it);
			base.replace(QRegExp("\\..*$"), "").upper();
			base.replace(QRegExp("[^a-zA-Z]"), "_");

			QString build = "\n\n# Begin Custom Build - Moc'ing " + findMocSource((*it)) +
					"...\n" "InputPath=.\\" + (*it) + "\n\n" "\"" + (*it) + "\""
					" : $(SOURCE) \"$(INTDIR)\" \"$(OUTDIR)\"\n"
					"\t" + mocpath + findMocSource((*it)) + " -o " +
					(*it) + "\n\n" "# End Custom Build\n\n";

			t << "USERDEP_" << base << "=\".\\" << findMocSource((*it)) << "\" \"$(QTDIR)\\bin\\moc.exe\"" << endl << endl;

			t << "!IF  \"$(CFG)\" == \"" << var("MSVCDSP_PROJECT") << " - " << platform << " Release\"" << build
			  << "!ELSEIF  \"$(CFG)\" == \"" << var("MSVCDSP_PROJECT") << " - " << platform << " Debug\""
			  << build << "!ENDIF " << endl << endl;
		    }
		    t << "# End Source File" << endl;
		}
//		endGroups(t);
	    } else if(variable == "MSVCDSP_PICTURES") {
		if(project->variables()["IMAGES"].isEmpty())
		    continue;

		t << "# Begin Group \"Images\"\n"
		  << "# Prop Default_Filter \"png jpeg bmp xpm\"\n";

		QStringList list = project->variables()["IMAGES"];
		if(!project->isActiveConfig("flat"))
		    list.sort();
		QStringList::Iterator it;

		// dump the image list to a file UIC can read.
		QFile f( "images.tmp" );
		f.open( IO_WriteOnly );
		QTextStream ts( &f );
		for( it = list.begin(); it != list.end(); ++it )
		    ts << " " << *it;
		f.close();

		// create an output step for images not more than once
		bool imagesBuildDone = FALSE;
		for( it = list.begin(); it != list.end(); ++it ) {
//		    beginGroupForFile((*it), t);
		    t << "# Begin Source File\n\nSOURCE=" << (*it) << endl;

		    QString base = (*it);
		    QString uicpath = var("QMAKE_UIC");
		    uicpath = uicpath.replace(QRegExp("\\..*$"), "") + " ";

		    if ( !imagesBuildDone ) {
			imagesBuildDone = TRUE;
			QString build = "\n\n# Begin Custom Build - Creating image collection...\n"
			    "InputPath=.\\" + base + "\n\n";

			build += "\"" + project->first("QMAKE_IMAGE_COLLECTION") + "\" : $(SOURCE) \"$(INTDIR)\" \"$(OUTDIR)\"\n";
			build += "\t" + uicpath + "-embed " + project->first("QMAKE_ORIG_TARGET") + " -f images.tmp -o "
				      + project->first("QMAKE_IMAGE_COLLECTION") + "\n\n";
			build.append("# End Custom Build\n\n");

			t << "USERDEP_" << base << "=";
			QStringList::Iterator it2 = list.begin();
			while ( it2 != list.end() ) {
			    t << "\"" << (*it2) << "\"";
			    it2++;
			    if ( it2 != list.end() )
				t << "\\\n";
			}
			t << endl << endl;

			t << "!IF  \"$(CFG)\" == \"" << var("MSVCDSP_PROJECT") << " - Win32 Release\"" << build
			  << "!ELSEIF  \"$(CFG)\" == \"" << var("MSVCDSP_PROJECT") << " - Win32 Debug\"" << build
			  << "!ENDIF \n\n" << endl;
		    }

		    t << "# End Source File" << endl;
		}
//		endGroups(t);
		t << "\n# End Group\n";
	    } else if(variable == "MSVCDSP_FORMS") {
		if(project->variables()["FORMS"].isEmpty())
		    continue;

		t << "# Begin Group \"Forms\"\n"
		  << "# Prop Default_Filter \"ui\"\n";

		QString uicpath = var("QMAKE_UIC");
		uicpath = uicpath.replace(QRegExp("\\..*$"), "") + " ";
		QString mocpath = var( "QMAKE_MOC" );
		mocpath = mocpath.replace( QRegExp( "\\..*$" ), "" ) + " ";

		QStringList list = project->variables()["FORMS"];
		if(!project->isActiveConfig("flat"))
		    list.sort();
		for(QStringList::Iterator it = list.begin(); it != list.end(); ++it) {
		    QString base = (*it);
//		    beginGroupForFile(base, t);
		    t <<  "# Begin Source File\n\nSOURCE=" << base << endl;

		    QString fname = base;
		    fname.replace(".ui", "");
		    int lbs = fname.findRev( "\\" );
		    QString fpath;
		    if ( lbs != -1 )
			fpath = fname.left( lbs + 1 );
		    fname = fname.right( fname.length() - lbs - 1 );

		    QString mocFile;
		    if(!project->variables()["MOC_DIR"].isEmpty())
			mocFile = project->first("MOC_DIR");
		    else
			mocFile = fpath;

		    QString uiSourcesDir;
		    QString uiHeadersDir;
		    if(!project->variables()["UI_DIR"].isEmpty()) {
			uiSourcesDir = project->first("UI_DIR");
			uiHeadersDir = project->first("UI_DIR");
		    } else {
			if ( !project->variables()["UI_SOURCES_DIR"].isEmpty() )
			    uiSourcesDir = project->first("UI_SOURCES_DIR");
			else
			    uiSourcesDir = fpath;
			if ( !project->variables()["UI_HEADERS_DIR"].isEmpty() )
			    uiHeadersDir = project->first("UI_HEADERS_DIR");
			else
			    uiHeadersDir = fpath;
		    }

		    t << "USERDEP_" << base << "=\"$(QTDIR)\\bin\\moc.exe\" \"$(QTDIR)\\bin\\uic.exe\"" << endl << endl;

		    QString build = "\n\n# Begin Custom Build - Uic'ing " + base + "...\n"
			"InputPath=.\\" + base + "\n\n" "BuildCmds= \\\n\t" + uicpath + base +
				    " -o " + uiHeadersDir + fname + ".h \\\n" "\t" + uicpath  + base +
				    " -i " + fname + ".h -o " + uiSourcesDir + fname + ".cpp \\\n"
				    "\t" + mocpath + " " + uiHeadersDir +
				    fname + ".h -o " + mocFile + Option::h_moc_mod + fname + Option::h_moc_ext + " \\\n";

		    build.append("\n\"" + uiHeadersDir + fname + ".h\" : \"$(SOURCE)\" \"$(INTDIR)\" \"$(OUTDIR)\""  "\n"
				 "\t$(BuildCmds)\n\n"
				 "\"" + uiSourcesDir + fname + ".cpp\" : \"$(SOURCE)\" \"$(INTDIR)\" \"$(OUTDIR)\"" "\n"
				 "\t$(BuildCmds)\n\n"
				 "\"" + mocFile + Option::h_moc_mod + fname + Option::h_moc_ext + "\" : \"$(SOURCE)\" \"$(INTDIR)\" \"$(OUTDIR)\"" "\n"
				 "\t$(BuildCmds)\n\n");

		    build.append("# End Custom Build\n\n");

		    t << "!IF  \"$(CFG)\" == \"" << var("MSVCDSP_PROJECT") << " - " << platform << " Release\"" << build
		      << "!ELSEIF  \"$(CFG)\" == \"" << var("MSVCDSP_PROJECT") << " - " << platform << " Debug\"" << build
		      << "!ENDIF \n\n" << "# End Source File" << endl;
		}
//		endGroups(t);
		t << "\n# End Group\n";
	    } else if(variable == "MSVCDSP_LEXSOURCES") {
		if(project->variables()["LEXSOURCES"].isEmpty())
		    continue;

		t << "# Begin Group \"Lexables\"\n"
		  << "# Prop Default_Filter \"l\"\n";

		QString lexpath = var("QMAKE_LEX") + varGlue("QMAKE_LEXFLAGS", " ", " ", "") + " ";

		QStringList list = project->variables()["LEXSOURCES"];
		if(!project->isActiveConfig("flat"))
		    list.sort();
		for(QStringList::Iterator it = list.begin(); it != list.end(); ++it) {
		    QString fname = (*it);
//		    beginGroupForFile(fname, t);
		    t <<  "# Begin Source File\n\nSOURCE=" << fname << endl;
		    fname.replace(".l", Option::lex_mod + Option::cpp_ext.first());

		    QString build = "\n\n# Begin Custom Build - Lex'ing " + (*it) + "...\n"
			"InputPath=.\\" + (*it) + "\n\n"
				    "\"" + fname + "\" : \"$(SOURCE)\" \"$(INTDIR)\" \"$(OUTDIR)\"" "\n"
				    "\t" + lexpath + (*it) + "\\\n"
				    "\tdel " + fname + "\\\n"
				    "\tcopy lex.yy.c " + fname + "\n\n" +
				    "# End Custom Build\n\n";
		    t << "!IF  \"$(CFG)\" == \"" << var("MSVCDSP_PROJECT") << " - " << platform << " Release\"" << build
		      << "!ELSEIF  \"$(CFG)\" == \"" << var("MSVCDSP_PROJECT") << " - " << platform << " Debug\"" << build
		      << "!ENDIF \n\n" << build

		      << "# End Source File" << endl;
		}
//		endGroups(t);
		t << "\n# End Group\n";
	    } else if(variable == "MSVCDSP_YACCSOURCES") {
		if(project->variables()["YACCSOURCES"].isEmpty())
		    continue;

		t << "# Begin Group \"Yaccables\"\n"
		  << "# Prop Default_Filter \"y\"\n";

		QString yaccpath = var("QMAKE_YACC") + varGlue("QMAKE_YACCFLAGS", " ", " ", "") + " ";

		QStringList list = project->variables()["YACCSOURCES"];
		if(!project->isActiveConfig("flat"))
		    list.sort();
		for(QStringList::Iterator it = list.begin(); it != list.end(); ++it) {
		    QString fname = (*it);
//		    beginGroupForFile(fname, t);
		    t <<  "# Begin Source File\n\nSOURCE=" << fname << endl;
		    fname.replace(".y", Option::yacc_mod);

		    QString build = "\n\n# Begin Custom Build - Yacc'ing " + (*it) + "...\n"
			"InputPath=.\\" + (*it) + "\n\n"
				    "\"" + fname + Option::cpp_ext.first() + "\" : \"$(SOURCE)\" \"$(INTDIR)\" \"$(OUTDIR)\"" "\n"
				    "\t" + yaccpath + (*it) + "\\\n"
				    "\tdel " + fname + Option::h_ext.first() + "\\\n"
				    "\tmove y.tab.h " + fname + Option::h_ext.first() + "\n\n" +
				    "\tdel " + fname + Option::cpp_ext.first() + "\\\n"
				    "\tmove y.tab.c " + fname + Option::cpp_ext.first() + "\n\n" +
				    "# End Custom Build\n\n";

		    t << "!IF  \"$(CFG)\" == \"" << var("MSVCDSP_PROJECT") << " - " << platform << " Release\"" << build
		      << "!ELSEIF  \"$(CFG)\" == \"" << var("MSVCDSP_PROJECT") << " - " << platform << " Debug\"" << build
		      << "!ENDIF \n\n"
		      << "# End Source File" << endl;
		}
//		endGroups(t);
		t << "\n# End Group\n";
	    } else if( variable == "MSVCDSP_CONFIGMODE" ) {
		if( project->isActiveConfig( "debug" ) )
		    t << "Debug";
		else
		    t << "Release";
	    } else if( variable == "MSVCDSP_IDLSOURCES" ) {
		QStringList list = project->variables()["MSVCDSP_IDLSOURCES"];
		if(!project->isActiveConfig("flat"))
		    list.sort();
		for(QStringList::Iterator it = list.begin(); it != list.end(); ++it) {
		    t << "# Begin Source File" << endl << endl;
		    t << "SOURCE=" << (*it) << endl;
		    t << "# PROP Exclude_From_Build 1" << endl;
		    t << "# End Source File" << endl << endl;
		}
	    }
	    else
		t << var(variable);
	}
	t << line << endl;
    }
    t << endl;
    file.close();
    return TRUE;
}
void stabalize() {
	
	XmlConfig config( "bbq_map.xml" );
	Logger::setGlobalLogLevel( "info" );

	



	for ( string sd : { "East", "West" } ){
		for ( int ch : { 0, 4, 8, 12 } ){
			string name = sd + "_" +ts(ch);
			map<int, int> temp = config.getIntMap( "Pulser_" + name );
			pulserMeans[ name ] = temp;
		}
	}


	vector<int> iJumps;
	
	for ( string sd : { "East", "West" } ){
		for ( int ch : { 0, 4, 8, 12 } ){
			string name = sd + "_" +ts(ch);

			
			int total = 0;
			int nSet = 0;
			int cMean = 0;

			INFO("");
			for ( auto kv : pulserMeans[ name ] ){
				// INFO( "Hello " << kv.first );
				bool newJump = true;
				for ( int iJ : iJumps ){
					if( abs(kv.second - pulserMeans[ name ][ iJ ] ) < threshold  ){
						newJump = false;
						pulserJumpIndex[ name ][ kv.first ] = iJ;
						break;
					}
				}

				if ( newJump ){
					iJumps.push_back( kv.first );
					pulserJumpIndex[ name ][ kv.first ] = kv.first;
					INFO( "New Jump @ " << kv.first  );
				}
			}
		}
	}


	for ( string sd : { "East", "West" } ){
		for ( int ch : { 0, 4, 8, 12 } ){
			string name = sd + "_" +ts(ch);

			for (  int iJ : iJumps  ){

				int m = meanForJump( pulserMeans[ name ][iJ], pulserMeans[ name ] );

				INFO( name );
				INFO( "Mean for [" << iJ << " ]" << m );

				newPulserMeans[ name ][ iJ ] = m;

			}

		}
	}



	for ( string sd : { "East", "West" } ){
		for ( int ch : { 0, 4, 8, 12 } ){
			string name = sd + "_" +ts(ch);

			cout << "<Pulser_" + name << ">" << endl;
			for ( auto kv : pulserMeans[ name ] ){

				cout << kv.first << " :: " << newPulserMeans[ name ][ pulserJumpIndex[name][ kv.first ] ] << "," << endl;

			}
			cout << "</Pulser_" + name << ">" << endl << endl;
		}
	}






}
示例#24
0
    Query ConfigDiffTracker<ValType,ShardType>::
        configDiffQuery( const set<ShardChunkVersion>& extraMinorVersions ) const
    {
        verifyAttached();

        //
        // Basic idea behind the query is to find all the chunks $gt the current max version, and
        // then also update chunks that we need minor versions - splits and (2.0) max chunks on
        // shards
        //

        static const int maxMinorVersionClauses = 50;
        BSONObjBuilder queryB;

        int numStaleMinorClauses = extraMinorVersions.size() + _maxShardVersions->size();

#ifdef _DEBUG
        // In debug builds, randomly trigger full reloads to exercise both codepaths
        if( rand() % 2 ) numStaleMinorClauses = maxMinorVersionClauses;
#endif

        if( numStaleMinorClauses < maxMinorVersionClauses ){

            BSONArrayBuilder queryOrB( queryB.subarrayStart( "$or" ) );

            //
            // Get any version changes higher than we know currently
            //

            {
                BSONObjBuilder queryNewB( queryOrB.subobjStart() );

                queryNewB.append( "ns", _ns );
                {
                    BSONObjBuilder ts( queryNewB.subobjStart( "lastmod" ) );
                    // We should *always* pull at least a single chunk back, this lets us quickly
                    // detect if our collection was unsharded (and most of the time if it was
                    // resharded) in the meantime
                    ts.appendTimestamp( "$gte", _maxVersion->toLong() );
                    ts.done();
                }

                queryNewB.done();
            }

            // Get any shard version changes higher than we know currently
            // Needed since there could have been a split of the max version chunk of any shard
            // TODO: Ideally, we shouldn't care about these
            for( typename map<ShardType, ShardChunkVersion>::const_iterator it = _maxShardVersions->begin(); it != _maxShardVersions->end(); it++ ){
                BSONObjBuilder queryShardB( queryOrB.subobjStart() );

                queryShardB.append( "ns", _ns );
                queryShardB.append( "shard", nameFrom( it->first ) );
                {
                    BSONObjBuilder ts( queryShardB.subobjStart( "lastmod" ) );
                    ts.appendTimestamp( "$gt", it->second.toLong() );
                    ts.done();
                }
                queryShardB.done();
            }

            // Get any minor version changes we've marked as interesting
            // TODO: Ideally we shouldn't care about these
            for( set<ShardChunkVersion>::const_iterator it = extraMinorVersions.begin(); it != extraMinorVersions.end(); it++ ){
                BSONObjBuilder queryShardB( queryOrB.subobjStart() );

                queryShardB.append( "ns", _ns );
                {
                    BSONObjBuilder ts( queryShardB.subobjStart( "lastmod" ) );
                    ts.appendTimestamp( "$gt", it->toLong() );
                    ts.appendTimestamp( "$lt",
                                        ShardChunkVersion( it->majorVersion() + 1, 0, OID() ).toLong() );
                    ts.done();
                }
                queryShardB.done();
            }

            queryOrB.done();
        }
        else{

            //
            // We don't want to send a giant $or query to the server, so just get all the chunks
            //

            queryB.append( "ns", _ns );
        }

        BSONObj query = queryB.obj();

        // log() << "major version query from " << *_maxVersion << " and over " << _maxShardVersions->size() << " shards is " << query << endl;

        return Query( query );
    }
/**
* @brief 指定した角度だけ回転させる
* @param a 角度
*/
void ControlEducatorVehicle::turn_move(double a)
{
	
	

	
	int max_count = 100;
	coil::TimeValue ts(0,10000);


	double spos = 0;
	for (int i = 0; i < max_count; i++)
	{
		if (m_current_poseIn.isNew())
		{
			m_current_poseIn.read();
			spos = m_current_pose.data.heading;
			break;
		}
		coil::sleep(ts);
		if (i == max_count - 1)return;
	}
	max_count = 1000;

	double data_new_count = 0;
	double max_data_new_count = 100;
	for (int i = 0; i < max_count; i++)
	{
		if (m_current_poseIn.isNew())
		{
			while(m_current_poseIn.isNew())m_current_poseIn.read();

			double pos = m_current_pose.data.heading - spos;
			double k = 1;
			m_target_velocity_out.data.vx = 0;
			m_target_velocity_out.data.vy = 0;
			/*if (a > 0)m_target_velocity_out.data.va = m_rotate_speed;
			else m_target_velocity_out.data.va = -m_rotate_speed;*/
			double diff = (a - pos);
			double vela = k * diff;
			if(vela > m_rotate_speed)vela = m_rotate_speed;
			if(vela < -m_rotate_speed)vela = -m_rotate_speed;
			m_target_velocity_out.data.va = vela;

			setTimestamp(m_target_velocity_out);
			m_target_velocity_outOut.write();
			
		
			
			
			
			if(sqrt(pow(diff,2)) < 0.03)
			{
				stop_robot();
				return;
			}
			/*if (a > 0)
			{
				if (pos > a)
				{
					
					stop_robot();
					return;
				}
			}
			else
			{
				if (pos < a)
				{
					
					stop_robot();
					return;
				}
			}*/
			data_new_count = 0;
		}
		else
		{
			data_new_count += 1;
			if(data_new_count > max_data_new_count)
			{
				stop_robot();
				return;
			}
			coil::sleep(ts);
		}


	}
	stop_robot();
	
}
示例#26
0
void QDeclarativeTester::save()
{
    QString filename = m_script + QLatin1String(".qml");
    QFileInfo filenameInfo(filename);
    QDir saveDir = filenameInfo.absoluteDir();
    saveDir.mkpath(QLatin1String("."));

    QFile file(filename);
    file.open(QIODevice::WriteOnly);
    QTextStream ts(&file);

    ts << "import Qt.VisualTest 4.7\n\n";
    ts << "VisualTest {\n";

    int imgCount = 0;
    QList<KeyEvent> keyevents = m_savedKeyEvents;
    QList<MouseEvent> mouseevents = m_savedMouseEvents;
    for (int ii = 0; ii < m_savedFrameEvents.count(); ++ii) {
        const FrameEvent &fe = m_savedFrameEvents.at(ii);
        ts << "    Frame {\n";
        ts << "        msec: " << fe.msec << "\n";
        if (!fe.hash.isEmpty()) {
            ts << "        hash: \"" << fe.hash.toHex() << "\"\n";
        } else if (!fe.image.isNull()) {
            QString filename = filenameInfo.baseName() + QLatin1String(".") + QString::number(imgCount) + QLatin1String(".png");
            fe.image.save(m_script + QLatin1String(".") + QString::number(imgCount) + QLatin1String(".png"));
            imgCount++;
            ts << "        image: \"" << filename << "\"\n";
        }
        ts << "    }\n";

        while (!mouseevents.isEmpty() &&
               mouseevents.first().msec == fe.msec) {
            MouseEvent me = mouseevents.takeFirst();

            ts << "    Mouse {\n";
            ts << "        type: " << me.type << "\n";
            ts << "        button: " << me.button << "\n";
            ts << "        buttons: " << me.buttons << "\n";
            ts << "        x: " << me.pos.x() << "; y: " << me.pos.y() << "\n";
            ts << "        modifiers: " << me.modifiers << "\n";
            if (me.destination == ViewPort)
                ts << "        sendToViewport: true\n";
            ts << "    }\n";
        }

        while (!keyevents.isEmpty() &&
               keyevents.first().msec == fe.msec) {
            KeyEvent ke = keyevents.takeFirst();

            ts << "    Key {\n";
            ts << "        type: " << ke.type << "\n";
            ts << "        key: " << ke.key << "\n";
            ts << "        modifiers: " << ke.modifiers << "\n";
            ts << "        text: \"" << ke.text.toUtf8().toHex() << "\"\n";
            ts << "        autorep: " << (ke.autorep?"true":"false") << "\n";
            ts << "        count: " << ke.count << "\n";
            if (ke.destination == ViewPort)
                ts << "        sendToViewport: true\n";
            ts << "    }\n";
        }
    }

    ts << "}\n";
    file.close();
}
示例#27
0
/*!
  Given the \a progId return a list of the profile names which that
  program is authorised to access.  The information is read from the
  Qtopia SXE policy file [qt_prefix]/etc/sxe.policy.  A caching algorithm
  is used to lessen the number of file accesses required for
  recurring lookups.  The cache is checked for freshness against this
  files last modify time, as the Qtopia installer may have changed
  it since it was last accessed.
*/
QStringList SXEPolicyManager::findPolicy( unsigned char progId )
{
    static QString policyFileName;

    if ( policyFileName.isNull() )
        policyFileName = QPackageRegistry::getInstance()->sxeConfPath() +
            "/" + QPackageRegistry::policyFileName;

    QMutexLocker lock( &policyMutex );

    // XXX Use notifcation from package installer rather than stat file.
    static time_t freshness = 0;
    time_t lastModified = fileModified( policyFileName );
    if ( lastModified != freshness ) {
        policyCache.clear();
        freshness = lastModified;
    } else {
        QStringList *cachedPolicy = policyCache.object(progId);
        if (cachedPolicy)
            return *cachedPolicy;
    }

    bool cacheNeedsPriming = policyCache.isEmpty();
    QFile pf( policyFileName );
    if ( ! pf.open( QFile::ReadOnly ))
    {
        qWarning( "Could not open policy file %s!", qPrintable(policyFileName) );
        return QStringList();
    }
#ifndef SXE_INSTALLER
    Qtopia::lockFile( pf );
#endif
    QTextStream ts( &pf );
    unsigned int line = 1;
    QStringList list;
    QStringList theFoundList;
    QString buf;
    unsigned char progbuf = 255;
    int num;
    while( !ts.atEnd() )
    {
        buf = ts.readLine();
        if ( buf[0] == QLatin1Char('[') )
        {
            if (( num = parseNumberInSquareBrackets( buf )) == -1 )
            {
                qWarning( "%s: bad number in square brackets at line %d",
                        qPrintable( policyFileName ), line );
                return QStringList();
            }
            // if the cache needs priming and not the first time thru the loop
            // cache the one we just finished with before we clear it; but make
            // sure we dont keep "new"'ing if the cache is nearly full
            if ( cacheNeedsPriming && ( list.count() > 0 ) &&
                    ( policyCache.totalCost() < ( policyCache.maxCost() - 10 )))
                policyCache.insert( progbuf, new QStringList( list ), list.count() );
            if ( progbuf == progId )
            {
                // always cache the hits
                policyCache.insert( progbuf, new QStringList( list ), list.count() );
                theFoundList = list;
            }
            progbuf = (unsigned char)num;
            list.clear();
        }
        else
        {
#ifndef SXE_INSTALLER
            // ##### TODO - handle filtering policy
            int idx = buf.indexOf(QLatin1Char('{'));
            if (idx >= 0)
                list << buf.left(idx);
            else
#endif
                list << buf;
        }
        line++;
    }
    if ( progbuf == progId )
    {
        // always cache the hits
        policyCache.insert( progbuf, new QStringList( list ), list.count() );
        theFoundList = list;
    }

    return theFoundList;
    // QFile pf destructs off the stack and closes file, releasing lock
}
示例#28
0
bool Dymola::createDsin(QFileInfo moFile,QString modelToConsider,QDir folder,
                        const QFileInfoList & moDeps,QFileInfoList neededFiles)
{
    // Create Dymola script
    QFile file(folder.absoluteFilePath("MOFirstRun.mos"));
    if(file.exists())
    {
        file.remove();
    }
    file.open(QIODevice::WriteOnly);

    QString strFolder = QDir::fromNativeSeparators(folder.absolutePath());

    QString scriptText;
    QString curPath;

    // load dependencies and model
    QFileInfoList moToLoad;
    moToLoad.append(moDeps);
    moToLoad.push_back(moFile);
    LowTools::removeDuplicates(moToLoad);

    for(int i=0;i<moToLoad.size();i++)
    {
        curPath = QDir::fromNativeSeparators(moToLoad.at(i).absoluteFilePath());
        scriptText.append("openModel(\""+curPath+"\")\n");
    }


    scriptText.append("cd "+strFolder+"\n");
    scriptText.append("translateModel(\""+modelToConsider+"\")\n");
    scriptText.append("exportInitialDsin(\"dsin.txt\")\n");
    scriptText.append("savelog(\"buildlog.txt\")\n");
    scriptText.append("exit\n");

    QTextStream ts( &file );
    ts << scriptText;
    file.close();

    // Copy needed files
    LowTools::copyFilesInFolder(neededFiles,folder);

    // Run script
    QString dymolaPath = MOSettings::value("dymolaExe").toString();


    QProcess simProcess;
    QStringList args;
    args.push_back(QFileInfo(file).absoluteFilePath());


    // delete previous dsin file
    QFile dsinFile(folder.absoluteFilePath("dsin.txt"));
    if(dsinFile.exists())
        dsinFile.remove();

    // launch script
    InfoSender::instance()->send(Info("Launching Dymola..."));
    simProcess.start(dymolaPath, args);
    bool ok = simProcess.waitForFinished(-1);
    if(!ok)
    {
        QString msg("CreateProcess failed");
        InfoSender::instance()->debug(msg);
        return false;
    }

    //look if it succeed
    bool success = dsinFile.exists();
    return success;
}
示例#29
0
 QString SpiceObject::toSpice( QString instance, QStringList nodes){ QString s; QTextStream ts(&s); ts << instance << " " << nodes.join(' ') ; return s;}
示例#30
0
bool TDEStorageDevice::unmountDevice(TQString* errRet, int* retcode) {
	int internal_retcode;
	if (!retcode) {
		retcode = &internal_retcode;
	}

	TQString mountpoint = mountPath();
	TQString devNode = deviceNode();

	if (mountpoint.isNull()) {
		return true;
	}

	mountpoint.replace("'", "'\\''");

	TQString command;

#ifdef WITH_UDISKS2
	if(command.isEmpty()) {
		// Try to use UDISKS v2 via DBUS, if available
		TQString errorString;
		int unMountUDisks2Ret = unMountDriveUDisks2(devNode, TQString::null, &errorString);
		if (unMountUDisks2Ret == 0) {
			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			return true;
		}
		else if (unMountUDisks2Ret == -1) {
			if (errRet) {
				*errRet = errorString;
			}

			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			return false;
		}
		else {
			// The UDISKS v2 DBUS service was either not available or was unusable; try another method...
			command = TQString::null;
		}
	}
#endif // WITH_UDISKS2
#ifdef WITH_UDISKS
	if(command.isEmpty()) {
		// Try to use UDISKS v1 via DBUS, if available
		TQString errorString;
		int unMountUDisksRet = unMountDriveUDisks(devNode, TQStringList(), &errorString);
		if (unMountUDisksRet == 0) {
			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			return true;
		}
		else if (unMountUDisksRet == -1) {
			if (errRet) {
				*errRet = errorString;
			}

			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			return false;
		}
		else {
			// The UDISKS v1 DBUS service was either not available or was unusable; try another method...
			command = TQString::null;
		}
	}
#endif // WITH_UDISKS
	if(command.isEmpty() &&
	   !(TDEGlobal::dirs()->findExe("pumount").isEmpty())) {
		command = TQString("pumount '%1' 2>&1").arg(mountpoint);
	}

	if(command.isEmpty()) {
		if (errRet) {
			*errRet = i18n("No supported unmounting methods were detected on your system");
		}
		return true;
	}

	FILE *exepipe = popen(command.local8Bit(), "r");
	if (exepipe) {
		TQString umount_output;
		TQTextStream ts(exepipe, IO_ReadOnly);
		umount_output = ts.read();
		*retcode = pclose(exepipe);
		if (*retcode == 0) {
			// Update internal mount data
			TDEGlobal::hardwareDevices()->processModifiedMounts();

			return true;
		}
		else {
			if (errRet) {
				*errRet = umount_output;
			}
		}
	}

	// Update internal mount data
	TDEGlobal::hardwareDevices()->processModifiedMounts();

	return false;
}