Esempio n. 1
0
bool BinaryFormat::checkHeader(QDataStream &stream) const
{
    Q_UINT32 magic, version;

    stream >> magic >> version;

    QFile *file = dynamic_cast< QFile * >(stream.device());

    if(!file)
    {
        kdError() << i18n("Not a file?") << endl;
        return false;
    }

    if(magic != 0x2e93e)
    {
        kdError() << i18n("File '%1' is not binary format.").arg(file->name()) << endl;
        return false;
    }

    if(version != BINARY_FORMAT_VERSION)
    {
        kdError() << i18n("File '%1' is the wrong version.").arg(file->name()) << endl;
        return false;
    }

    return true;
}
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"));

}
Esempio n. 3
0
void QFileInfo::setFile( const QFile &file )
{
    fn	= file.name();
    slashify( fn );
    delete fic;
    fic = 0;
}
Esempio n. 4
0
bool KlustersXmlReader::parseFile(const QFile& file,fileType type){
 this->type = type;
  
 // Init libxml
 xmlInitParser();

 // Load XML document
 doc = xmlParseFile(file.name());
 if(doc == NULL) return false;
 
 // Create xpath evaluation context
 xpathContex = xmlXPathNewContext(doc);
 if(xpathContex== NULL){
  xmlFreeDoc(doc);
  return false;   
 }

 //Read the document version
 xmlNodePtr rootElement = xmlDocGetRootElement(doc);
 xmlChar* versionTag = xmlCharStrdup(VERSION);
 if(rootElement != NULL){
  xmlChar* sVersion = xmlGetProp(rootElement,versionTag);
  if(sVersion != NULL) readVersion = QString((char*)sVersion);
  xmlFree(sVersion);
 }
 xmlFree(versionTag);

 return true;
}
//=====================================
// XAccessX reset and switch to Intro
//-------------------------------------
void XAccessX::resetPage (int reload) {
	// ...
	// this function is called if the xaccess dialog is finished or canceled
	// AccessX is an X11 extension which need a seperate configuration file
	// which is outside of the normal configuration create via ISaX. Therefore
	// we don`t need to serialize any data here
	// ---
	if (reload == PAGE_RELOAD) {
	if (mEnable -> isChecked()) {
		QFile* mHandle = new QFile (
			"/usr/X11R6/lib/X11/xkb/X0-config.keyboard"
		);
		if (! mHandle -> open(IO_WriteOnly)) {
		log (L_ERROR,
			"XAccessX::open failed on: %s -> %s\n",
			mHandle->name().ascii(),strerror(errno)
		);
		}
		QString* speed = new QString();
		speed -> sprintf ( 
			"%d",mLCD -> intValue()
		);
		QDict<char> data;
		data.insert ("MouseKeysMaxSpeed=" , 
			speed->ascii()
		);
		data.insert ("MouseKeysDelay="    , "40");
		data.insert ("MouseKeysInterval=" , "10" );
		data.insert ("MouseKeysTimeToMax=", "1000" );
		data.insert ("MouseKeysCurve="    , "0"  );
		data.insert ("Controls+=","MouseKeysAccel");
		#if 0
		data.insert ("Controls+=",
			"MouseKeysAccel + AccessxKeys"
		);
		data.insert ("Feedback+=",
			"SlowKeysPress + SlowKeysAccept + StickyKeys + LatchToLock"
		);
		#endif
		QDictIterator<char> it (data);
		for (; it.current(); ++it) {
			QString line;
			line.sprintf ("%s %s\n",
				it.currentKey().ascii(),it.current()
			);
			mHandle -> writeBlock (
				line.ascii(),line.length()
			);
		}
		mHandle -> close();
	}
	}
	if (reload == PAGE_RELOAD) {
		slotApply();
	}
	mStatus -> clear();
	slotIntro (mIndex);
	XTemplate::resetPage ();
	mStack -> raiseWidget (Intro);
}
Esempio n. 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 {
Esempio n. 7
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);
}
Esempio n. 8
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);
}
Esempio n. 9
0
QFileInfo::QFileInfo( const QFile &file )
{
    fn	  = file.name();
    slashify( fn );
    fic	  = 0;
    cache = TRUE;
#if defined(Q_OS_UNIX)
    symLink = FALSE;
#endif
}
Esempio n. 10
0
Sound * qGo::retrieveSound(const char * filename, SearchPath& sp)
{
  	QFile qfile(filename);
  	QFile * foundFile = sp.findFile(qfile);
	QString msg(filename);
  	if (! foundFile) 
	{
    		QString msg(filename);
    		msg.append(" not found");
    		qDebug(msg);
    		return (Sound *) NULL;
  	}
	else 
	{
		msg.append(" found : " + foundFile->name());
		qDebug(msg);
    		return SoundFactory::newSound(foundFile->name());
  	}
}
Esempio n. 11
0
bool TrendPw::loadTemplateFile( )
{
  ConfigRC conf_rc; 

  QFile f ( QString::fromStdString(conf_rc.getVisPredefPwPath( ) + "/trendpw.xml") );
  
  if ( !f.open( QIODevice::ReadOnly ) ) {
qDebug("Cant load file!!! %s %s", f.name().ascii(), __PRETTY_FUNCTION__ );
    return false;
  }
  
  if ( !pw_xml_template.setContent( &f ) ) {
qDebug("SET CONTENT FAILED!!! %s %s", f.name().ascii(), __PRETTY_FUNCTION__ );  
    f.close();  
    return false;
  }
  
  f.close();
  
  return true;
}
Esempio n. 12
0
static int open_file(QFile & fp, BooL & ro)
{
  QString filename = fp.name();
  
  while (! fp.open(QIODevice::ReadOnly)) {
    if (QMessageBox::critical(0, "Uml",
			      filename + "\ncannot be opened for read, retry ?\n",
			      "yes", "no", 0, 0, 0) != 0)
      return -1;
  }
  
  QFileInfo fi(fp);
  
  ro = !fi.isWritable();
  
  return fi.size();
}
Esempio n. 13
0
KSPlanetBase::KSPlanetBase( KStarsData *kd, QString s, QString image_file, double pSize )
 : SkyObject( 2, 0.0, 0.0, 0.0, s, "" ), Rearth(0.0), Image(0), data(kd) {

	 if (! image_file.isEmpty()) {
		QFile imFile;

		if ( KSUtils::openDataFile( imFile, image_file ) ) {
			imFile.close();
			Image0.load( imFile.name() );
			Image = Image0.convertDepth( 32 );
			Image0 = Image;
		}
	}
	PositionAngle = 0.0;
	ImageAngle = 0.0;
	PhysicalSize = pSize;
	Trail.setAutoDelete( TRUE );
}
Esempio n. 14
0
/*
 * let's call the one with the filename
 */
void FileTransfer::sendFile( const QFile& file ) {
    sendFile( file.name() );
}
Esempio n. 15
0
File: setting.cpp Progetto: 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);  
}
Esempio n. 16
0
// main method for invoking..
void XMLSchemaWriter::writeClass(UMLClassifier *c)
{

    if (!c) {
        kDebug()<<"Cannot write class of NULL classifier!\n";
        return;
    }

    // find an appropriate name for our file
    QString fileName = findFileName(c,".xsd");

    if (fileName.isEmpty()) {
        emit codeGenerated(c, false);
        return;
    }

    // check that we may open that file for writing
    QFile file;
    if ( !openFile(file, fileName) ) {
        emit codeGenerated(c, false);
        return;
    }

    QTextStream XMLschema(&file);

    // set package namespace tag appropriately
    if(!c->getPackage().isEmpty())
        packageNamespaceTag = c->getPackage();

    // START WRITING

    // 0. FIRST THING: open the xml processing instruction. This MUST be
    // the first thing in the file
    XMLschema<<"<?xml version=\"1.0\"?>"<<m_endl;

    // 1. create the header
    QString headerText = getHeadingFile(".xsd");
    if(!headerText.isEmpty()) {
        headerText.replace(QRegExp("%filename%"),fileName);
        headerText.replace(QRegExp("%filepath%"),file.name());
    }
    if(!headerText.isEmpty())
        XMLschema<<headerText<<m_endl;

    // 2. Open schema element node with appropriate namespace decl
    XMLschema<<"<"<<makeSchemaTag("schema");
    // common namespaces we know will be in the file..
    XMLschema<<" targetNamespace=\""<<packageNamespaceURI+packageNamespaceTag<<"\""<<m_endl;
    XMLschema<<" xmlns:"<<schemaNamespaceTag<<"=\""<<schemaNamespaceURI<<"\"";
    XMLschema<<" xmlns:"<<packageNamespaceTag<<"=\""<<packageNamespaceURI+packageNamespaceTag<<"\"";

    XMLschema<<">"<<m_endl; // close opening declaration

    m_indentLevel++;

    // 3? IMPORT statements -- do we need to do anything here? I suppose if
    // our document has more than one package, which is possible, we are missing
    // the correct import statements. Leave that for later at this time.
    /*
    //only import classes in a different package as this class
    UMLPackageList imports;
    findObjectsRelated(c,imports);
    for(UMLPackage *con = imports.first(); con ; con = imports.next())
        if(con->getPackage() != c->getPackage())
                XMLschema<<"import "<<con->getPackage()<<"."<<cleanName(con->getName())<<";"<<m_endl;
    */

    // 4. BODY of the schema.
    // start the writing by sending this classifier, the "root" for this particular
    // schema, to writeClassifier method, which will subsequently call itself on all
    // related classifiers and thus populate the schema.
    writeClassifier(c, XMLschema);

    // 5. What remains is to make the root node declaration
    XMLschema<<m_endl;
    writeElementDecl(getElementName(c), getElementTypeName(c), XMLschema);

    // 6. Finished: now we may close schema decl
    m_indentLevel--;
    XMLschema<<getIndent()<<"</"<<makeSchemaTag("schema")<<">"<<m_endl; // finished.. close schema node

    // bookeeping for code generation
    emit codeGenerated(c, true);

    // tidy up. no dangling open files please..
    file.close();

    // need to clear HERE, NOT in the destructor because we want each
    // schema that we write to have all related classes.
    writtenClassifiers.clear();
}
Esempio n. 17
0
FITSViewer::FITSViewer (const KURL *url, QWidget *parent, const char *name)
	: KMainWindow (parent, name)
{
    image      = NULL;
    currentURL = *url;
    imgBuffer  = NULL;
    histo      = NULL;
    Dirty      = 0;
    
    /* Initiliaze menu actions */
    history = new KCommandHistory(actionCollection());
    history->setUndoLimit(10);
    history->setRedoLimit(10);
    history->documentSaved();
    connect(history, SIGNAL(documentRestored()), this, SLOT(fitsRestore()));
    
    /* Setup image widget */    
    image = new FITSImage(this);
    setCentralWidget(image);
   
    statusBar()->insertItem("", 0);
    statusBar()->setItemFixed(0, 100);
    statusBar()->insertItem("", 1);
    statusBar()->setItemFixed(1, 100);
    statusBar()->insertItem("", 2);
    statusBar()->setItemFixed(2, 100);
    statusBar()->insertItem(i18n("Welcome to KStars FITS Viewer"), 3, 1, true);
    statusBar()->setItemAlignment(3 , Qt::AlignLeft);
    
    /* FITS initializations */
    if (!initFITS())
    {
     close();
     return;
    }
     
    QFile tempFile;
    
    if (KSUtils::openDataFile( tempFile, "imgreduction.png" ) )
    {
    	new KAction( i18n("Image Reduction"), tempFile.name(), KShortcut( "Ctrl+R" ), this, SLOT( imageReduction()), actionCollection(), "image_reduce");
	tempFile.close();
    }
    else
    	new KAction( i18n("Image Reduction"), "blend", KShortcut( "Ctrl+R" ), this, SLOT( imageReduction()), actionCollection(), "image_reduce");
	
    /*if (KSUtils::openDataFile( tempFile, "bricon.png" ) )
    {
    	new KAction( i18n("Brightness/Contrast"), tempFile.name(), KShortcut( "Ctrl+T" ), this, SLOT( BrightContrastDlg()), actionCollection(), "image_brightness_contrast");
	tempFile.close();
    }
    else*/
       	new KAction( i18n("Brightness/Contrast"), "contrast+", KShortcut( "Ctrl+T" ), this, SLOT( BrightContrastDlg()), actionCollection(), "image_brightness_contrast");
	
    if (KSUtils::openDataFile( tempFile, "histogram.png" ) )
    {
    	new KAction ( i18n("Histogram"), tempFile.name(), KShortcut("Ctrl+H"), this, SLOT (imageHistogram()), actionCollection(), "image_histogram");
	tempFile.close();
    }
    else
        new KAction ( i18n("Histogram"), "wizard", KShortcut("Ctrl+H"), this, SLOT (imageHistogram()), actionCollection(), "image_histogram");
    
    KStdAction::open(this, SLOT(fileOpen()), actionCollection());   
    KStdAction::save(this, SLOT(fileSave()), actionCollection());
    KStdAction::saveAs(this, SLOT(fileSaveAs()), actionCollection());
    KStdAction::close(this, SLOT(slotClose()), actionCollection());
    KStdAction::copy(this, SLOT(fitsCOPY()), actionCollection());
    KStdAction::zoomIn(image, SLOT(fitsZoomIn()), actionCollection());
    KStdAction::zoomOut(image, SLOT(fitsZoomOut()), actionCollection());
    new KAction( i18n( "&Default Zoom" ), "viewmagfit.png", KShortcut( "Ctrl+D" ),
		image, SLOT(fitsZoomDefault()), actionCollection(), "zoom_default" );
    new KAction( i18n( "Statistics"), "sum", 0, this, SLOT(fitsStatistics()), actionCollection(), "image_stats");
    new KAction( i18n( "FITS Header"), "frame_spreadsheet.png", 0, this, SLOT(fitsHeader()), actionCollection(), "fits_editor");
    
   /* Create GUI */  
   createGUI("fitsviewer.rc");
     
   /* initially resize in accord with KDE rules */
   resize(640, 480); 
}
Esempio n. 18
0
void KConfigINIBackEnd::parseSingleConfigFile(QFile &rFile, KEntryMap *pWriteBackMap, bool bGlobal, bool bDefault)
{
    const char *s;   // May get clobbered by sigsetjump, but we don't use them afterwards.
    const char *eof; // May get clobbered by sigsetjump, but we don't use them afterwards.
    QByteArray data;

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

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

    QCString aCurrentGroup("<default>");

    unsigned int ll = localeString.length();

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

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

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

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

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

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

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

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

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

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

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

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

            groupOptionImmutable = fileOptionImmutable;

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

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

            if(groupSkip && !bDefault)
                continue;

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

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

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

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

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

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

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

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

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

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

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

#ifdef HAVE_MMAP
    if(map)
    {
        munmap((char *)map, rFile.size());
#ifdef SIGBUS
        sigaction(SIGBUS, &mmap_old_sigact, 0);
#endif
    }
#endif
}
Esempio n. 19
0
// ------------------------------------------------------------------------
void SimMessage::startSimulator()
{
  // Using the Doc pointer here is risky as the user may have closed
  // the schematic, but converting the SPICE netlists is (hopefully)
  // faster than the user (I have no other idea).

  QString SimTime;
  QString Program;
  QStringList Arguments;
  QString SimPath = QDir::convertSeparators (QucsHomeDir.absPath());
#ifdef __MINGW32__
  QString QucsDigiLib = "qucsdigilib.bat";
  QString QucsDigi = "qucsdigi.bat";
  QString QucsVeri = "qucsveri.bat";
#else
  QString QucsDigiLib = "qucsdigilib";
  QString QucsDigi = "qucsdigi";
  QString QucsVeri = "qucsveri";
#endif
  SimOpt = NULL;
  bool isVerilog = false;

  // Simulate text window.
  if(DocWidget->inherits("QTextEdit")) {

    TextDoc * Doc = (TextDoc*)DocWidget;

    // Take VHDL file in memory as it could contain unsaved changes.
    Stream << Doc->text();
    NetlistFile.close();
    ProgText->insert(tr("done.")+"\n");  // of "creating netlist... 

    // Simulation.
    if (Doc->simulation) {
      SimTime = Doc->SimTime;
      QString libs = Doc->Libraries.lower();
#ifdef __MINGW32__
      if(libs.isEmpty()) {
	libs = "-Wl";
      } else {
	libs.replace(" ",",-l");
	libs = "-Wl,-l" + libs;
      }
#else
      if(libs.isEmpty()) {
	libs = "-c";
      } else {
	libs.replace(" ",",-l");
	libs = "-c,-l" + libs;
      }
#endif
      Program = pathName(QucsSettings.BinDir + QucsDigi);
	  Arguments  << "netlist.txt" << DataSet << SimTime << pathName(SimPath)
		  << pathName(QucsSettings.BinDir) << libs;
    }
    // Module.
    else {
      QString text = Doc->text();
      VHDL_File_Info VInfo (text);
      QString entity = VInfo.EntityName.lower();
      QString lib = Doc->Library.lower();
      if (lib.isEmpty()) lib = "work";
      QString dir = QDir::convertSeparators (QucsHomeDir.path());
      QDir vhdlDir(dir);
      if(!vhdlDir.exists("vhdl"))
	if(!vhdlDir.mkdir("vhdl")) {
	  ErrText->insert(tr("ERROR: Cannot create VHDL directory \"%1\"!")
			  .arg(vhdlDir.path()+"/vhdl"));
	  return;
	}
      vhdlDir.setPath(vhdlDir.path()+"/vhdl");
      if(!vhdlDir.exists(lib))
	if(!vhdlDir.mkdir(lib)) {
	  ErrText->insert(tr("ERROR: Cannot create VHDL directory \"%1\"!")
			  .arg(vhdlDir.path()+"/"+lib));
	  return;
	}
      vhdlDir.setPath(vhdlDir.path()+"/"+lib);
      QFile destFile;
      destFile.setName(vhdlDir.filePath(entity+".vhdl"));
      if(!destFile.open(QIODevice::WriteOnly)) {
	ErrText->insert(tr("ERROR: Cannot create \"%1\"!")
			.arg(destFile.name()));
	return;
      }
      destFile.writeBlock(text.ascii(), text.length());
      destFile.close();
      Program = pathName(QucsSettings.BinDir + QucsDigiLib);
	  Arguments << "netlist.txt" << pathName(SimPath) << entity << lib;
    }
  }
  // Simulate schematic window.
  else {
    // output NodeSets, SPICE simulations etc.
    for(QStringList::Iterator it = Collect.begin();
	it != Collect.end(); ++it) {
      // don't put library includes into netlist...
      if ((*it).right(4) != ".lst" &&
	  (*it).right(5) != ".vhdl" &&
	  (*it).right(4) != ".vhd" &&
	  (*it).right(2) != ".v") {
	Stream << *it << '\n';
      }
    }
    Stream << '\n';

    isVerilog = ((Schematic*)DocWidget)->isVerilog;
    SimTime = ((Schematic*)DocWidget)->createNetlist(Stream, SimPorts);
    if(SimTime.length()>0&&SimTime.at(0) == '\xA7') {
      NetlistFile.close();
      ErrText->insert(SimTime.mid(1));
      FinishSimulation(-1);
      return;
    }
    if (isVerilog) {
      Stream << "\n"
	     << "  initial begin\n"
	     << "    $dumpfile(\"digi.vcd\");\n"
	     << "    $dumpvars();\n"
	     << "    #" << SimTime << " $finish;\n"
	     << "  end\n\n"
	     << "endmodule // TestBench\n";
    }
    NetlistFile.close();
    ProgText->insert(tr("done.")+"\n");  // of "creating netlist... 

    if(SimPorts < 0) {
      if((SimOpt = findOptimization((Schematic*)DocWidget))) {
	    ((Optimize_Sim*)SimOpt)->createASCOnetlist();
	    Program = QucsSettings.AscoDir + "asco"+ executablePostfix; 
        Arguments << "-qucs" << QucsHomeDir.filePath("asco_netlist.txt") 
                  << "-o" << "asco_out";
      }
      else {
	    Program = QucsSettings.BinDir + "qucsator" + executablePostfix;

        Arguments << "-b" << "-g" << "-i" 
                  << QucsHomeDir.filePath("netlist.txt") 
                  << "-o" << DataSet;
      }
    } else {
      if (isVerilog) {
          Program = pathName(QucsSettings.BinDir + QucsVeri);
		  Arguments << "netlist.txt" << DataSet 
                    << SimTime << pathName(SimPath)
                    << pathName(QucsSettings.BinDir) << "-c";
      } else {
#ifdef __MINGW32__
	Program = pathName(QucsSettings.BinDir + QucsDigi);
	Arguments << "netlist.txt" << DataSet << SimTime << pathName(SimPath)
		      << pathName(QucsSettings.BinDir) << "-Wl" << "-c";
#else
	Program = pathName(QucsSettings.BinDir + QucsDigi);
	Arguments << "netlist.txt" << DataSet << SimTime << pathName(SimPath)
		      << pathName(QucsSettings.BinDir) << "-Wall" << "-c";

#endif
      }
    }
  }

  disconnect(&SimProcess, 0, 0, 0);
  connect(&SimProcess, SIGNAL(readyReadStandardError()), SLOT(slotDisplayErr()));
  connect(&SimProcess, SIGNAL(readyReadStandardOutput()), SLOT(slotDisplayMsg()));
  connect(&SimProcess, SIGNAL(finished(int)), SLOT(slotSimEnded(int)));

#ifdef SPEEDUP_PROGRESSBAR
  waitForUpdate = false;
#endif
  wasLF = false;
  
  ProgressText = "";
  
#ifdef __MINGW32__  
  QString sep(";"); // path separator
#else  
  QString sep(":");
#endif
  
  // append process PATH 
  QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
  env.insert("PATH", env.value("PATH") + sep + QucsSettings.BinDir );
  SimProcess.setProcessEnvironment(env); 
  QFile file(Program);
  if ( !file.exists() ){
    ErrText->insert(tr("ERROR: Program not found: %1").arg(Program));
    FinishSimulation(-1);
    return;
  }
  else
    file.close();
  
  SimProcess.start(Program, Arguments); // launch the program
  
  if(!SimProcess.Running) {
    ErrText->insert(tr("ERROR: Cannot start simulator!"));
    FinishSimulation(-1);
    return;
  }
	
}
Esempio n. 20
0
void CSharpWriter::writeClass(UMLClassifier *c) {
    if (!c) {
        kDebug()<<"Cannot write class of NULL concept!" << endl;
        return;
    }

    QString classname = cleanName(c->getName());
    //find an appropriate name for our file
    QString fileName = findFileName(c, ".cs");
    if (fileName.isEmpty()) {
        emit codeGenerated(c, false);
        return;
    }

    QFile filecs;
    if (!openFile(filecs, fileName)) {
        emit codeGenerated(c, false);
        return;
    }
    QTextStream cs(&filecs);

    //////////////////////////////
    //Start generating the code!!
    /////////////////////////////


    //try to find a heading file (license, coments, etc)
    QString str;
    str = getHeadingFile(".cs");
    if (!str.isEmpty()) {
        str.replace(QRegExp("%filename%"),fileName);
        str.replace(QRegExp("%filepath%"),filecs.name());
        cs<<str<<m_endl;
    }

    UMLDoc *umldoc = UMLApp::app()->getDocument();
    UMLFolder *logicalView = umldoc->getRootFolder(Uml::mt_Logical);

    // write generic includes
    cs << "using System;" << m_endl;
    cs << "using System.Text;" << m_endl;
    cs << "using System.Collections;" << m_endl;
    cs << "using System.Collections.Generic;" << m_endl << m_endl;

    //write includes and namespace

    UMLPackage *container = c->getUMLPackage();
    if (container == logicalView)
        container = NULL;

    UMLPackageList includes;
    findObjectsRelated(c, includes);
    m_seenIncludes.clear();
    //m_seenIncludes.append(logicalView);
    if (includes.count()) {
        UMLPackage *p;
        for (UMLPackageListIt it(includes); (p = it.current()) != NULL; ++it) {
            UMLClassifier *cl = dynamic_cast<UMLClassifier*>(p);
            if (cl)
                p = cl->getUMLPackage();
            if (p != logicalView && m_seenIncludes.findRef(p) == -1 && p != container) {
                cs << "using " << p->getFullyQualifiedName(".") << ";" << m_endl;
                m_seenIncludes.append(p);
            }
        }
        cs << m_endl;
    }

    m_container_indent = "";

    if (container) {
        cs << "namespace " << container->getFullyQualifiedName(".") << m_endl;
        cs << "{" << m_endl << m_endl;
        m_container_indent = m_indentation;
        m_seenIncludes.append(container);
    }

    //Write class Documentation if there is somthing or if force option
    if (forceDoc() || !c->getDoc().isEmpty()) {
        cs << m_container_indent << "/// <summary>" << m_endl;
        cs << formatDoc(c->getDoc(), m_container_indent + "/// " );
        cs << m_container_indent << "/// </summary>" << m_endl ;
    }

    UMLClassifierList superclasses = c->getSuperClasses();
    UMLAssociationList aggregations = c->getAggregations();
    UMLAssociationList compositions = c->getCompositions();
    UMLAssociationList realizations = c->getRealizations();
    bool isInterface = c->isInterface();
    m_unnamedRoles = 1;

    cs << m_container_indent << "public ";

    //check if it is an interface or regular class
    if (isInterface) {
        cs << "interface " << classname;
    } else {
        //check if class is abstract and / or has abstract methods
        if (c->getAbstract() || c->hasAbstractOps())
            cs << "abstract ";

        cs << "class " << classname << (superclasses.count() > 0 ? " : ":"");

        // write baseclass, ignore interfaces, write error on multiple inheritance
        if (superclasses.count() > 0) {
            UMLClassifier *obj;
            int supers = 0;
            for (obj = superclasses.first(); obj; obj = superclasses.next()) {
                if (!obj->isInterface()) {
                    if (supers > 0) {
                        cs << " // AND ";
                    }
                    cs << cleanName(obj->getName());
                    supers++;
                }
            }
            if (supers > 1) {
                cs << m_endl << "//WARNING: C# does not support multiple inheritance but there is more than 1 superclass defined in your UML model!" << m_endl;
        }
        }
        //check for realizations
        UMLAssociationList realizations = c->getRealizations();
        UMLAssociation *a;

        if (!realizations.isEmpty()) {
            for (a = realizations.first(); a; a = realizations.next()) {
                UMLClassifier *real = (UMLClassifier*)a->getObject(Uml::B);
                if(real != c) {
                    // write list of realizations
                    cs << ", " << real->getName();
                }

            }
        }
    }
    cs << m_endl << m_container_indent << '{' << m_endl;

    //associations
    if (forceSections() || !aggregations.isEmpty()) {
        cs << m_endl << m_container_indent << m_indentation << "#region Aggregations" << m_endl << m_endl;
        writeAssociatedAttributes(aggregations, c, cs);
        cs << m_endl << m_container_indent << m_indentation << "#endregion" << m_endl;
    }

    //compositions
    if (forceSections() || !compositions.isEmpty()) {
        cs << m_endl << m_container_indent << m_indentation << "#region Compositions" << m_endl << m_endl;
        writeAssociatedAttributes(compositions, c, cs);
        cs << m_endl << m_container_indent << m_indentation << "#endregion" << m_endl;
    }

    //attributes
    // FIXME: C# allows Properties in interface!
    if (!isInterface)
        writeAttributes(c, cs);

    //operations
    writeOperations(c, cs);

    //finish file
    cs << m_endl << m_container_indent << "}" << m_endl << m_endl; // close class

    if (container) {
        cs << "}  // end of namespace "
            << container->getFullyQualifiedName(".") << m_endl << m_endl;
    }

    //close files and notfiy we are done
    filecs.close();
    emit codeGenerated(c, true);
}
Esempio n. 21
0
bool RC2UI::makeDialog()
{
    line = in->readLine();
    do {
        QFile fileOut;
	QString buffer;
	int count;
	QCString className;
	uint x, y, w, h;
	uint endDesc;
	bool space = FALSE;
	for ( endDesc = 0; endDesc < line.length() ; endDesc++ ) {
	    char c = (QChar)line.at(endDesc);
	    if ( space && (c >= '0') && (c <= '9') )
		break;
	    space = c==' ';
	}
	
	QString desc = line.left(endDesc-1);
	line = line.right( line.length() - endDesc );

	className = parseNext( desc, ' ' );

 	count = sscanf( line, "%d, %d, %d, %d", &x, &y, &w, &h );
	
	if ( !count && count == EOF )
	    return FALSE;

	char property[256];
	QStringList styles;
	QStringList extendedStyles;
	QString caption = "";
	QString baseClass = "";
	QString widgetType;
	QString widgetName;
	QString arguments;
	int pointsize;
	QString fontname;
	do {
	    if ( in->eof() )
		return TRUE;
	    line = "";
	    do {
		line += in->readLine();
	    } while ( line[(int)line.length()-1] == '|' || 
		      line[(int)line.length()-1] == ',' );
	    count = sscanf( line, "%s", property );
	    line = line.right( line.length() - line.find(" ") -1 );
	    if ( QString(property) == "STYLE" ) {
		styles = splitStyles(line);
		if ( styles.contains( "WS_CAPTION" ) )
		    baseClass = "QDialog";
		else
		    baseClass = "QWidget";
	    } else if ( QString(property) == "CAPTION" ) {
		caption = stripQM( line );
	    } else if ( QString(property) == "FONT" ) {
		QString pt = line.left( line.find(",") );
		pointsize = pt.toInt();
		fontname = stripQM(line.right( line.length() - line.find(",") - 2 ));
	    }
	} while ( line != "BEGIN" );

	if ( writeToFile ) {
	    
	    QString outputFile = QString(className) + ".ui";
	    fileOut.setName( outputFile );
	    if (!fileOut.open( IO_WriteOnly ) )
		qFatal( "rc2ui: Could not open output file '%s'", outputFile.latin1() );
	    out = new QTextStream( &fileOut );

	} else {
	    out = new QTextStream( &buffer, IO_WriteOnly );
	}

	*out << "<!DOCTYPE UI><UI>" << endl;
	writeClass( className );
	wi(); *out << "<widget>"<< endl; indent();
	writeClass( baseClass );
	writeCString( "name", className );
	writeRect( "geometry", x, y, w, h );
	writeString( "caption", caption );
	writeFont( fontname, pointsize );

	do {
	    line = in->readLine().stripWhiteSpace();
	    if ( line == "END" )
		continue;

	    widgetType = parseNext(line, ' ');
	    arguments = line.stripWhiteSpace();
	    while ( arguments[(int)arguments.length()-1] == ',' || 
		    arguments[(int)arguments.length()-1] == '|'  )
		arguments += " "+in->readLine().stripWhiteSpace();

	    wi(); *out << "<widget>" << endl; indent();

	    WidgetType ID = IDUnknown;
	    QString controlType;
	    QString widgetID;
	    QString widgetText;
	    bool hasText = FALSE;
	    bool isControl = FALSE;
	    bool isFrame = FALSE;

	    if ( widgetType == "PUSHBUTTON" ) {
		ID = IDPushButton;
		hasText = TRUE;
	    } else if ( widgetType == "DEFPUSHBUTTON" ) {
		ID = IDPushButton;
		hasText = TRUE;
	    } else if ( widgetType == "LTEXT" ) {
		ID = IDLabel;
		hasText = TRUE;
	    } else if ( widgetType == "CTEXT" ) {
		ID = IDLabel;
		hasText = TRUE;
	    } else if ( widgetType == "RTEXT" ) {
		ID = IDLabel;
		hasText = TRUE;
	    } else if ( widgetType == "EDITTEXT" ) {
		ID = IDLineEdit;
	    } else if ( widgetType == "GROUPBOX" ) {
		ID = IDGroupBox;
		hasText = TRUE;
	    } else if ( widgetType == "COMBOBOX" ) {
		ID = IDComboBox;
	    } else if ( widgetType == "LISTBOX" ) {
		ID = IDListBox;
	    } else if ( widgetType == "SCROLLBAR" ) {
		ID = IDScrollBar;
	    } else if ( widgetType == "CHECKBOX" ) {
		ID = IDCheckBox;
		hasText = TRUE;
	    } else if ( widgetType == "RADIOBUTTON" ) {
		ID = IDRadioButton;
		hasText = TRUE;
	    } else if ( widgetType == "CONTROL" ) {
		isControl = TRUE;
		widgetText = stripQM(parseNext( arguments ));
		widgetID = parseNext( arguments );
		controlType = stripQM(parseNext( arguments ));
		styles = splitStyles(parseNext( arguments ));
		
		if ( controlType == "Static" ) {
		    ID = IDLabel;
		} else if ( controlType == "Button" ) {
		    if ( styles.contains("BS_AUTOCHECKBOX") ||
			 styles.contains("BS_3STATE") )
			ID = IDCheckBox;
		    else if ( styles.contains("BS_AUTORADIOBUTTON") )
			ID = IDRadioButton;
		} else if ( controlType == "msctls_updown32" ) {
		    ID = IDSpinBox;
		} else if ( controlType == "msctls_progress32" ) {
		    ID = IDProgressBar;
		} else if ( controlType == "msctls_trackbar32" ) {
		    ID = IDSlider;
		} else if ( controlType == "SysListView32" ) {
		    ID = IDIconView;
		} else if ( controlType == "SysTreeView32" ) {
		    ID = IDListView;
		} else if ( controlType == "SysTabControl32" ) {
		    ID = IDTabWidget;
		} else if ( controlType == "SysAnimate32" ) {
		    ID = IDLabel;
		} else if ( controlType == "RICHEDIT" ) {
		    ID = IDMultiLineEdit;
		} else if ( controlType == "ComboBoxEx32" ) {
		    ID = IDComboBox;
		} else if ( controlType == "" ) {
		    ID = IDCustom;
		} else {
		    ID = IDUnknown;
		}
	    } else
		ID = IDUnknown;

	    if ( hasText )
		widgetText = stripQM(parseNext( arguments ));

	    if ( isControl ) {
		x = parseNext( arguments ).toInt();
		y = parseNext( arguments ).toInt();
		w = parseNext( arguments ).toInt();
		h = parseNext( arguments ).toInt();
	    } else {
		widgetID = parseNext( arguments );
		x = parseNext( arguments ).toInt();
		y = parseNext( arguments ).toInt();
		w = parseNext( arguments ).toInt();
		h = parseNext( arguments ).toInt();
		styles.clear();
	    }

	    do {
		extendedStyles = splitStyles(parseNext( arguments ));
		for ( uint i = 0; i < extendedStyles.count(); i++ )
		    styles << (*extendedStyles.at(i));
	    } while ( arguments.find(',') > -1 );

	    switch ( ID ) {
	    case IDWidget:
		break;
	    case IDPushButton: 
		{
		    writeClass("QPushButton");
		    writeCString( "name", useName("PushButton_"+widgetID) );
		    writeRect( "geometry", x, y, w, h );
		    writeString( "text", widgetText );
		    if ( widgetType == "DEFPUSHBUTTON" )
			writeBool( "default", TRUE );
		}
		break;
	    case IDLabel:
		{
		    isFrame = TRUE,
		    writeClass("QLabel");
		    writeCString( "name", useName("Label_"+widgetID) );
		    writeRect( "geometry", x,y,w,h );
		    writeString( "text", widgetText );
		    QString align;
		    if ( !styles.contains("SS_CENTERIMAGE") )
			align += "|AlignTop";
		    else
			align += "|AlignVCenter";
		    if ( widgetType == "LTEXT" ) {
			align += "|AlignLeft";
		    } else if ( widgetType == "CTEXT") {
			align += "|AlignHCenter";
		    } else if ( widgetType == "RTEXT") {
			align += "|AlignRight";
		    }
		    writeSet("alignment", align );
		}
		break;
	    case IDCheckBox:
		{
		    writeClass("QCheckBox");
		    writeCString("name", useName("CheckBox_"+widgetID) );
		    writeRect("geometry", x,y,w,h);
		    writeString("text", widgetText );
		    if ( styles.contains( "BS_3STATE" ) )
			writeBool( "tristate", TRUE );
		}
		break;
	    case IDRadioButton:
		{
		    writeClass("QRadioButton");
		    writeCString("name", useName("RadioButton_"+widgetID) );
		    writeRect("geometry", x,y,w,h);
		    writeString("text", widgetText );
		}
		break;
	    case IDGroupBox:
		{
		    isFrame = TRUE;
		    writeClass("QGroupBox");
		    writeCString( "name", useName("GroupBox_"+widgetID) );
		    writeRect( "geometry", x,y,w,h );
		    writeString( "title", widgetText );
		    if ( !styles.contains( "WS_BORDER" ) )
			styles.append( "WS_BORDER" );
		}
		break;
	    case IDLineEdit:
		{
		    if ( !styles.contains("ES_MULTILINE") ) {
			writeClass("QLineEdit");
			writeCString( "name", useName("LineEdit_"+widgetID) );
		    } else {
			writeClass("QMultiLineEdit");
			writeCString( "name", useName("MultiLineEdit_"+widgetID) );
		    }
		    writeRect( "geometry", x,y,w,h );
		    QString align = "AlignTop";
		    if ( styles.contains("ES_CENTER") )
			align+="|AlignHCenter";
		    else if ( styles.contains("ES_RIGHT") )
			align+="|AlignRight";
		    else
			align+="|AlignLeft";
		    writeSet("alignment", align);
		}
		break;
	    case IDMultiLineEdit:
		{
		    writeClass("QMultiLineEdit");
		    writeCString("name", useName("MultiLineEdit_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		}
		break;
	    case IDIconView:
		{
		    isFrame = TRUE;
		    writeClass("QIconView");
		    writeCString("name", useName("IconView_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		    if ( !styles.contains( "LVS_SINGLESEL" ) )
			writeEnum( "selectionMode", "Extended" );
		    if ( styles.contains( "LVS_NOLABELWRAP" ) )
			writeBool("wordWrapIconText", FALSE );
		}
		break;
	    case IDListView:
		{
		    isFrame = TRUE;
		    writeClass("QListView");
		    writeCString("name", useName("ListView_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		    if ( styles.contains( "TVS_LINESATROOT" ) )
			writeBool( "rootIsDecorated", TRUE );
		    if ( styles.contains( "TVS_FULLROWSELECT" ) )
			writeBool( "allColumnsShowFocus", TRUE );
		}
		break;
	    case IDProgressBar:
		{
		    isFrame = TRUE;
		    writeClass("QProgressBar");
		    writeCString("name", useName("ProgressBar_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		    if ( styles.contains("TBS_VERT") )
			writeEnum("orientation", "Vertical");
		    else
			writeEnum("orientation", "Horizontal");
		}
		break;
	    case IDTabWidget:
		{
		    writeClass("QTabWidget");
		    writeCString("name", useName("TabWidget_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		    wi(); *out << "<widget>" << endl; indent();
		    writeClass("QWidget");
		    wi(); *out << "<attribute>" << endl; indent();
		    wi(); *out << "<name>title</name>" << endl;
		    wi(); *out << "<string>Tab1</string>" << endl; undent();
		    wi(); *out << "</attribute>" << endl; undent();
		    wi(); *out << "</widget>" << endl;
		}
		break;
	    case IDSpinBox:
		{
		    isFrame = TRUE;
		    writeClass("QSpinBox");
		    writeCString("name", useName("SpinBox_"+widgetID) );
		    writeRect("geometry", x,y,w,h);
		}
		break;
	    case IDSlider:
		{
		    writeClass("QSlider");
		    writeCString("name", useName("Slider_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		    if ( styles.contains("TBS_VERT") )
			writeEnum("orientation", "Vertical");
		    else
			writeEnum("orientation", "Horizontal");
		    if ( !styles.contains("TBS_NOTICKS") )
			writeEnum("tickmarks", "Left" );
		}
		break;
	    case IDComboBox:
		{
		    writeClass("QComboBox");
		    writeCString("name", useName("ComboBox_"+widgetID) );
		    if ( isControl )
			writeRect( "geometry", x,y,w,14 );
		    else 
			writeRect( "geometry", x,y,w,h );
		}
		break;
	    case IDListBox:
		{
		    isFrame = TRUE;
		    writeClass("QListBox");
		    writeCString("name", useName("ListBox_"+widgetID) );
		    writeRect( "geometry", x,y,w,h );
		    if ( styles.contains("WS_HSCROLL") )
			writeEnum("hScrollBarMode", "Auto");
		    else
			writeEnum("hScrollBarMode", "AlwaysOff");
		    if ( styles.contains("WS_VSCROLL") )
			writeEnum("vScrollBarMode", "Auto");
		    else
			writeEnum("vScrollBarMode", "AlwaysOff");
		    if ( styles.contains("LBS_EXTENDEDSEL") )
			writeEnum("selectionMode", "Extended");
		    else if ( styles.contains("LBS_MULTIPLESEL") )
			writeEnum("selectionMode", "Multi");
		    else if ( styles.contains("LBS_NOSEL") )
			writeEnum("selectionMode", "NoSelection");
		    else 
			writeEnum("selectionMode", "Single");
		    if ( !styles.contains( "NO WS_BORDER" ) )
			styles.append( "WS_BORDER" );
		}
		break;
	    case IDScrollBar:
		{
		    writeClass("QScrollBar");
		    writeCString("name", useName("ScrollBar_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		    if ( styles.contains("SBS_VERT") )
			writeEnum("orientation", "Vertical");
		    else
			writeEnum("orientation", "Horizontal");
		}
		break;
	    case IDCustom:
		{
		    writeClass("QLabel");
		    writeCString("name", useName("Custom_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		    writeString("text", "Create a custom widget and place it here." );
		}
	    default:
		{
		    writeClass("QLabel");
		    writeCString("name", useName("Unknown_"+widgetID) );
		    writeRect("geometry", x,y,w,h );
		    writeString("text", QString("No support for %1.").arg(controlType) );
		}
		break;
	    }

	    writeStyles( styles, isFrame );

	    styles.clear();

	    undent();
	    wi(); *out << "</widget>" << endl;
	} while ( line != "END" );

	undent();
	wi(); *out << "</widget>" << endl;
	*out << "</UI>" << endl;

	do {
	    line = in->readLine();
	} while ( line.isEmpty() );

	if ( !writeToFile )
	    target.append( buffer.copy() );

	if (out) {
	    delete out;
	    out = 0;
	}
	fileOut.close();

	if ( writeToFile )
	    printf( QDir::currentDirPath() + "/" + fileOut.name() + '\n' );

    } while ( line != blockStart1 );

    return TRUE;
}
Esempio n. 22
0
void JSWriter::writeClass(UMLClassifier *c)
{
    if(!c)
    {
        kDebug()<<"Cannot write class of NULL concept!" << endl;
        return;
    }

    QString classname = cleanName(c->getName());
    QString fileName = c->getName().lower();

    //find an appropriate name for our file
    fileName = findFileName(c,".js");
    if (fileName.isEmpty())
    {
        emit codeGenerated(c, false);
        return;
    }

    QFile filejs;
    if(!openFile(filejs, fileName))
    {
        emit codeGenerated(c, false);
        return;
    }
    QTextStream js(&filejs);

    //////////////////////////////
    //Start generating the code!!
    /////////////////////////////


    //try to find a heading file (license, coments, etc)
    QString str;
    str = getHeadingFile(".js");
    if(!str.isEmpty())
    {
        str.replace(QRegExp("%filename%"),fileName);
        str.replace(QRegExp("%filepath%"),filejs.name());
        js << str << m_endl;
    }


    //write includes
    UMLPackageList includes;
    findObjectsRelated(c,includes);
    for (UMLPackage *conc = includes.first(); conc; conc = includes.next())
    {
        QString headerName = findFileName(conc, ".js");
        if ( !headerName.isEmpty() )
        {
            js << "#include \"" << headerName << "\"" << m_endl;
        }
    }
    js << m_endl;

    //Write class Documentation if there is somthing or if force option
    if(forceDoc() || !c->getDoc().isEmpty())
    {
        js << m_endl << "/**" << m_endl;
        js << "  * class " << classname << m_endl;
        js << formatDoc(c->getDoc(),"  * ");
        js << "  */" << m_endl << m_endl;
    }


    //check if class is abstract and / or has abstract methods
    if(c->getAbstract() && !hasAbstractOps(c))
        js << "/******************************* Abstract Class ****************************" << m_endl << "  "
        << classname << " does not have any pure virtual methods, but its author" << m_endl
        << "  defined it as an abstract class, so you should not use it directly." << m_endl
        << "  Inherit from it instead and create only objects from the derived classes" << m_endl
        << "*****************************************************************************/" << m_endl << m_endl;

    js << classname << " = function ()" << m_endl;
    js << "{" << m_endl;
    js << m_indentation << "this._init ();" << m_endl;
    js << "}" << m_endl;
    js << m_endl;

    UMLClassifierList superclasses = c->getSuperClasses();
    for (UMLClassifier *obj = superclasses.first();
            obj; obj = superclasses.next()) {
        js << classname << ".prototype = new " << cleanName(obj->getName()) << " ();" << m_endl;
    }

    js << m_endl;

    if (! c->isInterface()) {
        UMLAttributeList atl = c->getAttributeList();

        js << "/**" << m_endl;
        QString temp = "_init sets all " + classname + " attributes to their default value."
                       " Make sure to call this method within your class constructor";
        js << formatDoc(temp, " * ");
        js << " */" << m_endl;
        js << classname << ".prototype._init = function ()" << m_endl;
        js << "{" << m_endl;
        for(UMLAttribute *at = atl.first(); at ; at = atl.next())
        {
            if (forceDoc() || !at->getDoc().isEmpty())
            {
                js << m_indentation << "/**" << m_endl
                << formatDoc(at->getDoc(), m_indentation + " * ")
                << m_indentation << " */" << m_endl;
            }
            if(!at->getInitialValue().isEmpty())
            {
                js << m_indentation << "this.m_" << cleanName(at->getName()) << " = " << at->getInitialValue() << ";" << m_endl;
            }
            else
            {
                js << m_indentation << "this.m_" << cleanName(at->getName()) << " = \"\";" << m_endl;
            }
        }
    }

    //associations
    UMLAssociationList aggregations = c->getAggregations();
    if (forceSections() || !aggregations.isEmpty ())
    {
        js << m_endl << m_indentation << "/**Aggregations: */" << m_endl;
        writeAssociation(classname, aggregations , js );

    }
    UMLAssociationList compositions = c->getCompositions();
    if( forceSections() || !compositions.isEmpty())
    {
        js << m_endl << m_indentation << "/**Compositions: */" << m_endl;
        writeAssociation(classname, compositions , js );

    }
    js << m_endl;
    js << "}" << m_endl;
    js << m_endl;

    //operations
    UMLOperationList ops(c->getOpList());
    writeOperations(classname, &ops, js);

    js << m_endl;

    //finish file

    //close files and notfiy we are done
    filejs.close();
    emit codeGenerated(c, true);
}
Esempio n. 23
0
void SQLWriter::writeClass(UMLClassifier *c) {

    if(!c) {
        kDebug()<<"Cannot write class of NULL concept!" << endl;
        return;
    }

    const bool isClass = !c->isInterface();
    QString classname = cleanName(c->getName());

    //find an appropriate name for our file
    QString fileName = findFileName(c, ".sql");
    if (fileName.isEmpty()) {
        emit codeGenerated(c, false);
        return;
    }

    QFile file;
    if( !openFile(file, fileName) ) {
        emit codeGenerated(c, false);
        return;
    }

    //Start generating the code!!

    QTextStream sql(&file);
    //try to find a heading file (license, coments, etc)
    QString str;
    str = getHeadingFile(".sql");
    if(!str.isEmpty()) {
        str.replace(QRegExp("%filename%"),fileName);
        str.replace(QRegExp("%filepath%"),file.name());
        sql<<str<<m_endl;
    }

    //Write class Documentation if there is somthing or if force option
    if(forceDoc() || !c->getDoc().isEmpty()) {
        sql << m_endl << "--" << m_endl;
        sql<<"-- TABLE: "<<classname<<m_endl;
        sql<<formatDoc(c->getDoc(),"-- ");
        sql << "--  " << m_endl << m_endl;
    }

    sql << "CREATE TABLE "<< classname << " ( " << m_endl;

    if (isClass)
        writeAttributes(c, sql);

    sql << m_endl << ");" << m_endl;

    QMap<UMLAssociation*,UMLAssociation*> constraintMap; // so we don't repeat constraint
    UMLAssociationList aggregations = c->getAggregations();
    if( forceSections() || !aggregations.isEmpty() ) {
        for(UMLAssociation* a = aggregations.first(); a; a = aggregations.next()) {
            UMLObject *objA = a->getObject(Uml::A);
            UMLObject *objB = a->getObject(Uml::B);
            if (objA->getID() == c->getID() && objB->getID() != c->getID())
                continue;
            constraintMap[a] = a;
        }
    }

    QMap<UMLAssociation*,UMLAssociation*>::Iterator itor = constraintMap.begin();
    for (;itor != constraintMap.end();itor++) {
        UMLAssociation* a = itor.data();
        sql << "ALTER TABLE "<< classname
            << " ADD CONSTRAINT " << a->getName() << " FOREIGN KEY ("
            << a->getRoleName(Uml::B) << ") REFERENCES "
            << a->getObject(Uml::A)->getName()
            << " (" << a->getRoleName(Uml::A) << ");" << m_endl;
    }


    file.close();
    emit codeGenerated(c, true);
}
Esempio n. 24
0
/*!
 * \brief SimMessage::startSimulator simulates the document in view.
 */
void SimMessage::startSimulator()
{
  // Using the Doc pointer here is risky as the user may have closed
  // the schematic, but converting the SPICE netlists is (hopefully)
  // faster than the user (I have no other idea).

  QString SimTime;
  QString Program;
  QStringList Arguments;
  QString SimPath = QDir::convertSeparators (QucsSettings.QucsHomeDir.absPath());
#ifdef __MINGW32__
  QString QucsDigiLib = "qucsdigilib.bat";
  QString QucsDigi = "qucsdigi.bat";
  QString QucsVeri = "qucsveri.bat";
#else
  QString QucsDigiLib = "qucsdigilib";
  QString QucsDigi = "qucsdigi";
  QString QucsVeri = "qucsveri";
#endif
  SimOpt = NULL;
  bool isVerilog = false;

  // Simulate text window.
  if(DocWidget->inherits("QTextEdit")) {

    TextDoc * Doc = (TextDoc*)DocWidget;

    // Take VHDL file in memory as it could contain unsaved changes.
    Stream << Doc->toPlainText();
    NetlistFile.close();
    ProgText->insert(tr("done.")+"\n");  // of "creating netlist...

    // Simulation.
    if (Doc->simulation) {
      SimTime = Doc->SimTime;
      QString libs = Doc->Libraries.lower();
      /// \todo \bug error: unrecognized command line option '-Wl'
#ifdef __MINGW32__
      if(libs.isEmpty()) {
        libs = "";
      }
      else {
        libs.replace(" ",",-l");
        libs = "-Wl,-l" + libs;
      }
#else
      if(libs.isEmpty()) {
        libs = "-c";
      }
      else {
        libs.replace(" ",",-l");
        libs = "-c,-l" + libs;
      }
#endif
      Program = pathName(QucsSettings.BinDir + QucsDigi);
      Arguments  << QucsSettings.QucsHomeDir.filePath("netlist.txt")
                 << DataSet << SimTime << pathName(SimPath)
                 << pathName(QucsSettings.BinDir) << libs;
    }
    // Module.
    else {
      QString text = Doc->toPlainText();
      VHDL_File_Info VInfo (text);
      QString entity = VInfo.EntityName.lower();
      QString lib = Doc->Library.lower();
      if (lib.isEmpty()) lib = "work";
      QString dir = QDir::convertSeparators (QucsSettings.QucsHomeDir.path());
      QDir vhdlDir(dir);
      if(!vhdlDir.exists("vhdl"))
	if(!vhdlDir.mkdir("vhdl")) {
	  ErrText->insert(tr("ERROR: Cannot create VHDL directory \"%1\"!")
			  .arg(vhdlDir.path()+"/vhdl"));
	  return;
	}
      vhdlDir.setPath(vhdlDir.path()+"/vhdl");
      if(!vhdlDir.exists(lib))
	if(!vhdlDir.mkdir(lib)) {
	  ErrText->insert(tr("ERROR: Cannot create VHDL directory \"%1\"!")
			  .arg(vhdlDir.path()+"/"+lib));
	  return;
	}
      vhdlDir.setPath(vhdlDir.path()+"/"+lib);
      QFile destFile;
      destFile.setName(vhdlDir.filePath(entity+".vhdl"));
      if(!destFile.open(QIODevice::WriteOnly)) {
	ErrText->insert(tr("ERROR: Cannot create \"%1\"!")
			.arg(destFile.name()));
	return;
      }
      destFile.writeBlock(text.ascii(), text.length());
      destFile.close();
      Program = pathName(QucsSettings.BinDir + QucsDigiLib);
      Arguments << QucsSettings.QucsHomeDir.filePath("netlist.txt")
                << pathName(SimPath)
                << entity
                << lib;
    }
  }
  // Simulate schematic window.
  else {
    // output NodeSets, SPICE simulations etc.
    for(QStringList::Iterator it = Collect.begin();
	it != Collect.end(); ++it) {
      // don't put library includes into netlist...
      if ((*it).right(4) != ".lst" &&
	  (*it).right(5) != ".vhdl" &&
	  (*it).right(4) != ".vhd" &&
	  (*it).right(2) != ".v") {
	Stream << *it << '\n';
      }
    }
    Stream << '\n';

    isVerilog = ((Schematic*)DocWidget)->isVerilog;
    SimTime = ((Schematic*)DocWidget)->createNetlist(Stream, SimPorts);
    if(SimTime.length()>0&&SimTime.at(0) == '\xA7') {
      NetlistFile.close();
      ErrText->insert(SimTime.mid(1));
      FinishSimulation(-1);
      return;
    }
    if (isVerilog) {
      Stream << "\n"
	     << "  initial begin\n"
	     << "    $dumpfile(\"digi.vcd\");\n"
	     << "    $dumpvars();\n"
	     << "    #" << SimTime << " $finish;\n"
	     << "  end\n\n"
	     << "endmodule // TestBench\n";
    }
    NetlistFile.close();
    ProgText->insert(tr("done.")+"\n");  // of "creating netlist...

    if(SimPorts < 0) {

      // append command arguments
      // append netlist with same arguments
      if (! Module::vaComponents.isEmpty()) {

          /*! Only pass modules to Qucsator that are indeed used on
           * the schematic,it might be the case that the user loaded the icons,
           * but did not compiled the module. Qucsator will not find the library.
           *
           * Check if used symbols have corresponing lib before running
           * Qucsator? Need to search on the netlis.txt? Is there other data
           * structure containig the netlist?
           *
          */
          QStringList usedComponents;

          if (!NetlistFile.open(QIODevice::ReadOnly))
             QMessageBox::critical(this, tr("Error"), tr("Cannot read netlist!"));
          else {
             QString net = QString(NetlistFile.readAll());

             QMapIterator<QString, QString> i(Module::vaComponents);
             while (i.hasNext()) {
                 i.next();
                 if (net.contains(i.key()))
                     usedComponents << i.key();
             }
             NetlistFile.close();
          }

          if (! usedComponents.isEmpty()) {


            // \todo remvoe the command line arguments? use only netlist annotation?
            //Arguments << "-p" << QucsSettings.QucsWorkDir.absolutePath()
            //          << "-m" << usedComponents;
            //qDebug() << "Command :" << Program << Arguments.join(" ");

            /// Anotate netlist with Verilog-A dynamic path and module names
            ///
            if (!NetlistFile.open(QFile::Append | QFile::Text))
               QMessageBox::critical(this, tr("Error"), tr("Cannot read netlist!"));
            else {
               QTextStream out(&NetlistFile);
               out << "\n";
               out << "# --path=" << QucsSettings.QucsWorkDir.absolutePath() << "\n";
               out << "# --module=" << usedComponents.join(" ") << "\n";

               NetlistFile.close();
            }
          }
      } // vaComponents not empty

      if((SimOpt = findOptimization((Schematic*)DocWidget))) {
	    ((Optimize_Sim*)SimOpt)->createASCOnetlist();

        Program = QucsSettings.AscoBinDir.canonicalPath();
        Program = QDir::toNativeSeparators(Program+"/"+"asco"+QString(executableSuffix));
        Arguments << "-qucs" << QucsSettings.QucsHomeDir.filePath("asco_netlist.txt")
                  << "-o" << "asco_out";
      }
      else {
        Program = QucsSettings.BinDir + "qucsator" + executableSuffix;
        Arguments << "-b" << "-g" << "-i"
                  << QucsSettings.QucsHomeDir.filePath("netlist.txt")
                  << "-o" << DataSet;
      }
    }
    else {
      if (isVerilog) {
          Program = QDir::toNativeSeparators(QucsSettings.BinDir + QucsVeri);
          Arguments << QDir::toNativeSeparators(QucsSettings.QucsHomeDir.filePath("netlist.txt"))
                    << DataSet
                    << SimTime
                    << QDir::toNativeSeparators(SimPath)
                    << QDir::toNativeSeparators(QucsSettings.BinDir)
                    << "-c";
      } else {
/// \todo \bug error: unrecognized command line option '-Wl'
#ifdef __MINGW32__
    Program = QDir::toNativeSeparators(pathName(QucsSettings.BinDir + QucsDigi));
    Arguments << QDir::toNativeSeparators(QucsSettings.QucsHomeDir.filePath("netlist.txt"))
              << DataSet
              << SimTime
              << QDir::toNativeSeparators(SimPath)
              << QDir::toNativeSeparators(QucsSettings.BinDir) << "-Wall" << "-c";
#else
    Program = QDir::toNativeSeparators(pathName(QucsSettings.BinDir + QucsDigi));
    Arguments << QucsSettings.QucsHomeDir.filePath("netlist.txt")
              << DataSet << SimTime << pathName(SimPath)
		      << pathName(QucsSettings.BinDir) << "-Wall" << "-c";

#endif
      }
    }
  }

  disconnect(&SimProcess, 0, 0, 0);
  connect(&SimProcess, SIGNAL(readyReadStandardError()), SLOT(slotDisplayErr()));
  connect(&SimProcess, SIGNAL(readyReadStandardOutput()), SLOT(slotDisplayMsg()));
  connect(&SimProcess, SIGNAL(finished(int)), SLOT(slotSimEnded(int)));

#ifdef SPEEDUP_PROGRESSBAR
  waitForUpdate = false;
#endif
  wasLF = false;

  ProgressText = "";

#ifdef __MINGW32__
  QString sep(";"); // path separator
#else
  QString sep(":");
#endif

  // append process PATH
  QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
  // insert Qucs bin dir, so ASCO can find qucsator
  env.insert("PATH", env.value("PATH") + sep + QucsSettings.BinDir );
  SimProcess.setProcessEnvironment(env);
  QFile file(Program);
  if ( !file.exists() ){
    ErrText->insert(tr("ERROR: Program not found: %1").arg(Program));
    FinishSimulation(-1);
    return;
  }
  else
    file.close();

  qDebug() << "Command :" << Program << Arguments.join(" ");
  SimProcess.start(Program, Arguments); // launch the program

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

}
Esempio n. 25
0
QValueVector<QColor> amaroK::readMood(const QString path)
{
	debug() << "MakeMood: Reading mood file " << path << endl;
	QString filebase = path;
	QValueVector<QColor> theArray;
	filebase.truncate(filebase.findRev('.'));
	filebase += ".mood";
	QString dotfilebase = filebase, homefilebase = filebase;
	dotfilebase.insert(filebase.findRev('/') + 1, '.');
	homefilebase.replace('/', ',');
	homefilebase = ::locateLocal("data", "amarok/moods/" + homefilebase);
	QFile mood;
	if(QFile::exists(filebase)) mood.setName(filebase);
	if(QFile::exists(dotfilebase)) mood.setName(dotfilebase);
	if(QFile::exists(homefilebase)) mood.setName(homefilebase);
	if(mood.name() != "" && mood.open(IO_ReadOnly))
	{
		int r, g, b, s = mood.size() / 3;
		debug() << "ReadMood: File opened. Proceeding to read contents... s=" << s << endl;
		QMemArray<int> huedist(360);
		int total = 0, mx = 0;
		for(int i = 0; i < 360; i++) huedist[i] = 0;
		theArray.resize(s);
		for(int i = 0; i < s; i++)
		{
			r = mood.getch();
			g = mood.getch();
			b = mood.getch();
			theArray[i] = QColor(CLAMP(0, r, 255), CLAMP(0, g, 255), CLAMP(0, b, 255), QColor::Rgb);
			int h, s, v;
			theArray[i].getHsv(&h, &s, &v);
			if(h < 0) h = 0; else h = h % 360;
			huedist[h]++;
			if(mx < huedist[h]) mx = huedist[h];
		}
		debug() << "ReadMood: File read. Maximum hue bin size = " <<  mx << endl;
		if(AmarokConfig::makeMoodier())
		{
			debug() << "ReadMood: Making moodier!" << endl;
			int threshold, rangeStart = 0, rangeDelta = 359, sat = 100, val = 100;
			switch(AmarokConfig::alterMood())
			{
				// Angry
				case 1: threshold = s / 360 * 9; rangeStart = 45; rangeDelta = -45; sat = 200; val = 100; break;
				// Frozen
				case 2: threshold = s / 360 * 1; rangeStart = 140; rangeDelta = 160; sat = 50; val = 100; break;
				// Happy
				default: threshold = s / 360 * 2; rangeStart = 0; rangeDelta = 359; sat = 150; val = 250;
			}
			debug() << "ReadMood: Appling filter t=" << threshold << ", rS=" << rangeStart << ", rD=" << rangeDelta << ", s=" << sat << "%, v=" << val << "%" << endl;
			for(int i = 0; i < 360; i++) if(huedist[i] > threshold) total++;
			debug() << "ReadMood: Total=" << total << endl;
			if(total < 360 && total > 0)
			{
				for(int i = 0, n = 0; i < 360; i++)
					huedist[i] = ((huedist[i] > threshold ? n++ : n) * rangeDelta / total + rangeStart) % 360;
				for(uint i = 0; i < theArray.size(); i++)
				{	int h, s, v;
					theArray[i].getHsv(&h, &s, &v);
					if(h < 0) h = 0; else h = h % 360;
					if(h > 359) debug() << "ReadMood: Bad hue in array[" << i << "]: " << h << endl;
					theArray[i].setHsv(CLAMP(0, huedist[h], 359), CLAMP(0, s * sat / 100, 255), CLAMP(0, v * val / 100, 255));
				}
			}
		}
	}
	debug() << "ReadMood: All done." << endl;
	return theArray;
}
Esempio n. 26
0
void testCodec (const char* msg, Codec type, bool isFile)
{
    QByteArray output;

    if ( isFile )
    {
        int count;
        QByteArray data;

        QFile f (QFile::encodeName(msg));

        if (!f.exists())
        {
          kdError() << "Could not find: " << f.name () << endl;
          return;
        }

        if (!f.open(IO_ReadOnly))
        {
          f.close ();
          kdError() << "Could not open: " << f.name() << endl;
          return;
        }

        // Read contents of file...
        count = 0;

        while ((count= readContent(f, MAX_READ_BUF_SIZE, data)) > 0);

        // Error! Exit!
        if ( count == -1 )
        {
          kdError () << "Error reading from: " << f.name() << endl;
          f.close ();
          return;
        }

        f.close ();

        // Perform the requested encoding or decoding...
        switch (type)
        {
            case Base64Encode:
                KCodecs::base64Encode(data, output, true);
                break;
            case Base64Decode:
                KCodecs::base64Decode(data, output);
                break;
            case UUEncode:
                KCodecs::uuencode(data, output);
                break;
            case UUDecode:
                KCodecs::uudecode(data, output);
                break;
            case QPEncode:
                KCodecs::quotedPrintableEncode(data, output, true);
                break;
            case QPDecode:
                KCodecs::quotedPrintableDecode(data, output);
                break;
            default:
                break;
        }

        QCString result (output.data(), output.size()+1);
        cout << "Result: " << endl << result << endl;
    }
    else
    {
        QCString result;

        const size_t len = strlen(msg);
        output.resize(len);
        memcpy (output.data(), msg, len);

        switch (type)
        {
          case Base64Encode:
            result = KCodecs::base64Encode(output);
            break;
          case Base64Decode:
            result = KCodecs::base64Decode(output);
            break;
          case UUEncode:
            result = KCodecs::uuencode(output);
            break;
          case UUDecode:
            result = KCodecs::uudecode(output);
            break;
          case QPEncode:
            result = KCodecs::quotedPrintableEncode(output);
            break;
          case QPDecode:
            result = KCodecs::quotedPrintableDecode(output);
            break;
          default:
            break;
        }
        cout << result << endl;
    }
}