void MultipleBackendsTest::xml2xml()
{
	DbBackendIface *backend1 = new XmlDbBackend( "database.xml" );
	Manager *manager1 = new Manager( backend1 );
	manager1->createSchema();
	
	DbBackendIface *backend2 = new XmlDbBackend( "database2.xml", true );
	Manager *manager2 = new Manager( backend2 );
	manager2->createSchema();
	manager1->copyTo( manager2 );
	manager2->commit();

	delete manager2;
	delete manager1;

	QFile file;
	QByteArray a1, a2;
	file.setName( "database.xml" );
	CHECK( file.open( IO_ReadOnly ), true );
	a1 = file.readAll();
	file.close();
	file.setName( "database2.xml" );
	CHECK( file.open( IO_ReadOnly ), true );
	a2 = file.readAll();
	file.close();
	CHECK( a1, a2 );
}
Example #2
0
bool
DspMakefileGenerator::openOutput(QFile &file) const
{
    QString outdir;
    if(!file.name().isEmpty()) {
	if(QDir::isRelativePath(file.name()))
	    file.setName(Option::output_dir + file.name()); //pwd when qmake was run
	QFileInfo fi(file);
	if(fi.isDir())
	    outdir = file.name() + QDir::separator();
    }
    if(!outdir.isEmpty() || file.name().isEmpty())
	file.setName(outdir + project->first("TARGET") + project->first("DSP_EXTENSION"));
    if(QDir::isRelativePath(file.name())) {
	QString ofile;
	ofile = file.name();
	int slashfind = ofile.findRev('\\');
	if (slashfind == -1) {
	    ofile = ofile.replace(QRegExp("-"), "_");
	} else {
	    int hypenfind = ofile.find('-', slashfind);
	    while (hypenfind != -1 && slashfind < hypenfind) {
		ofile = ofile.replace(hypenfind, 1, "_");
		hypenfind = ofile.find('-', hypenfind + 1);
	    }
	}
	file.setName(Option::fixPathToLocalOS(QDir::currentDirPath() + Option::dir_sep + ofile));
    }
    return Win32MakefileGenerator::openOutput(file);
}
void
aBackup::cleanupTmpFiles(const QString& tmpDirName, QStringList *files)
{
	QFile file;
	QDir dir;
	file.setName(QDir::convertSeparators(tmpDirName+"/content.xml"));
	aLog::print(aLog::Debug, tr("aBackup delete file %1").arg(file.name()));
	file.remove();
	file.setName(QDir::convertSeparators(tmpDirName+"/busines-schema.cfg"));
	aLog::print(aLog::Debug, tr("aBackup delete file %1").arg(file.name()));
	file.remove();
	file.setName(QDir::convertSeparators(tmpDirName+"/META-INF/manifest.xml"));
	aLog::print(aLog::Debug, tr("aBackup delete file %1").arg(file.name()));
	file.remove();
	for(uint i=0; i<files->count(); i++)
	{
			file.setName(QDir::convertSeparators(tmpDirName + "/templates/"+ (*files)[i]));
			aLog::print(aLog::Debug, tr("aBackup delete file %1").arg(file.name()));
			file.remove();
	}
	aLog::print(aLog::Debug, tr("aBackup delete directory %1").arg(tmpDirName + "/META-INF"));
	dir.rmdir(QDir::convertSeparators(tmpDirName + "/META-INF"));
	aLog::print(aLog::Debug, tr("aBackup delete directory %1").arg(tmpDirName + "/templates"));
	dir.rmdir(QDir::convertSeparators(tmpDirName + "/templates"));
	aLog::print(aLog::Debug, tr("aBackup delete directory %1").arg(tmpDirName));
	dir.rmdir(QDir::convertSeparators(tmpDirName));
	aLog::print(aLog::Info, tr("aBackup cleanup temporary files"));

}
void MultipleBackendsTest::creates()
{
	DbBackendIface *backend1 = new XmlDbBackend( "databaseA.xml", true );
	Manager *m1 = new Manager( backend1 );

	DbBackendIface *backend2 = new XmlDbBackend( "databaseB.xml", true );
	Manager *m2 = new Manager( backend2 );

	ObjectRef<Customer> c1 = Customer::create( m1 );
	c1->setCustomerName( "Customer Name" );
	ObjectRef<Customer> c2 = Customer::create( m2 );
	c2->setCustomerName( "Customer Name" );
	
	CHECK( m1->objects().count(), m2->objects().count() );
	
	CHECK( m1->commit(), true );
	CHECK( m2->commit(), true );
	
	
	QFile file;
	QByteArray a1, a2;
	file.setName( "databaseA.xml" );
	CHECK( file.open( IO_ReadOnly ), true );
	a1 = file.readAll();
	file.close();
	file.setName( "databaseB.xml" );
	CHECK( file.open( IO_ReadOnly ), true );
	a2 = file.readAll();
	file.close();
	CHECK( a1, a2 );

	delete m1;
	delete m2;
}
Example #5
0
// ---------------------------------------------------------------
int PackageDialog::insertDirectory(const QString& DirName,
                           QDataStream& Stream)
{
  QFile File;
  QDir myDir(DirName);

  // Put all files of this directory into the package.
  QStringList Entries = myDir.entryList("*", QDir::Files, QDir::Name);
  QStringList::iterator it;
  for(it = Entries.begin(); it != Entries.end(); ++it) {
    File.setName(myDir.absFilePath(*it));
    Stream << Q_UINT32(CODE_FILE);
    if(insertFile(*it, File, Stream) < 0)
      return -1;
  }

  // Put all subdirectories into the package.
  Entries = myDir.entryList("*", QDir::Dirs, QDir::Name);
  Entries.pop_front();  // delete "." from list
  Entries.pop_front();  // delete ".." from list
  for(it = Entries.begin(); it != Entries.end(); ++it) {
    Stream << Q_UINT32(CODE_DIR) << (*it).latin1();
    if(insertDirectory(myDir.absPath()+QDir::separator()+(*it), Stream) < 0)
      return -1;
    Stream << Q_UINT32(CODE_DIR_END) << Q_UINT32(0);
  }
  return 0;
}
Example #6
0
//// Send the def file as body of the message.
//int KLMailClient::kMailOpenComposer(const QString& arg0,const QString& arg1, const QString& arg2,const QString& arg3,const QString& arg4,int arg5, const KURL& arg6) {
//  int result = 0;
//
//   QString attfn = QString(arg6.path().utf8());
//   QFile attfile;
//    attfile.setName(attfn);
//    if (attfile.open(IO_ReadOnly) == false)
//    	cout << "Could not open file: " << attfile.name();
//  QByteArray data, replyData;
//  QCString replyType;
//  QDataStream arg( data, IO_WriteOnly );
//  arg << arg0; // to
//  arg << arg1;  // cc
//  arg << arg2; // bcc
//  arg << arg3; //subject
//  arg << arg4; //body
//  arg << arg5; // hidden=0
//  arg << attfile.readAll(); // KURL messageFile
//  cout << "In kMailOpenComposer version 1: arg6=" << arg6.path().utf8() << endl;
//  cout << "In kMailOpenComposer version 1: data=" << data << endl;
//  if (kapp->dcopClient()->call("kmail","KMailIface","openComposer(QString,QString,QString,QString,QString,int,KURL)", data, replyType, replyData ) ) {
//    if ( replyType == "int" ) {
//      QDataStream _reply_stream( replyData, IO_ReadOnly );
//      _reply_stream >> result;
//    } else {
//      kdDebug() << "kMailOpenComposer() call failed." << endl;
//    }
//  } else {
//    kdDebug() << "kMailOpenComposer() call failed." << endl;
//  }
//  return result;
//}
// Create an email and add the def file as an attachment.
int KLMailClient::kMailOpenComposer( const QString& arg0, const QString& arg1, const QString& arg2, const QString& arg3,
                                     const QString& arg4, int arg5, const QString& arg6, const QCString& arg7, const QCString& arg8,
                                     const QCString& arg9, const QCString& arg10, const QCString& arg11, const QString& arg12, const QCString& arg13 ) {

    int result = 0;
    QString attfn = QString(arg8);
    QFile attfile;
    attfile.setName(attfn);
    if (attfile.open(IO_ReadOnly) == false)
    	cout << "Could not open file: " << attfile.name();
    QByteArray data, replyData;
    QCString replyType;
    QDataStream arg( data, IO_WriteOnly );
    arg << arg0; //to
    arg << arg1; // cc
    arg << arg2; // from (bcc)
    arg << arg3; //subject
    arg << arg4; //body
    arg << arg5; // hidden=0
    arg << arg6; // attachName
    arg << arg7; // "7bit" (attachCte)
    arg << attfile.readAll(); //attachment (attachData)
    arg << arg9; // "text" (attachType)
    arg << arg10; // "calendar" (attachSubType)
    arg << arg11; // "method" (attachParamAttr)
    arg << arg12; // "publish" (attachParamValue)
    arg << arg13; // "attachment" (attachContDisp)
    if ( kapp->dcopClient()->call("kmail","KMailIface","openComposer(QString,QString,QString,QString,QString,int,QString,QCString,QCString,QCString,QCString,QCString,QString,QCString)", data, replyType, replyData ) ) {
        if ( replyType == "int" ) {
            QDataStream _reply_stream( replyData, IO_ReadOnly );
            _reply_stream >> result;
        } else {
Example #7
0
/*!
 *\~english
 *	Writes text to log.
 *\~russian
 *	Пишет текст в лог.
 *\~
 *	\param log_name - \~english Full path to logfile \~russian Полный путь к лог файлу \~
 *	\param test_name - \~english Test name \~russian Имя теста \~
 *	\param status - \~english OK, ERROR or SKIP \~russian OK, ОШИБКА или ПРОПУЩЕН \~
 *	\param text - \~english Comment \~russian Комментарий \~
*/
void
aTests::print2log(	const QString &log_name,
			const QString &test_name,
			const QString &status,
			const QString &text)
{
	QString toWrite = QString("%1::%2::%3::%4\r\n")\
			  .arg(QDateTime::currentDateTime().toString(Qt::ISODate).replace('T',' '))\
			  .arg(test_name)\
			  .arg(status)\
			  .arg(text);

	QFile f;
	if(log_name==QString::null)
	{
		f.open( QIODevice::WriteOnly, stdout );
		f.writeBlock((const char*)toWrite,strlen((const char*)toWrite));
	}
	else
	{
		f.setName(log_name);
		f.open( QIODevice::WriteOnly | QIODevice::Append );
		f.writeBlock((const char*)toWrite,strlen((const char*)toWrite));
		f.flush();
	}
	f.close();

//	else printf("error write to log\n");
}
Example #8
0
/*!
*	\en
*	Gets name for new template. Need for OpenOffice v2.
*	\_en
*	\ru
*	Получение имени для нового шаблона. Нужна из-за блокировок в OpenOffice v2.
*	\_ru
*/
QString
aReport::getName4NewTemplate()
{
	uint count=0;
	QFile tmpf;
	QString suff = ".odt";
	QString fname;
	if(type==RT_office_calc) suff = ".ods";
	if(type==RT_msoffice_word || type==RT_msoffice_excel) suff = ".xml";
	do
	{
		// tpl->getDir() должно заканчиваться на /
		fname =  QDir::convertSeparators(QString(tpl->getDir()+".ananas-report%1%2").arg(count).arg(suff));
		tmpf.setName(fname);
		if(tmpf.exists())
		{
			if(tmpf.remove()) break;
			else ++count;
		}
		else
		{
			break;
		}
	}while(count<100);

	aLog::print(aLog::MT_DEBUG, tr("aReport: name for template = %1").arg(fname));
	return fname;
}
Example #9
0
//New saveUserLog, moved from DetailDialog.  
//Should create a special UserLog widget that encapsulates the "default"
//message in the widget when no log exists (much like we do with dmsBox now)
void SkyObject::saveUserLog( const QString &newLog ) {
	QFile file;
	QString logs; //existing logs
	
	//Do nothing if new log is the "default" message
	//(keep going if new log is empty; we'll want to delete its current entry)
	if ( newLog == (i18n("Record here observation logs and/or data on %1.").arg(name())) || newLog.isEmpty() )
		return;

	// header label
	QString KSLabel ="[KSLABEL:" + name() + "]";
	//However, we can't accept a star name if it has a greek letter in it:
	if ( type() == STAR ) {
		StarObject *star = (StarObject*)this;
		if ( name() == star->gname() ) 
			KSLabel = "[KSLABEL:" + star->gname( false ) + "]"; //"false": spell out greek letter
	}
	
	file.setName( locateLocal( "appdata", "userlog.dat" ) ); //determine filename in local user KDE directory tree.
	if ( file.open( IO_ReadOnly)) {
		QTextStream instream(&file);
		// read all data into memory
		logs = instream.read();
		file.close();
	}
	
	//Remove old log entry from the logs text
	if ( ! userLog.isEmpty() ) {
		int startIndex, endIndex;
		QString sub;
	
		startIndex = logs.find(KSLabel);
		sub = logs.mid (startIndex);
		endIndex = sub.find("[KSLogEnd]");
	
		logs.remove(startIndex, endIndex + 11);
	}
	
	//append the new log entry to the end of the logs text,
	//but only if the log is not empty
	if ( ! newLog.stripWhiteSpace().isEmpty() )
		logs.append( KSLabel + "\n" + newLog + "\n[KSLogEnd]\n" );
	
	//Open file for writing
	//FIXME: change error message to "cannot write to user log file"
	if ( !file.open( IO_WriteOnly ) ) {
		kdDebug() << i18n( "user log file could not be opened." ) << endl;
		return;
	}
	
	//Write new logs text
	QTextStream outstream(&file);
	outstream << logs;
	
	//Set the log text in the object itself.
	userLog = newLog;
	
	file.close();
}
Example #10
0
Agent::Agent() : QObject(NULL, "agent")
{
	kdebugf();

	connect(gadu, SIGNAL(userStatusChangeIgnored(UinType)), this, SLOT(userFound(UinType)));

	// Main menu entry
	agentActionDescription = new ActionDescription(
		ActionDescription::TypeMainMenu, "agentAction",
		this, SLOT(resultsRequest()),
		"Agent", tr("Who has me on list")
	);
	kadu->insertMenuActionDescription(0, agentActionDescription);

	if(config_file.readBoolEntry("Agent", "FirstTime", true))
	{
		QFile listFile;
		listFile.setName(QString(ggPath("spy-unknownslist").ascii()));
		if(listFile.open(IO_ReadOnly))
		{
			if(MessageBox::ask(tr("Agent has founded spy's unknown-users list. Do you want to append this list to agent module?")))
			{
				QTextStream stream(&listFile);

				QString uin_str, date_str, line;
				bool ok;
				while (!stream.atEnd())
				{
					UnknownUser user;
					bool isAlready = false;

					line = stream.readLine();
					uin_str = line.section(',', 0, 0);
					date_str = line.section(',', 1, 1);

					unsigned int uin_int = uin_str.toUInt(&ok, 10);
					if(!ok)
						kdebugm(KDEBUG_PANIC, "Couldn't cast QString to int");

					foreach(UnknownUser user, UnknownsList)
					{
						if (user.uin == uin_int)
						{
							isAlready = true;
							break;
						}
					}
					if (!isAlready)
					{
						user.uin = uin_int;
						user.date = QDate::fromString(date_str, Qt::ISODate);
						user.seq = 0;
						UnknownsList.append(user);
					}
				}
			}
			listFile.close();
		}
Example #11
0
int initDaemon()
{
  pid_t pid;
  QString s;
  QString pidFileName;
  QFile pidFile;

  // we probably have a nice little race condition here that I am not
  // going to worry about right now.  
  s.sprintf("%s/share/apps/korganizer",KApplication::localkdedir().data());
  qd.setPath(s.data());

  pidFileName.sprintf("%s/alarmd.pid",s.data());
  pidFile.setName(pidFileName.data());

  // a lock file already exists, don't start up.
  if (pidFile.exists()) {
    if(pidFile.open(IO_ReadOnly)) {
      pid_t pid;
      char pidStr[25];
      pidFile.readLine(pidStr, 24);
      pidFile.close();
      pid = atoi(pidStr);
      if (kill(pid, SIGUSR1) < 0) {
	// stale lockfile
	unlink(pidFileName.data()); // get rid of old lockfile
      }
    }
  }

  // if the PID file still exists, a daemon really is running.
  // quit silently.
  if (pidFile.exists()) {
    exit(0);
  } else {
    // make ourselves a daemon
    if ((pid = fork()) < 0)
      return(-1); // we had an error forking
    else if (pid != 0) {
      // make a lock file.
      pidFile.open(IO_ReadWrite);
      s.sprintf("%d",pid);
      pidFile.writeBlock(s.data(), s.length());
      pidFile.close();
      exit(0); // parent dies silently
    }
    
    // child continues
    setsid();
    
    if (getenv("$HOME") != NULL)
      chdir(getenv("$HOME"));
    umask(0);
  }
  return(0);
}
Example #12
0
bool Desk::writeDesk (void)
   {
   QFile file;
   QString fname;

   // remove any old file
   fname = _dir + "/maxdesk.ini";
   file.setName (fname);
   if (file.exists ())
      file.remove ();
   fname = _dir + "/MaxDesk.ini";
   file.setName (fname);
   if (file.exists ())
      file.remove ();
   file.setName (_dir + DESK_FNAME);
   if (file.exists ())
      file.remove ();

   QTextStream stream( &file );
   QString line;

   if (!file.open (QIODevice::WriteOnly))
      return false;

   // write header
   stream << "[DesktopFile]" << endl;
   stream << "File=" << endl;
   stream << endl;
   stream << "[Folder]" << endl;
   stream << "Version=0x00060000" << endl;
   stream << endl;

   stream << "[Files]" << endl;

   // output the file list
   foreach (File *f, _files)
      f->encodeFile (stream);

   _dirty = false; // we are clean again
   return true;
   }
Example #13
0
// ---------------------------------------------------------------
int PackageDialog::insertLibraries(QDataStream& Stream)
{
  QFile File;
  QDir myDir(QucsSettings.QucsHomeDir.absPath() + QDir::separator() + "user_lib");
  QStringList Entries = myDir.entryList("*", QDir::Files, QDir::Name);
  QStringList::iterator it;
  for(it = Entries.begin(); it != Entries.end(); ++it) {
    File.setName(myDir.absFilePath(*it));
    Stream << Q_UINT32(CODE_LIBRARY);
    if(insertFile(*it, File, Stream) < 0)
      return -1;
  }
  return 0;
}
void MultipleBackendsTest::sql2xml()
{
	QString dbname = "testmultiple";
	QSqlDatabase *db = QSqlDatabase::addDatabase( "QPSQL7" );
	db->setDatabaseName( dbname );
	db->setUserName( "ak213" );
	db->setPassword( "ak" );
	db->setHostName( "localhost" );
	if ( ! db->open() ) {
		kdDebug() << "Failed to open database: " << db->lastError().text() << endl;
		return;
	}
	DbBackendIface *backend1 = new InMemorySqlDbBackend( db );
	Manager *manager1 = new Manager( backend1 );

	DbBackendIface *backend2 = new XmlDbBackend( "database3.xml", true );
	Manager *manager2 = new Manager( backend2 );
	
	manager1->copyTo( manager2 );
	manager2->commit();

	delete manager1;
	delete manager2;
	QSqlDatabase::removeDatabase( db );
	
	QFile file;
	QByteArray a1, a2;
	file.setName( "database.xml" );
	CHECK( file.open( IO_ReadOnly ), true );
	a1 = file.readAll();
	file.close();
	file.setName( "database3.xml" );
	CHECK( file.open( IO_ReadOnly ), true );
	a2 = file.readAll();
	file.close();
	CHECK( a1, a2 );
}
Example #15
0
static bool get_dri_device()
{
    QFile file;
    file.setName(INFO_DRI);
    if (!file.exists() || !file.open(QIODevice::ReadOnly))
	return false;

    QTextStream stream(&file);
    QString line = stream.readLine();
    if (!line.isEmpty()) {
	dri_info.module = line.mid(0, line.indexOf(0x20));

	// possible formats, for regression testing
	// line = " PCI:01:00:0";
	// line = " pci:0000:01:00.0"
	QRegExp rx = QRegExp("\\b[Pp][Cc][Ii][:]([0-9a-fA-F]+[:])?([0-9a-fA-F]+[:][0-9a-fA-F]+[:.][0-9a-fA-F]+)\\b");
	if (rx.indexIn(line)>0)	 {
		dri_info.pci = rx.cap(2);
		int end = dri_info.pci.lastIndexOf(':');
		int end2 = dri_info.pci.lastIndexOf('.');
		if (end2>end) end=end2;
		dri_info.pci[end]='.';

		QString cmd = QString("lspci -m -v -s ") + dri_info.pci;
		QStringList pci_info;
		int num;
		if (((num = ReadPipe(cmd, pci_info)) ||
		(num = ReadPipe("/sbin/"+cmd, pci_info)) ||
		(num = ReadPipe("/usr/sbin/"+cmd, pci_info)) ||
		(num = ReadPipe("/usr/local/sbin/"+cmd, pci_info))) && num>=7) {
			for (int i=2; i<=6; i++) {
				line = pci_info[i];
				line.remove(QRegExp("[^:]*:[ ]*"));
				switch (i){
					case 2: dri_info.vendor = line;    break;
					case 3: dri_info.device = line;    break;
					case 4: dri_info.subvendor = line; break;
					case 6: dri_info.rev = line;       break;
				}
			}
			return true;
		}
	}
    }

    return false;
}
Example #16
0
bool
ProjectGenerator::openOutput(QFile &file) const
{
    QString outdir;
    if(!file.name().isEmpty()) {
	QFileInfo fi(file);
	if(fi.isDir())
	    outdir = fi.dirPath() + QDir::separator();
    }
    if(!outdir.isEmpty() || file.name().isEmpty()) {
	QString dir = QDir::currentDirPath();
	int s = dir.findRev('/');
	if(s != -1)
	    dir = dir.right(dir.length() - (s + 1));
	file.setName(outdir + dir + ".pro");
    }
    return MakefileGenerator::openOutput(file);
}
Example #17
0
bool History::open(bool bWrite, QFile &f)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), "%s%c%lu.history",
             HISTORY,
#ifdef WIN32
             '\\',
#else
             '/',
#endif
             m_nUin);
    string fname = pMain->getFullPath(buffer);
    f.setName(QString::fromLocal8Bit(fname.c_str()));
    if (!f.open(bWrite ? IO_ReadWrite | IO_Append : IO_ReadOnly)){
        log(L_WARN, "File %s not open", fname.c_str());
        return false;
    }
    return true;
}
Example #18
0
void MapsPrivate::loadDiffs( const QString& basePath, unsigned int id )
{
    // Try to read the index
    QDir baseFolder( basePath );
    QStringList files = baseFolder.entryList();
    QString mapDiffListName = QString( "mapdifl%1.mul" ).arg( id );
    QString mapDiffFileName = QString( "mapdif%1.mul" ).arg( id );
    QString statDiffFileName = QString( "stadif%1.mul" ).arg( id );
    QString statDiffListName = QString( "stadifl%1.mul" ).arg( id );
    QString statDiffIndexName = QString( "stadifi%1.mul" ).arg( id );
    for ( QStringList::const_iterator it = files.begin(); it != files.end(); ++it )
    {
        if ( ( *it ).lower() == mapDiffListName )
            mapDiffListName = *it;
        else if ( ( *it ).lower() == mapDiffFileName )
            mapDiffFileName = *it;
        else if ( ( *it ).lower() == statDiffFileName )
            statDiffFileName = *it;
        else if ( ( *it ).lower() == statDiffListName )
            statDiffListName = *it;
        else if ( ( *it ).lower() == statDiffIndexName )
            statDiffIndexName = *it;
    }

    QFile mapdiflist( basePath + mapDiffListName );
    mapdifdata.setName( basePath + mapDiffFileName );

    // Try to read a list of ids
    if ( mapdifdata.open( IO_ReadOnly ) && mapdiflist.open( IO_ReadOnly ) )
    {
        QDataStream listinput( &mapdiflist );
        listinput.setByteOrder( QDataStream::LittleEndian );
        unsigned int offset = 0;
        while ( !listinput.atEnd() )
        {
            unsigned int id;
            listinput >> id;
            mappatches.insert( id, offset );
            offset += sizeof( mapblock );
        }
        mapdiflist.close();
    }
Example #19
0
// ---------------------------------------------------------------
int LibraryDialog::intoFile(QString &ifn, QString &ofn, QStringList &IFiles)
{
  int error = 0;
  QFile ifile(ifn);
  if(!ifile.open(QIODevice::ReadOnly)) {
    ErrText->insert(QObject::tr("ERROR: Cannot open file \"%1\".\n").
		    arg(ifn));
    error++;
  }
  else {
    QByteArray FileContent = ifile.readAll();
    ifile.close();
    if(ifile.name().right(4) == ".lst")
      LibDir.remove(ifile.name());
    QDir LibDirSub(LibDir);
    if(!LibDirSub.cd(NameEdit->text())) {
      if(!LibDirSub.mkdir(NameEdit->text())) {
	ErrText->insert(
          QObject::tr("ERROR: Cannot create user library subdirectory !\n"));
	error++;
      }
      LibDirSub.cd(NameEdit->text());
    }
    QFileInfo Info(ofn);
    ofn = Info.fileName();
    IFiles.append(ofn);
    QFile ofile;
    ofile.setName(LibDirSub.absFilePath(ofn));
    if(!ofile.open(QIODevice::WriteOnly)) {
      ErrText->insert(
        QObject::tr("ERROR: Cannot create file \"%1\".\n").arg(ofn));
      error++;
    }
    else {
      QDataStream ds(&ofile);
      ds.writeRawBytes(FileContent.data(), FileContent.size());
      ofile.close();
    }
  }
  return error;
}
Example #20
0
/*!
 *\~english
 *	Writes line in log with name \a log_name
 *\~russian
 *	Пишет строку в лог с именем \a log_name
 *\~
 *	\param log_name - \~english logfile name \~russian Путь к логу (не обязательно) \~
*/
void
aTests::printline2log(const QString &log_name)
{
	QString toWrite;
	toWrite.fill('=',60);
	toWrite+="\n";
	QFile f;
	if(log_name==QString::null)
	{
		f.open( QIODevice::WriteOnly, stdout );
		f.writeBlock((const char*)toWrite,strlen((const char*)toWrite));
	}
	else
	{
		f.setName(log_name);
		f.open( QIODevice::WriteOnly | QIODevice::Append );
		f.writeBlock((const char*)toWrite,strlen((const char*)toWrite));
		f.flush();
	}
	f.close();
}
Example #21
0
void MapsPrivate::loadDiffs( const QString& basepath, unsigned int id )
{
	// Try to read the index
	QFile mapdiflist( basepath + QString( "mapdifl%1.mul" ).arg( id ) );
	mapdifdata.setName( basepath + QString( "mapdif%1.mul" ).arg( id ) );
	mapdifdata.open( IO_ReadOnly );

	// Try to read a list of ids
	if ( mapdifdata.isOpen() && mapdiflist.open( IO_ReadOnly ) )
	{
		QDataStream listinput( &mapdiflist );
		listinput.setByteOrder( QDataStream::LittleEndian );
		unsigned int offset = 0;
		while ( !listinput.atEnd() )
		{
			unsigned int id;
			listinput >> id;
			mappatches.insert( id, offset );
			offset += sizeof( mapblock );
		}
		mapdiflist.close();
	}
Example #22
0
bool dash_open(QFile &file, const QString &filename, int m, FILE *handle)
{
    bool retval = false;
    if (filename == "-")
    {
        if (handle == NULL)
        {
            handle = stdout;
            if (m & IO_ReadOnly)
            {
                handle = stdin;
            }
        }
        retval = file.open(m, handle);
    }
    else
    {
        file.setName(filename);
        retval = file.open(m);
    }

    return retval;
}
void ShowEditTextFileAgent::done () {
	RK_TRACE (APP);
	delete dialog;

	// int_b in RShowFiles means files are to be deleted
	if ((args->type == RCallbackArgs::RShowFiles) && args->int_b) {
		for (int n = 0; n < args->int_a; ++n) {
			// does not compile on some systems (October 2005).
			//QFile (QString (args->chars_a[n])).remove ();
			// Workaround (use this instead for a couple of months):
			QFile file;
			file.setName (QString (args->chars_a[n]));
			file.remove ();
		}
	}

	MUTEX_LOCK;
	// this line is what causes the backend-thread to resume processing:
	args->done = true;
	MUTEX_UNLOCK;

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

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

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

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

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

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

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

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

    // None of the deterministic stuff above has worked: try a heuristic. We
    // try to find a pair of matching timezone abbreviations...that way, we'll
    // likely return a value in the user's own country.
    if (!m_zoneinfoDir.isEmpty())
    {
        tzset();
        AbbreviationsMatch matcher(tzname[0], tzname[1]);
        int bestOffset = INT_MAX;
        for (ZoneMap::Iterator it = m_zones->begin(); it != m_zones->end(); ++it)
        {
            KstTimezone *zone = it.data();
            int candidateOffset = QABS(zone->offset(Qt::LocalTime));
            if (zone->parse(matcher) && matcher.test() && (candidateOffset < bestOffset))
            {
                bestOffset = candidateOffset;
                local = zone;
            }
        }
    }
    if (local)
        return local;
    return m_UTC;
}
const KstTimezones::ZoneMap KstTimezones::allZones()
{
    // Have we already done all the hard work? If not, create the cache.
    if (m_zones)
        return *m_zones;
    m_zones = new ZoneMap();

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

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

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

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

        // Add entry to list.
        if (tokens[0] == "??")
            tokens[0] = "";
        KstTimezone *timezone = new KstTimezone(db, tokens[2], tokens[0], latitude, longitude, tokens[3]);
        add(timezone);
    }
    f.close();
    return *m_zones;
}
Example #26
0
void Desk::readDesk (bool read_sizes)
   {
   QFile oldfile;
   QFile file (_dir + DESK_FNAME);
   QString fname;

   // if there is a maxdesk.ini file, rename it to the official name
   fname = _dir + "/maxdesk.ini";
   oldfile.setName (fname);
   if (!oldfile.exists ())
      {
      fname = _dir + "/MaxDesk.ini";
      oldfile.setName (fname);
      }
   if (oldfile.exists ())
      {
      // if we have the official file, just remove this one
      if (file.exists ())
         oldfile.remove ();
      else
         oldfile.rename (_dir + DESK_FNAME);
      }

   QTextStream stream (&file);
   QString line;
   bool files = false;
   File *f;
   int pos;

   if (file.open (QIODevice::ReadOnly)) while (!stream.atEnd())
      {
      line = stream.readLine(); // line of text excluding '\n'

//      printf( "%s\n", line.latin1() );
      if (line [0] == '[')
         {
         files = line == "[Files]";
         continue;
         }

      // add a new file
      pos = line.find ('=');
      if (files && pos != -1)
         {
         QString fname = line.left (pos);

         QFile test (_dir + fname);
         if (!test.exists ())
            continue;

         if (!addToExistingFile (fname))
            {
            f = createFile (_dir, fname);
            line = line.mid (pos + 1);
            f->decodeFile (line, read_sizes);
            _files << f;
            }
         }
      }

   // advance the position past these
   advance ();
   }
Example #27
0
// ----------------------------------------------------
void QucsLib::slotSelectLibrary(int Index)
{
  int Start, End, NameStart, NameEnd;
  End = Library->count()-1;
  if(Library->text(End) == tr("Search result")) {
    if(Index < End)
      Library->removeItem(End); // if search result still there -> remove it
    else  return;
  }

  CompList->clear();
  LibraryComps.clear();
  DefaultSymbol = "";

  QFile file;
  if(Index < UserLibCount)  // Is it user library ?
    file.setName(UserLibDir.absPath() + QDir::separator() + Library->text(Index) + ".lib");
  else
    file.setName(QucsSettings.LibDir + Library->text(Index) + ".lib");

  if(!file.open(IO_ReadOnly)) {
    QMessageBox::critical(this, tr("Error"),
        tr("Cannot open \"%1\".").arg(
           QucsSettings.LibDir + Library->text(Index) + ".lib"));
    return;
  }

  QTextStream ReadWhole(&file);
  QString LibraryString = ReadWhole.read();
  file.close();

  Start = LibraryString.find("<Qucs Library ");
  if(Start < 0) {
    QMessageBox::critical(this, tr("Error"), tr("Library is corrupt."));
    return;
  }
  End = LibraryString.find('>', Start);
  if(End < 0) {
    QMessageBox::critical(this, tr("Error"), tr("Library is corrupt."));
    return;
  }
  QString LibName = LibraryString.mid(Start, End-Start).section('"', 1, 1);

  Start = LibraryString.find("\n<", End);
  if(Start < 0) return;
  if(LibraryString.mid(Start+2, 14) == "DefaultSymbol>") {
    End = LibraryString.find("\n</DefaultSymbol>");
    if(End < 0) {
      QMessageBox::critical(this, tr("Error"), tr("Library is corrupt."));
      return;
    }

    DefaultSymbol = LibraryString.mid(Start+16, End-Start-16);
    Start = End + 3;
  }

  while((Start=LibraryString.find("\n<Component ", Start)) > 0) {
    Start++;
    NameStart = Start + 11;
    NameEnd = LibraryString.find('>', NameStart);
    if(NameEnd < 0)  continue;

    End = LibraryString.find("\n</Component>", NameEnd);
    if(End < 0)  continue;
    End += 13;

    CompList->insertItem(LibraryString.mid(NameStart, NameEnd-NameStart));
    LibraryComps.append(LibName+'\n'+LibraryString.mid(Start, End-Start));
    Start = End;
  }

  CompList->setSelected(0, true);  // select first item
}
Example #28
0
void CiteDict::generatePage() const
{
  //printf("** CiteDict::generatePage() count=%d\n",m_ordering.count());

  // do not generate an empty citations page
  if (isEmpty()) return; // nothing to cite

  // 1. generate file with markers and citations to OUTPUT_DIRECTORY
  QFile f;
  QCString outputDir = Config_getString("OUTPUT_DIRECTORY");
  QCString citeListFile = outputDir+"/citelist.doc";
  f.setName(citeListFile);
  if (!f.open(IO_WriteOnly)) 
  {
    err("could not open file %s for writing\n",citeListFile.data());
  }
  FTextStream t(&f);
  t << "<!-- BEGIN CITATIONS -->" << endl;
  t << "<!--" << endl;
  QDictIterator<CiteInfo> it(m_entries);
  CiteInfo *ci;
  for (it.toFirst();(ci=it.current());++it)
  {
    t << "\\citation{" << ci->label << "}" << endl;
  }
  t << "-->" << endl;
  t << "<!-- END CITATIONS -->" << endl;
  t << "<!-- BEGIN BIBLIOGRAPHY -->" << endl;
  t << "<!-- END BIBLIOGRAPHY -->" << endl;
  f.close();

  // 2. generate bib2xhtml
  QCString bib2xhtmlFile = outputDir+"/bib2xhtml.pl";
  f.setName(bib2xhtmlFile);
  QCString bib2xhtml = bib2xhtml_pl;
  if (!f.open(IO_WriteOnly)) 
  {
    err("could not open file %s for writing\n",bib2xhtmlFile.data());
  }
  f.writeBlock(bib2xhtml, bib2xhtml.length());
  f.close();

  // 3. generate doxygen.bst
  QCString doxygenBstFile = outputDir+"/doxygen.bst";
  QCString bstData = doxygen_bst;
  f.setName(doxygenBstFile);
  if (!f.open(IO_WriteOnly)) 
  {
    err("could not open file %s for writing\n",doxygenBstFile.data());
  }
  f.writeBlock(bstData, bstData.length());
  f.close();

  // 4. for html we just copy the bib files to the output so that
  //    bibtex can find them without path (bibtex doesn't support path's
  //    with spaces!)
  QList<QCString> tempFiles;
  tempFiles.setAutoDelete(TRUE);
  QDir thisDir;
  if (Config_getBool("GENERATE_HTML"))
  {
    // copy bib files to the latex output dir
    QStrList &citeDataList = Config_getList("CITE_BIB_FILES");
    QCString bibOutputDir = outputDir+"/";
    QFileInfo fo(bibOutputDir);
    const char *bibdata = citeDataList.first();
    while (bibdata)
    {
      QCString bibFile = bibdata;
      if (!bibFile.isEmpty() && bibFile.right(4)!=".bib") bibFile+=".bib";
      QFileInfo fi(bibFile);
      if (fi.exists() && fi.dirPath(TRUE)!=fo.absFilePath())
      {
        if (!bibFile.isEmpty())
        {
          QCString destFile=bibOutputDir+fi.fileName().data();
          copyFile(bibFile,destFile);
          tempFiles.append(new QCString(destFile));
        }
      }
      else if (!fi.exists())
      {
        err("bib file %s not found!\n",bibFile.data());
      }
      bibdata = citeDataList.next();
    }
  }

  QCString oldDir = QDir::currentDirPath().utf8();
  QDir::setCurrent(outputDir);

  // 5. run bib2xhtml perl script on the generated file which will insert the
  //    bibliography in citelist.doc
  portable_system("perl","\""+bib2xhtmlFile+"\" "+getListOfBibFiles(" ",FALSE)+" \""+
                         citeListFile+"\"");

  QDir::setCurrent(oldDir);

  // 6. read back the file
  f.setName(citeListFile);
  if (!f.open(IO_ReadOnly)) 
  {
    err("could not open file %s/citelist.doc for reading\n",outputDir.data());
  }
  bool insideBib=FALSE;
  
  QCString doc;
  QFileInfo fi(citeListFile);
  QCString input(fi.size()+1);
  f.readBlock(input.data(),fi.size());
  f.close();
  input.at(fi.size())='\0';
  int p=0,s;
  //printf("input=[%s]\n",input.data());
  while ((s=input.find('\n',p))!=-1)
  {
    QCString line = input.mid(p,s-p);
    //printf("p=%d s=%d line=[%s]\n",p,s,line.data());
    p=s+1;

    if      (line.find("<!-- BEGIN BIBLIOGRAPHY")!=-1) insideBib=TRUE;
    else if (line.find("<!-- END BIBLIOGRAPH")!=-1)    insideBib=FALSE;
    else if (insideBib) doc+=line+"\n";
    int i;
    // determine text to use at the location of the @cite command
    if (insideBib && (i=line.find("<a name=\"CITEREF_"))!=-1)
    {
      int j=line.find("\">[");
      int k=line.find("]</a>");
      if (j!=-1 && k!=-1)
      {
        QCString label = line.mid(i+17,j-i-17);
        QCString number = line.mid(j+2,k-j-1);
        CiteInfo *ci = m_entries.find(label);
        //printf("label='%s' number='%s' => %p\n",label.data(),number.data(),ci);
        if (ci)
        {
          ci->text = number;
        }
      }
    }
  }
  //printf("doc=[%s]\n",doc.data());

  // 7. add it as a page
  addRelatedPage(CiteConsts::fileName,
       theTranslator->trCiteReferences(),doc,0,CiteConsts::fileName,1,0,0,0);

  // 8. for latex we just copy the bib files to the output and let 
  //    latex do this work.
  if (Config_getBool("GENERATE_LATEX"))
  {
    // copy bib files to the latex output dir
    QStrList &citeDataList = Config_getList("CITE_BIB_FILES");
    QCString latexOutputDir = Config_getString("LATEX_OUTPUT")+"/";
    const char *bibdata = citeDataList.first();
    while (bibdata)
    {
      QCString bibFile = bibdata;
      if (!bibFile.isEmpty() && bibFile.right(4)!=".bib") bibFile+=".bib";
      QFileInfo fi(bibFile);
      if (fi.exists())
      {
        if (!bibFile.isEmpty())
        {
          copyFile(bibFile,latexOutputDir+fi.fileName().data());
        }
      }
      else
      {
        err("bib file %s not found!\n",bibFile.data());
      }
      bibdata = citeDataList.next();
    }
  }

  // 9. Remove temporary files
  thisDir.remove(citeListFile);
  thisDir.remove(doxygenBstFile);
  thisDir.remove(bib2xhtmlFile);
  while (!tempFiles.isEmpty()) 
  {
    QCString *s=tempFiles.take(0);
    thisDir.remove(*s);
  }
}
Example #29
0
// -------------------------------------------------------------------------
bool SpiceDialog::loadSpiceNetList(const QString& s)
{
  Comp->withSim = false;
  if(s.isEmpty()) return false;
  QFileInfo FileInfo(QucsWorkDir, s);

  NodesList->clear();
  PortsList->clear();
  textStatus = 0;
  Line = Error = "";

  QString preprocessor = PrepCombo->currentText();
  if (preprocessor != "none") {
    bool piping = true;
    QString script;
#ifdef __MINGW32__
    QString interpreter = "tinyperl.exe";
#else
    QString interpreter = "perl";
#endif
    if (preprocessor == "ps2sp") {
      script = "ps2sp";
    } else if (preprocessor == "spicepp") {
      script = "spicepp.pl";
    } else if (preprocessor == "spiceprm") {
      script = "spiceprm";
      piping = false;
    }
    script = QucsSettings.BinDir + script;
    SpicePrep = new QProcess(this);
    SpicePrep->addArgument(interpreter);
    SpicePrep->addArgument(script);
    SpicePrep->addArgument(FileInfo.filePath());

    QFile PrepFile;
    QFileInfo PrepInfo(QucsWorkDir, s + ".pre");
    QString PrepName = PrepInfo.filePath();

    if (!piping) {
      SpicePrep->addArgument(PrepName);
      connect(SpicePrep, SIGNAL(readyReadStdout()), SLOT(slotSkipOut()));
      connect(SpicePrep, SIGNAL(readyReadStderr()), SLOT(slotGetPrepErr()));
    } else {
      connect(SpicePrep, SIGNAL(readyReadStdout()), SLOT(slotGetPrepOut()));
      connect(SpicePrep, SIGNAL(readyReadStderr()), SLOT(slotGetPrepErr()));
    }

    QMessageBox *MBox = new QMessageBox(tr("Info"),
	       tr("Preprocessing SPICE file \"%1\".").arg(FileInfo.filePath()),
               QMessageBox::NoIcon, QMessageBox::Abort,
               QMessageBox::NoButton, QMessageBox::NoButton, this, 0, true,
	       Qt::WStyle_DialogBorder |  Qt::WDestructiveClose);
    connect(SpicePrep, SIGNAL(processExited()), MBox, SLOT(close()));

    if (piping) {
      PrepFile.setName(PrepName);
      if(!PrepFile.open(IO_WriteOnly)) {
	QMessageBox::critical(this, tr("Error"),
          tr("Cannot save preprocessed SPICE file \"%1\".").
	  arg(PrepName));
	return false;
      }
      prestream = new QTextStream(&PrepFile);
    }

    if(!SpicePrep->start()) {
      QMessageBox::critical(this, tr("Error"),
        tr("Cannot execute \"%1\".").arg(interpreter + " " + script));
      if (piping) {
	PrepFile.close();
	delete prestream;
      }
      return false;
    }
    SpicePrep->closeStdin();

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

    if(!Error.isEmpty()) {
      QMessageBox::critical(this, tr("SPICE Preprocessor Error"), Error);
      return false;
    }
    FileInfo = QFileInfo(QucsWorkDir, s + ".pre");
  }

  // first call Qucsconv ............
  QucsConv = new QProcess(this);
  QucsConv->addArgument(QucsSettings.BinDir + "qucsconv");
  QucsConv->addArgument("-if");
  QucsConv->addArgument("spice");
  QucsConv->addArgument("-of");
  QucsConv->addArgument("qucs");
  QucsConv->addArgument("-i");
  QucsConv->addArgument(FileInfo.filePath());
  connect(QucsConv, SIGNAL(readyReadStdout()), SLOT(slotGetNetlist()));
  connect(QucsConv, SIGNAL(readyReadStderr()), SLOT(slotGetError()));

  QMessageBox *MBox = new QMessageBox(tr("Info"),
	       tr("Converting SPICE file \"%1\".").arg(FileInfo.filePath()),
               QMessageBox::NoIcon, QMessageBox::Abort,
               QMessageBox::NoButton, QMessageBox::NoButton, this, 0, true,
	       Qt::WStyle_DialogBorder |  Qt::WDestructiveClose);
  connect(QucsConv, SIGNAL(processExited()), MBox, SLOT(close()));

  if(!QucsConv->start()) {
    QMessageBox::critical(this, tr("Error"),
      tr("Cannot execute \"%1\".").arg(QucsSettings.BinDir + "qucsconv"));
    return false;
  }
  QucsConv->closeStdin();

  MBox->exec();
  delete QucsConv;

  if(!Error.isEmpty())
    QMessageBox::critical(this, tr("QucsConv Error"), Error);

  Property *pp = Comp->Props.at(1);
  if(!pp->Value.isEmpty()) {
    PortsList->clear();
    PortsList->insertStringList(QStringList::split(',', pp->Value));
  }

  QString tmp;
  QListBoxItem *pi;
  for(unsigned int i=0; i<PortsList->count(); i++) {
    tmp = PortsList->text(i).remove(0, 4);
    PortsList->changeItem(tmp, i);

    pi = NodesList->findItem(tmp, Qt::CaseSensitive | Qt::ExactMatch);
    if(pi) delete pi;
    else PortsList->removeItem(i--);
  }
  return true;
}
Example #30
0
File: setting.cpp Project: rd8/qGo
void Setting::loadSettings()
{
	QFile file;

	// set under Linux
	settingHomeDir = QString(getenv("HOME"));
	if (!settingHomeDir)
		// set under Windows
		settingHomeDir = QString(getenv("USERPROFILE"));
	if (!settingHomeDir)
	{
		// however...
		qDebug("HOME and/or USERPROFILE are not set");
		settingHomeDir = QDir::homeDirPath();
		file.setName(settingHomeDir + "/.qgoclientrc");
		if (file.exists())
		{
			// rename, but use it anyway
			QString oldName = ".qgoclientrc";
			QString newName = ".qgoclientrc.bak";
			QDir::home().rename(oldName, newName);
			file.setName(settingHomeDir + "/.qgoclientrc.bak");
		}
		else
			// file may be already renamed
			file.setName(settingHomeDir + "/." + PACKAGE + "rc");
	}
	else
		file.setName(settingHomeDir + "/." + PACKAGE + "rc");

	if (!file.exists() || !file.open(IO_ReadOnly))
	{
		qDebug("Failed loading settings: " + file.name());

		// maybe old file available
		file.setName(QDir::homeDirPath() + "/.qgoclientrc");

		if (!file.exists() || !file.open(IO_ReadOnly))
		{
			qWarning("Failed loading settings: " + file.name());
			return;
		}
	}

	qDebug("Use settings: " + file.name());

	// read file
	QTextStream txt(&file);
	QString s;
	int pos, pos1, pos2;
	while (!txt.eof())
	{
		s = txt.readLine();
		if (s.length() > 2)
		{
			// ' ' is delitmiter between key and txt
			pos = s.find(' ');
			// find first '['
			pos1 = s.find('[');
			// find last ']'
			pos2 = s.findRev(']');
			writeEntry(s.left(pos), s.mid(pos1 + 1, pos2 - pos1 - 1));
		}
	}

	file.close();

	// init fonts and colors
	updateFont(fontStandard, "FONT_MAIN");
	updateFont(fontMarks, "FONT_MARK");
	updateFont(fontComments, "FONT_COMMENT");
	updateFont(fontLists, "FONT_LIST");
	updateFont(fontClocks, "FONT_CLOCK");
	updateFont(fontConsole, "FONT_CONSOLE");
 	s = readEntry("COLOR_BK");
	if (s)
		colorBackground = QColor(s);
	s = readEntry("COLOR_ALT_BK");
	if (s)
		colorAltBackground = QColor(s);
	s=readEntry("CHARSET");
	charset->blackStone = s.constref(0);
	charset->emptyPoint = s.constref(1);
	charset->hBorder = s.constref(2);
	charset->starPoint = s.constref(3);
	charset->vBorder = s.constref(4);
	charset->whiteStone = s.constref(5);  
}