Пример #1
0
void PythonPlugin::initialize()
{
    addObject(&mLogger);

    if (!Py_IsInitialized()) {
        // PEP370
        Py_NoSiteFlag = 1;
        Py_NoUserSiteDirectory = 1;

        Py_Initialize();
        inittiled();

        // Get reference to base class to find its extensions later on
        PyObject *pmod = PyImport_ImportModule("tiled");
        if (pmod) {
            PyObject *tiledPlugin = PyObject_GetAttrString(pmod, "Plugin");
            Py_DECREF(pmod);

            if (tiledPlugin) {
                if (PyCallable_Check(tiledPlugin)) {
                    mPluginClass = tiledPlugin;
                } else {
                    Py_DECREF(tiledPlugin);
                }
            }
        }

        if (!mPluginClass) {
            log(Tiled::LoggingInterface::ERROR, "Can't find tiled.Plugin baseclass\n");
            handleError();
            return;
        }

        // w/o differentiating error messages could just rename "log"
        // to "write" in the binding and assign plugin directly to stdout/stderr
        PySys_SetObject((char *)"_tiledplugin",
                        _wrap_convert_c2py__Tiled__LoggingInterface(&mLogger));

        PyRun_SimpleString("import sys\n"
                           "#from tiled.Tiled.LoggingInterface import INFO,ERROR\n"
                           "class _Catcher:\n"
                           "   def __init__(self, type):\n"
                           "      self.buffer = ''\n"
                           "      self.type = type\n"
                           "   def write(self, msg):\n"
                           "      self.buffer += msg\n"
                           "      if self.buffer.endswith('\\n'):\n"
                           "         sys._tiledplugin.log(self.type, self.buffer)\n"
                           "         self.buffer = ''\n"
                           "sys.stdout = _Catcher(0)\n"
                           "sys.stderr = _Catcher(1)\n");

        PyRun_SimpleString(QString("import sys; sys.path.insert(0, \"%1\")")
                           .arg(mScriptDir).toUtf8().constData());

        log(QString("-- Added %1 to path\n").arg(mScriptDir));
    }

    reloadModules();

    if (QFile::exists(mScriptDir)) {
        mFileSystemWatcher.addPath(mScriptDir);

        connect(&mFileSystemWatcher, SIGNAL(directoryChanged(QString)),
                &mReloadTimer, SLOT(start()));
    }
}
Пример #2
0
int main(void)
{

   int stepSize = 1;
   int quit = 0;
   int timer = 0;

   // Set STDIN non-blocking (Still requires Return)
   int flags = fcntl(0, F_GETFL);
   flags |= O_NONBLOCK;
   fcntl(0, F_SETFL, flags);

   handleError("Couldn't open stdin.", 1);

   printf("---Press q and press return to quit---\n");
   printf("   Press 1-8 and press return to change the step-size\n");

   //POLLED_UAR Specific Stuff
   tcnter_init();


   while(!quit)
   {
      //This worked in 0.10-3! But now 0.10-4?!
//    handleError(" Unhandled Error.", 0);

      char kbChar;
      kbChar = getchar();

      //"Resource Temporarily Unavailable" isn't an error in this case
      if(errno == 35)
         errno = 0;
      else
      {
         switch(kbChar)
         {
            case 'q':
               quit = 1;
               break;
            case '1':
               stepSize = 1;
               break;
            case '2':
               stepSize = 2;
               break;
            case '3':
               stepSize = 3;
               break;
            case '4':
               stepSize = 4;
               break;
            case '5':
               stepSize = 5;
               break;
            case '6':
               stepSize = 6;
               break;
            case '7':
               stepSize = 7;
               break;
            case '8':
               stepSize = 8;
               break;

            case '\n':
               break;
            //^^^ TO HERE
            default:
               printf("Received: '%c'", kbChar);
         }
      }


   // tcnter_update();

      timer++;

      if(timer == 100000)
      {
         static int nextOverflowTime=0;
         static int waitForOverflow=FALSE;

         timerCounter+=stepSize;
         if(timerCounter >= TCNTER_SOURCE_OVERFLOW_VAL)
         {
            waitForOverflow = FALSE;
            timerCounter -= TCNTER_SOURCE_OVERFLOW_VAL;
         }

         timer=0;
         
         if(!waitForOverflow && (timerCounter == nextOverflowTime))
         {
            printf("tcnter_overflowUpdate()\n");
            tcnter_overflowUpdate();

            nextOverflowTime=random()%3;
            printf(" next at %d\n", nextOverflowTime);
            waitForOverflow=TRUE;
         }

         if((random()&0x07) == 0x01)
         {
            printf("tcnter_update()\n");
            tcnter_update();
         }
         
         printf("TCNT: %d, tcnter=%d\n",timerCounter, tcnter_get());
      }

//    tcnter_update();

   }


   return 0;
}
Пример #3
0
/*
	ExpandVolumeWizard

	Expands a trucrypt volume (wizard for user interface)

	Parameters:

		hwndDlg : HWND
			[in] handle to parent window (if any)

		szVolume : char *
			[in] Pointer to a string with the volume name (e.g. '\Device\Harddisk0\Partition1' or 'C:\topsecret.tc')

	Return value:

		none

*/
void ExpandVolumeWizard (HWND hwndDlg, wchar_t *lpszVolume)
{
	int nStatus = ERR_OS_ERROR;
	wchar_t szTmp[4096];
	Password VolumePassword;
	int VolumePkcs5 = 0, VolumePim = -1;
	uint64 hostSize, volSize, hostSizeFree, maxSizeFS;
	BOOL bIsDevice, bIsLegacy;
	DWORD dwError;
	int driveNo;
	enum EV_FileSystem volFSType;
	wchar_t rootPath[] = L"A:\\";

	switch (IsSystemDevicePath (lpszVolume, hwndDlg, TRUE))
	{
	case 1:
	case 2:
		MessageBoxW (hwndDlg, L"A VeraCrypt system volume can't be expanded.", lpszTitle, MB_OK|MB_ICONEXCLAMATION);
		goto ret;
	}

	EnableElevatedCursorChange (hwndDlg);
	WaitCursor();

	if (IsMountedVolume (lpszVolume))
	{
		Warning ("DISMOUNT_FIRST", hwndDlg);
		goto ret;
	}

	if (Randinit() != ERR_SUCCESS) {
		if (CryptoAPILastError == ERROR_SUCCESS)
			nStatus = ERR_RAND_INIT_FAILED;
		else
			nStatus = ERR_CAPI_INIT_FAILED;
		goto error;
	}

	NormalCursor();

	// Ask the user if there is a hidden volume
	char *volTypeChoices[] = {0, "DOES_VOLUME_CONTAIN_HIDDEN", "VOLUME_CONTAINS_HIDDEN", "VOLUME_DOES_NOT_CONTAIN_HIDDEN", "IDCANCEL", 0};
	switch (AskMultiChoice ((void **) volTypeChoices, FALSE, hwndDlg))
	{
	case 1:
		MessageBoxW (hwndDlg, L"An outer volume containing a hidden volume can't be expanded, because this destroys the hidden volume.", lpszTitle, MB_OK|MB_ICONEXCLAMATION);
		goto ret;

	case 2:
		break;

	default:
		nStatus = ERR_SUCCESS;
		goto ret;
	}

	WaitCursor();

	nStatus = QueryVolumeInfo(hwndDlg,lpszVolume,&hostSizeFree,&maxSizeFS);

	if (nStatus!=ERR_SUCCESS)
	{
		nStatus = ERR_OS_ERROR;
		goto error;
	}

	NormalCursor();

	while (TRUE)
	{
		OpenVolumeContext expandVol;
		BOOL truecryptMode = FALSE;

		if (!VeraCryptExpander::ExtcvAskVolumePassword (hwndDlg, lpszVolume, &VolumePassword, &VolumePkcs5, &VolumePim, &truecryptMode, "ENTER_NORMAL_VOL_PASSWORD", FALSE))
		{
			goto ret;
		}

		EnableElevatedCursorChange (hwndDlg);
		WaitCursor();

		if (KeyFilesEnable && FirstKeyFile)
			KeyFilesApply (hwndDlg, &VolumePassword, FirstKeyFile, lpszVolume);

		WaitCursor ();

		OpenVolumeThreadParam threadParam;
		threadParam.context = &expandVol;
		threadParam.volumePath = lpszVolume;
		threadParam.password = &VolumePassword;
		threadParam.pkcs5_prf = VolumePkcs5;
		threadParam.pim = VolumePim;
		threadParam.truecryptMode = FALSE;
		threadParam.write = FALSE;
		threadParam.preserveTimestamps = bPreserveTimestamp;
		threadParam.useBackupHeader = FALSE;
		threadParam.nStatus = &nStatus;

		ShowWaitDialog (hwndDlg, TRUE, OpenVolumeWaitThreadProc, &threadParam);

		NormalCursor ();

		dwError = GetLastError();

		if (nStatus == ERR_SUCCESS)
		{
			bIsDevice = expandVol.IsDevice;
			bIsLegacy = expandVol.CryptoInfo->LegacyVolume;
			hostSize = expandVol.HostSize;			
			VolumePkcs5 = expandVol.CryptoInfo->pkcs5;
			if ( bIsLegacy )
			{
				if ( bIsDevice ) 
					volSize = 0; // updated later
				else
					volSize = hostSize;
			}
			else
			{
				volSize = GetVolumeSizeByDataAreaSize (expandVol.CryptoInfo->VolumeSize.Value, bIsLegacy);
			}
			CloseVolume (&expandVol);
			break;
		}
		else if (nStatus != ERR_PASSWORD_WRONG)
		{
			SetLastError (dwError);
			goto error;
		}

		NormalCursor();

		handleError (hwndDlg, nStatus, SRC_POS);
	}

	WaitCursor();

	// auto mount the volume to check the file system type
	nStatus=MountVolTemp(hwndDlg, lpszVolume, &driveNo, &VolumePassword, VolumePkcs5, VolumePim);

	if (nStatus != ERR_SUCCESS)
		goto error;

	rootPath[0] += driveNo;

	if ( !GetFileSystemType(rootPath,&volFSType) )
		volFSType = EV_FS_TYPE_RAW;

	if ( bIsLegacy && bIsDevice && volFSType == EV_FS_TYPE_NTFS )
	{
		uint64 NumberOfSectors;
		DWORD BytesPerSector;
		
		if ( !GetNtfsNumberOfSectors(rootPath, &NumberOfSectors, &BytesPerSector) )
			nStatus = ERR_OS_ERROR;

		// NTFS reported size does not include boot sector copy at volume end
		volSize = ( NumberOfSectors + 1 ) * BytesPerSector;
	}

	UnmountVolume (hwndDlg, driveNo, TRUE);

	NormalCursor();

	if (nStatus != ERR_SUCCESS)
		goto error;

	if ( bIsDevice && bIsLegacy && volFSType != EV_FS_TYPE_NTFS )
	{
		MessageBoxW (hwndDlg,
			L"Expanding a device hosted legacy volume with no NTFS file system\n"
			L"is unsupported.\n"
			L"Note that expanding the VeraCrypt volume itself is not neccessary\n"
			L"for legacy volumes.\n",
			lpszTitle, MB_OK|MB_ICONEXCLAMATION);
		goto ret;
	}

	// check if there is enough free space on host device/drive to expand the volume
	if ( (bIsDevice && hostSize < volSize + TC_MINVAL_FS_EXPAND) || (!bIsDevice && hostSizeFree < TC_MINVAL_FS_EXPAND) )
	{
		MessageBoxW (hwndDlg, L"Not enough free space to expand the volume", lpszTitle, MB_OK|MB_ICONEXCLAMATION);
		goto ret;
	}

	if (!bIsDevice && hostSize != volSize ) {
		// there is some junk data at the end of the volume
		if (MessageBoxW (hwndDlg, L"Warning: The container file is larger than the VeraCrypt volume area. The data after the VeraCrypt volume area will be overwritten.\n\nDo you want to continue?", lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO)
			goto ret;
	}

	switch (volFSType)
	{
	case EV_FS_TYPE_NTFS:
		break;
	case EV_FS_TYPE_FAT:
		if (MessageBoxW (hwndDlg,L"Warning: The VeraCrypt volume contains a FAT file system!\n\nOnly the VeraCrypt volume itself will be expanded, but not the file system.\n\nDo you want to continue?",
			lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO)
			goto ret;
		break;
	default:
		if (MessageBoxW (hwndDlg,L"Warning: The VeraCrypt volume contains an unknown or no file system!\n\nOnly the VeraCrypt volume itself will be expanded, the file system remains unchanged.\n\nDo you want to continue?",
			lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO)
			goto ret;
	}

	EXPAND_VOL_THREAD_PARAMS VolExpandParam;

	VolExpandParam.bInitFreeSpace = (bIsLegacy && bIsDevice) ? FALSE:TRUE;
	VolExpandParam.szVolumeName = lpszVolume;
	VolExpandParam.FileSystem = volFSType;
	VolExpandParam.pVolumePassword = &VolumePassword;
	VolExpandParam.VolumePkcs5 = VolumePkcs5;
	VolExpandParam.VolumePim = VolumePim;
	VolExpandParam.bIsDevice = bIsDevice;
	VolExpandParam.bIsLegacy = bIsLegacy;
	VolExpandParam.oldSize = bIsDevice ? volSize : hostSize;
	VolExpandParam.newSize = hostSize;
	VolExpandParam.hostSizeFree = hostSizeFree;

	while (1)
	{
		uint64 newVolumeSize;

		if (IDCANCEL == DialogBoxParamW (hInst,
			MAKEINTRESOURCEW (IDD_SIZE_DIALOG), hwndDlg,
			(DLGPROC) ExpandVolSizeDlgProc, (LPARAM) &VolExpandParam))
		{
			goto ret;
		}

		newVolumeSize = VolExpandParam.newSize;

		if ( !bIsDevice )
		{
			if ( newVolumeSize < hostSize + TC_MINVAL_FS_EXPAND)
			{
				StringCbPrintfW(szTmp,sizeof(szTmp),L"New volume size too small, must be at least %I64u kB larger than the current size.",TC_MINVAL_FS_EXPAND/BYTES_PER_KB);
				MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_OK | MB_ICONEXCLAMATION );
				continue;
			}

			if ( newVolumeSize - hostSize > hostSizeFree )
			{
				StringCbPrintfW(szTmp,sizeof(szTmp),L"New volume size too large, not enough space on host drive.");
				MessageBoxW (hwndDlg, szTmp, lpszTitle, MB_OK | MB_ICONEXCLAMATION );
				continue;
			}

			if ( newVolumeSize>maxSizeFS )
			{
				StringCbPrintfW(szTmp,sizeof(szTmp),L"Maximum file size of %I64u MB on host drive exceeded.",maxSizeFS/BYTES_PER_MB);
				MessageBoxW (hwndDlg, L"!\n",lpszTitle, MB_OK | MB_ICONEXCLAMATION );
				continue;
			}
		}

		if ( newVolumeSize > TC_MAX_VOLUME_SIZE )
		{
			// note: current limit TC_MAX_VOLUME_SIZE is 1 PetaByte
			StringCbPrintfW(szTmp,sizeof(szTmp),L"Maximum VeraCrypt volume size of %I64u TB exceeded!\n",TC_MAX_VOLUME_SIZE/BYTES_PER_TB);
			MessageBoxW (hwndDlg, szTmp,lpszTitle, MB_OK | MB_ICONEXCLAMATION );
			if (bIsDevice)
				break; // TODO: ask to limit volume size to TC_MAX_VOLUME_SIZE
			continue;
		}

		break;
	}

	VolExpandParam.oldSize = volSize;

	// start progress dialog
	DialogBoxParamW (hInst,	MAKEINTRESOURCEW (IDD_EXPAND_PROGRESS_DLG), hwndDlg,
		(DLGPROC) ExpandVolProgressDlgProc, (LPARAM) &VolExpandParam );

ret:
	nStatus = ERR_SUCCESS;

error:

	if (nStatus != 0)
		handleError (hwndDlg, nStatus, SRC_POS);

	burn (&VolumePassword, sizeof (VolumePassword));

	RestoreDefaultKeyFilesParam();
	RandStop (FALSE);
	NormalCursor();

	return;
}
bool TSReader::read(Translator &translator)
{
    STRING(both);
    STRING(byte);
    STRING(comment);
    STRING(context);
    STRING(defaultcodec);
    STRING(encoding);
    STRING(extracomment);
    STRING(filename);
    STRING(id);
    STRING(language);
    STRING(line);
    STRING(location);
    STRING(message);
    STRING(name);
    STRING(numerus);
    STRING(numerusform);
    STRING(obsolete);
    STRING(oldcomment);
    STRING(oldsource);
    STRING(source);
    STRING(sourcelanguage);
    STRING(translation);
    STRING(translatorcomment);
    STRING(true);
    STRING(TS);
    STRING(type);
    STRING(unfinished);
    STRING(userdata);
    STRING(utf8);
    STRING(value);
    //STRING(version);
    STRING(yes);

    static const QString strextrans(QLatin1String("extra-"));
    static const QString strUtf8(QLatin1String("UTF-8"));

    while (!atEnd()) {
        readNext();
        if (isStartDocument()) {
            // <!DOCTYPE TS>
            //qDebug() << attributes();
        } else if (isEndDocument()) {
            // <!DOCTYPE TS>
            //qDebug() << attributes();
        } else if (isDTD()) {
            // <!DOCTYPE TS>
            //qDebug() << tokenString();
        } else if (elementStarts(strTS)) {
            // <TS>
            //qDebug() << "TS " << attributes();
            QHash<QString, int> currentLine;
            QString currentFile;

            QXmlStreamAttributes atts = attributes();
            //QString version = atts.value(strversion).toString();
            translator.setLanguageCode(atts.value(strlanguage).toString());
            translator.setSourceLanguageCode(atts.value(strsourcelanguage).toString());
            while (!atEnd()) {
                readNext();
                if (isEndElement()) {
                    // </TS> found, finish local loop
                    break;
                } else if (isWhiteSpace()) {
                    // ignore these, just whitespace
                } else if (elementStarts(strdefaultcodec)) {
                    // <defaultcodec>
                    const QString &codec = readElementText();
                    if (!codec.isEmpty())
                        translator.setCodecName(codec.toLatin1());
                    // </defaultcodec>
                } else if (isStartElement()
                        && name().toString().startsWith(strextrans)) {
                    // <extra-...>
                    QString tag = name().toString();
                    translator.setExtra(tag.mid(6), readContents());
                    // </extra-...>
                } else if (elementStarts(strcontext)) {
                    // <context>
                    QString context;
                    while (!atEnd()) {
                        readNext();
                        if (isEndElement()) {
                            // </context> found, finish local loop
                            break;
                        } else if (isWhiteSpace()) {
                            // ignore these, just whitespace
                        } else if (elementStarts(strname)) {
                            // <name>
                            context = readElementText();
                            // </name>
                        } else if (elementStarts(strmessage)) {
                            // <message>
                            TranslatorMessage::References refs;
                            QString currentMsgFile = currentFile;

                            TranslatorMessage msg;
                            msg.setId(attributes().value(strid).toString());
                            msg.setContext(context);
                            msg.setType(TranslatorMessage::Finished);
                            msg.setPlural(attributes().value(strnumerus) == stryes);
                            const QStringRef &utf8Attr = attributes().value(strutf8);
                            msg.setNonUtf8(utf8Attr == strboth);
                            msg.setUtf8(msg.isNonUtf8() || utf8Attr == strtrue
                                 ||  attributes().value(strencoding) == strUtf8);
                            while (!atEnd()) {
                                readNext();
                                if (isEndElement()) {
                                    // </message> found, finish local loop
                                    msg.setReferences(refs);
                                    translator.append(msg);
                                    break;
                                } else if (isWhiteSpace()) {
                                    // ignore these, just whitespace
                                } else if (elementStarts(strsource)) {
                                    // <source>...</source>
                                    msg.setSourceText(readContents());
                                } else if (elementStarts(stroldsource)) {
                                    // <oldsource>...</oldsource>
                                    msg.setOldSourceText(readContents());
                                } else if (elementStarts(stroldcomment)) {
                                    // <oldcomment>...</oldcomment>
                                    msg.setOldComment(readContents());
                                } else if (elementStarts(strextracomment)) {
                                    // <extracomment>...</extracomment>
                                    msg.setExtraComment(readContents());
                                } else if (elementStarts(strtranslatorcomment)) {
                                    // <translatorcomment>...</translatorcomment>
                                    msg.setTranslatorComment(readContents());
                                } else if (elementStarts(strlocation)) {
                                    // <location/>
                                    QXmlStreamAttributes atts = attributes();
                                    QString fileName = atts.value(strfilename).toString();
                                    if (fileName.isEmpty()) {
                                        fileName = currentMsgFile;
                                    } else {
                                        if (refs.isEmpty())
                                            currentFile = fileName;
                                        currentMsgFile = fileName;
                                    }
                                    const QString lin = atts.value(strline).toString();
                                    if (lin.isEmpty()) {
                                        translator.setLocationsType(Translator::RelativeLocations);
                                        refs.append(TranslatorMessage::Reference(fileName, -1));
                                    } else {
                                        bool bOK;
                                        int lineNo = lin.toInt(&bOK);
                                        if (bOK) {
                                            if (lin.startsWith(QLatin1Char('+')) || lin.startsWith(QLatin1Char('-'))) {
                                                lineNo = (currentLine[fileName] += lineNo);
                                                translator.setLocationsType(Translator::RelativeLocations);
                                            } else {
                                                translator.setLocationsType(Translator::AbsoluteLocations);
                                            }
                                            refs.append(TranslatorMessage::Reference(fileName, lineNo));
                                        }
                                    }
                                    readContents();
                                } else if (elementStarts(strcomment)) {
                                    // <comment>...</comment>
                                    msg.setComment(readContents());
                                } else if (elementStarts(struserdata)) {
                                    // <userdata>...</userdata>
                                    msg.setUserData(readContents());
                                } else if (elementStarts(strtranslation)) {
                                    // <translation>
                                    QXmlStreamAttributes atts = attributes();
                                    QStringRef type = atts.value(strtype);
                                    if (type == strunfinished)
                                        msg.setType(TranslatorMessage::Unfinished);
                                    else if (type == strobsolete)
                                        msg.setType(TranslatorMessage::Obsolete);
                                    if (msg.isPlural()) {
                                        QStringList translations;
                                        while (!atEnd()) {
                                            readNext();
                                            if (isEndElement()) {
                                                break;
                                            } else if (isWhiteSpace()) {
                                                // ignore these, just whitespace
                                            } else if (elementStarts(strnumerusform)) {
                                                translations.append(readTransContents());
                                            } else {
                                                handleError();
                                                break;
                                            }
                                        }
                                        msg.setTranslations(translations);
                                    } else {
                                        msg.setTranslation(readTransContents());
                                    }
                                    // </translation>
                                } else if (isStartElement()
                                        && name().toString().startsWith(strextrans)) {
                                    // <extra-...>
                                    QString tag = name().toString();
                                    msg.setExtra(tag.mid(6), readContents());
                                    // </extra-...>
                                } else {
                                    handleError();
                                }
                            }
                            // </message>
                        } else {
                            handleError();
                        }
                    }
                    // </context>
                } else {
                    handleError();
                }
            } // </TS>
        } else {
            handleError();
        }
    }
    if (hasError()) {
        m_cd.appendError(errorString());
        return false;
    }
    return true;
}
Пример #5
0
void VoicForm :: controlChange( int number, StkFloat value )
{
  StkFloat norm = value * ONE_OVER_128;
  if ( norm < 0 ) {
    norm = 0.0;
    errorString_ << "VoicForm::controlChange: control value less than zero ... setting to zero!";
    handleError( StkError::WARNING );
  }
  else if ( norm > 1.0 ) {
    norm = 1.0;
    errorString_ << "VoicForm::controlChange: control value greater than 128.0 ... setting to 128.0!";
    handleError( StkError::WARNING );
  }

  if (number == __SK_Breath_)	{ // 2
    this->setVoiced( 1.0 - norm );
    this->setUnVoiced( 0.01 * norm );
  }
  else if (number == __SK_FootControl_)	{ // 4
    StkFloat temp = 0.0;
    unsigned int i = (int) value;
    if (i < 32)	{
      temp = 0.9;
    }
    else if (i < 64)	{
      i -= 32;
      temp = 1.0;
    }
    else if (i < 96)	{
      i -= 64;
      temp = 1.1;
    }
    else if (i < 128)	{
      i -= 96;
      temp = 1.2;
    }
    else if (i == 128)	{
      i = 0;
      temp = 1.4;
    }
    filters_[0].setTargets( temp * Phonemes::formantFrequency(i, 0), Phonemes::formantRadius(i, 0), pow(10.0, Phonemes::formantGain(i, 0 ) / 20.0) );
    filters_[1].setTargets( temp * Phonemes::formantFrequency(i, 1), Phonemes::formantRadius(i, 1), pow(10.0, Phonemes::formantGain(i, 1 ) / 20.0) );
    filters_[2].setTargets( temp * Phonemes::formantFrequency(i, 2), Phonemes::formantRadius(i, 2), pow(10.0, Phonemes::formantGain(i, 2 ) / 20.0) );
    filters_[3].setTargets( temp * Phonemes::formantFrequency(i, 3), Phonemes::formantRadius(i, 3), pow(10.0, Phonemes::formantGain(i, 3 ) / 20.0) );
    this->setVoiced( Phonemes::voiceGain( i ) );
    this->setUnVoiced( Phonemes::noiseGain( i ) );
  }
  else if (number == __SK_ModFrequency_) // 11
    voiced_->setVibratoRate( norm * 12.0);  // 0 to 12 Hz
  else if (number == __SK_ModWheel_) // 1
    voiced_->setVibratoGain( norm * 0.2);
  else if (number == __SK_AfterTouch_Cont_)	{ // 128
    this->setVoiced( norm );
    onepole_.setPole( 0.97 - ( norm * 0.2) );
  }
  else {
    errorString_ << "VoicForm::controlChange: undefined control number (" << number << ")!";
    handleError( StkError::WARNING );
  }

#if defined(_STK_DEBUG_)
  errorString_ << "VoicForm::controlChange: number = " << number << ", value = " << value << '.';
  handleError( StkError::DEBUG_WARNING );
#endif
}
Пример #6
0
int main (int argc, char *argv[]) {

    // Parallelization related. Initialize and identify
    // ---------------------------------------------------
    int rank;   // This processor's identifier
    int nproc;  // Number of processors in the group
    PetscInitialize(&argc, &argv, "petsc_commandline_arg", PETSC_NULL);
    MPI_Comm_size(PETSC_COMM_WORLD, &nproc);
    MPI_Comm_rank(PETSC_COMM_WORLD, &rank);
    std::cout << "Rank: " << rank << ", Nproc: " << nproc << std::endl;
    //----------------------------------------------------

    // TODO probably remove this error check in future to play around with petsc 
    //if (argc != 2){
    //    handleError(1, "A configuration file is required! Call the program by ./main configfile.xml");
    //}

    // read configuration and store information in parameters object
    Configuration configuration(argv[1]);
    Parameters parameters;
    configuration.loadParameters(parameters);
    PetscParallelConfiguration parallelConfiguration(parameters);
    FlowField *flowField = NULL;
    Simulation *simulation = NULL;

    std::cout << "Processor " << parameters.parallel.rank << " with index ";
    std::cout << parameters.parallel.indices[0] << ",";
    std::cout << parameters.parallel.indices[1] << ",";
    std::cout << parameters.parallel.indices[2];
    std::cout <<    " is computing the size of its subdomain and obtains ";
    std::cout << parameters.parallel.localSize[0] << ", ";
    std::cout << parameters.parallel.localSize[1] << " and ";
    std::cout << parameters.parallel.localSize[2];
    std::cout << ". Left neighbour: " << parameters.parallel.leftNb;
    std::cout << ", right neighbour: " << parameters.parallel.rightNb;
    std::cout << std::endl;

    // initialise simulation
    if (parameters.simulation.type=="dns"){
      std::cout << "Start DNS simulation in " << parameters.geometry.dim << "D" << std::endl;
      flowField = new FlowField(parameters);
      if(flowField == NULL){ handleError(1, "flowField==NULL!"); }
      simulation = new Simulation(parameters,*flowField);
    } else {
      handleError(1, "Unknown simulation type! Currently supported: dns");
    }
    // call initialization of simulation (initialize flow field)
    if(simulation == NULL){ handleError(1, "simulation==NULL!"); }
    simulation->initializeFlowField();
    //flowField->getFlags().show();

    FLOAT time = 0.0;
    FLOAT timeVtk=parameters.vtk.interval;
    FLOAT timeStdOut=parameters.stdOut.interval;
    int timeSteps = 0;

    // plot initial state
    simulation->plotVTK(timeSteps);

    // time loop
    while (time < parameters.simulation.finalTime){

      simulation->solveTimestep();

      time += parameters.timestep.dt;

      // std-out: terminal info
      if ( (rank==0) && (timeStdOut <= time) ){
          std::cout << "Current time: " << time << "\ttimestep: " <<
                        parameters.timestep.dt << std::endl;
          timeStdOut += parameters.stdOut.interval;
      }
      // VTK output
      if ( timeVtk <= time ) {
        simulation->plotVTK(timeSteps);
        timeVtk += parameters.vtk.interval;
      }
      timeSteps++;
    }

    // plot final output
    simulation->plotVTK(timeSteps);

    delete simulation; simulation=NULL;
    delete flowField;  flowField= NULL;

    PetscFinalize();
}
Пример #7
0
void OpenRouteServiceRunner::get()
{
    QNetworkReply *reply = m_networkAccessManager.get(m_request);
    connect( reply, SIGNAL(error(QNetworkReply::NetworkError)),
             this, SLOT(handleError(QNetworkReply::NetworkError)), Qt::DirectConnection);
}
Пример #8
0
/*!
  Opens a new network session.
*/
void ConnectionManager::openNewNetworkSession()
{
    qDebug() << "ConnectionManager::openNewNetworkSession() =>";

    if (mState == Connecting) {
        qDebug() << "ConnectionManager::openNewNetworkSession()"
                 << "<= Already connecting!!!";
        return;
    }

    // Disconnect previous connection and delete the network session instance.
    disconnect();
    clearConnectionInformation();
    delete mNetworkSession;
    mNetworkSession = 0;

    // Set state to 'Connecting'.
    setState(Connecting);

    // Get the configurations.
    QList<QNetworkConfiguration> configurations =
            mNetworkConfMgr->allConfigurations(QNetworkConfiguration::Discovered);

    if (configurations.isEmpty()) {
        configurations << mNetworkConfMgr->defaultConfiguration();
    }

    bool sessionOpened(false);

    foreach (QNetworkConfiguration configuration, configurations) {
        if (!validWlanConfiguration(configuration)) {
            // Invalid configuration, try the next one.
            continue;
        }

        // Valid configuration found!
        mNetworkSession = new QNetworkSession(configuration, this);

        // Open the network session.
        mNetworkSession->open();

        if (mNetworkSession->waitForOpened()) {
            qDebug() << "ConnectionManager::openNewNetworkSession():"
                     << "Selecting" << configuration.name();

            // Connect the signals.
            connect(mNetworkSession, SIGNAL(closed()),
                    this, SLOT(handleNetworkSessionClosed()),
                    Qt::UniqueConnection);
            connect(mNetworkSession, SIGNAL(error(QNetworkSession::SessionError)),
                    this, SLOT(handleError(QNetworkSession::SessionError)),
                    Qt::UniqueConnection);
            connect(mNetworkSession, SIGNAL(newConfigurationActivated()),
                    this, SLOT(handleNewConfigurationActivated()),
                    Qt::UniqueConnection);
            connect(mNetworkSession, SIGNAL(stateChanged(QNetworkSession::State)),
                    this, SLOT(handleStateChanged(QNetworkSession::State)),
                    Qt::UniqueConnection);

            handleNetworkSessionOpened();
            sessionOpened = true;

            break;
        }
        else {
            qDebug() << "ConnectionManager::openNewNetworkSession():"
                     << "Failed to open" << configuration.name()
                     << ":" << mNetworkSession->errorString();

            delete mNetworkSession;
            mNetworkSession = 0;
        }
    }

    if (!sessionOpened) {
        qDebug() << "ConnectionManager::openNewNetworkSession():"
                 << "No valid session opened!";
        setState(Failed);
    }

    qDebug() << "ConnectionManager::openNewNetworkSession() <=";
}
Пример #9
0
void ModelBaker::handleBakedTexture() {
    TextureBaker* bakedTexture = qobject_cast<TextureBaker*>(sender());
    qDebug() << "Handling baked texture" << bakedTexture->getTextureURL();

    // make sure we haven't already run into errors, and that this is a valid texture
    if (bakedTexture) {
        if (!shouldStop()) {
            if (!bakedTexture->hasErrors()) {
                if (!_originalOutputDir.isEmpty()) {
                    // we've been asked to make copies of the originals, so we need to make copies of this if it is a linked texture

                    // use the path to the texture being baked to determine if this was an embedded or a linked texture

                    // it is embeddded if the texure being baked was inside a folder with the name of the model
                    // since that is the fake URL we provide when baking external textures

                    if (!_modelURL.isParentOf(bakedTexture->getTextureURL())) {
                        // for linked textures we want to save a copy of original texture beside the original model

                        qCDebug(model_baking) << "Saving original texture for" << bakedTexture->getTextureURL();

                        // check if we have a relative path to use for the texture
                        auto relativeTexturePath = texturePathRelativeToModel(_modelURL, bakedTexture->getTextureURL());

                        QFile originalTextureFile{
                            _originalOutputDir + "/" + relativeTexturePath + bakedTexture->getTextureURL().fileName()
                        };

                        if (relativeTexturePath.length() > 0) {
                            // make the folders needed by the relative path
                        }

                        if (originalTextureFile.open(QIODevice::WriteOnly) && originalTextureFile.write(bakedTexture->getOriginalTexture()) != -1) {
                            qCDebug(model_baking) << "Saved original texture file" << originalTextureFile.fileName()
                                << "for" << _modelURL;
                        } else {
                            handleError("Could not save original external texture " + originalTextureFile.fileName()
                                        + " for " + _modelURL.toString());
                            return;
                        }
                    }
                }


                // now that this texture has been baked and handled, we can remove that TextureBaker from our hash
                _bakingTextures.remove(bakedTexture->getTextureURL());

                checkIfTexturesFinished();
            } else {
                // there was an error baking this texture - add it to our list of errors
                _errorList.append(bakedTexture->getErrors());

                // we don't emit finished yet so that the other textures can finish baking first
                _pendingErrorEmission = true;

                // now that this texture has been baked, even though it failed, we can remove that TextureBaker from our list
                _bakingTextures.remove(bakedTexture->getTextureURL());

                // abort any other ongoing texture bakes since we know we'll end up failing
                for (auto& bakingTexture : _bakingTextures) {
                    bakingTexture->abort();
                }

                checkIfTexturesFinished();
            }
        } else {
            // we have errors to attend to, so we don't do extra processing for this texture
            // but we do need to remove that TextureBaker from our list
            // and then check if we're done with all textures
            _bakingTextures.remove(bakedTexture->getTextureURL());

            checkIfTexturesFinished();
        }
    }
}
Пример #10
0
bool SSLSocket::setupCrypto(SSLSocket *session /* = NULL */) {
  if (m_data->m_handle) {
    raise_warning("SSL/TLS already set-up for this stream");
    return false;
  }

  if (!m_context.exists(s_verify_peer)) {
    m_context.add(s_verify_peer, true);
  }

  /* need to do slightly different things, based on client/server method,
   * so lets remember which method was selected */
#if OPENSSL_VERSION_NUMBER < 0x00909000L
  SSL_METHOD *smethod;
#else
  const SSL_METHOD *smethod;
#endif
  switch (m_data->m_method) {
  case CryptoMethod::ClientSSLv23:
    m_data->m_client = true;
    smethod = SSLv23_client_method();
    break;
  case CryptoMethod::ClientTLS:
    m_data->m_client = true;
    smethod = TLSv1_client_method();
    break;
  case CryptoMethod::ServerSSLv23:
    m_data->m_client = false;
    smethod = SSLv23_server_method();
    break;

#ifndef OPENSSL_NO_SSL3
  case CryptoMethod::ClientSSLv3:
    m_data->m_client = true;
    smethod = SSLv3_client_method();
    break;
  case CryptoMethod::ServerSSLv3:
    m_data->m_client = false;
    smethod = SSLv3_server_method();
    break;
#else
  case CryptoMethod::ClientSSLv3:
  case CryptoMethod::ServerSSLv3:
    raise_warning("OpenSSL library does not support SSL3 protocol");
    return false;
#endif

  /* SSLv2 protocol might be disabled in the OpenSSL library */
#ifndef OPENSSL_NO_SSL2
  case CryptoMethod::ClientSSLv2:
    m_data->m_client = true;
    smethod = SSLv2_client_method();
    break;
  case CryptoMethod::ServerSSLv2:
    m_data->m_client = false;
    smethod = SSLv2_server_method();
    break;
#else
  case CryptoMethod::ClientSSLv2:
  case CryptoMethod::ServerSSLv2:
    raise_warning("OpenSSL library does not support SSL2 protocol");
    return false;
  break;
#endif

  case CryptoMethod::ServerTLS:
    m_data->m_client = false;
    smethod = TLSv1_server_method();
    break;
  default:
    return false;
  }

  SSL_CTX *ctx = SSL_CTX_new(smethod);
  if (ctx == nullptr) {
    raise_warning("failed to create an SSL context");
    return false;
  }

  SSL_CTX_set_options(ctx, SSL_OP_ALL);
  m_data->m_handle = createSSL(ctx);
  if (m_data->m_handle == nullptr) {
    raise_warning("failed to create an SSL handle");
    SSL_CTX_free(ctx);
    return false;
  }

  m_data->m_ctx = ctx;

  if (!SSL_set_fd(m_data->m_handle, getFd())) {
    handleError(0, true);
  }
  if (session) {
    SSL_copy_session_id(m_data->m_handle, session->m_data->m_handle);
  }
  return true;
}
Пример #11
0
bool SSLSocket::enableCrypto(bool activate /* = true */) {
  if (activate && !m_data->m_ssl_active) {
    double timeout = m_data->m_connect_timeout;
    bool blocked = m_data->m_is_blocked;
    if (!m_data->m_state_set) {
      if (m_data->m_client) {
        SSL_set_connect_state(m_data->m_handle);
      } else {
        SSL_set_accept_state(m_data->m_handle);
      }
      m_data->m_state_set = true;
    }

    if (m_data->m_client && setBlocking(false)) {
      m_data->m_is_blocked = false;
    }

    int n;
    bool retry = true;
    do {
      if (m_data->m_client) {
        struct timeval tvs, tve;
        struct timezone tz;

        gettimeofday(&tvs, &tz);
        n = SSL_connect(m_data->m_handle);
        gettimeofday(&tve, &tz);

        timeout -= (tve.tv_sec + (double) tve.tv_usec / 1000000) -
          (tvs.tv_sec + (double) tvs.tv_usec / 1000000);
        if (timeout < 0) {
          raise_warning("SSL: connection timeout");
          return false;
        }
      } else {
        n = SSL_accept(m_data->m_handle);
      }

      if (n <= 0) {
        retry = handleError(n, true);
      } else {
        break;
      }
    } while (retry);

    if (m_data->m_client &&
        m_data->m_is_blocked != blocked &&
        setBlocking(blocked)) {
      m_data->m_is_blocked = blocked;
    }

    if (n == 1) {
      X509 *peer_cert = SSL_get_peer_certificate(m_data->m_handle);
      if (!applyVerificationPolicy(peer_cert)) {
        SSL_shutdown(m_data->m_handle);
      } else {
        m_data->m_ssl_active = true;

        /* allow the script to capture the peer cert
         * and/or the certificate chain */
        if (m_context[s_capture_peer_cert].toBoolean()) {
          m_context.set(s_peer_certificate,
                        Variant(req::make<Certificate>(peer_cert)));
          peer_cert = nullptr;
        }

        if (m_context[s_capture_peer_cert_chain].toBoolean()) {
          Array arr;
          STACK_OF(X509) *chain = SSL_get_peer_cert_chain(m_data->m_handle);
          if (chain) {
            for (int i = 0; i < sk_X509_num(chain); i++) {
              X509 *mycert = X509_dup(sk_X509_value(chain, i));
              arr.append(Variant(req::make<Certificate>(mycert)));
            }
          }
          m_context.set(s_peer_certificate_chain, arr);
        }
      }

      if (peer_cert) {
        X509_free(peer_cert);
      }
    } else  {
      n = errno == EAGAIN ? 0 : -1;
    }

    return n >= 0;

  } else if (!activate && m_data->m_ssl_active) {
    /* deactivate - common for server/client */
    SSL_shutdown(m_data->m_handle);
    m_data->m_ssl_active = false;
  }
  return true;
}
Пример #12
0
SSCDControl::SSCDControl(QObject* parent) : QTcpServer(parent)
,db(new DatabaseAccess(this))
{
  connect (db, SIGNAL(error(QString)), this, SLOT(handleError(QString)));
}
Пример #13
0
bool WvOut :: setMatFile( const char *fileName )
{
  char name[128];
  strncpy(name, fileName, 128);
  if ( strstr(name, ".mat") == NULL) strcat(name, ".mat");
  fd = fopen(name, "w+b");
  if ( !fd ) {
    sprintf(msg, "WvOut: Could not create MAT file: %s", name);
    return false;
  }

  if ( dataType != MY_FLOAT64 ) {
    dataType = MY_FLOAT64;
    sprintf(msg, "WvOut: Using 64-bit floating-point data format for file %s", name);
    handleError(msg, StkError::WARNING);
  }

  struct mathdr hdr;
  strcpy(hdr.heading,"MATLAB 5.0 MAT-file, Generated using the Synthesis ToolKit in C++ (STK). By Perry R. Cook and Gary P. Scavone, 1995-2002.");

  int i;
  for (i=strlen(hdr.heading);i<124;i++) hdr.heading[i] = ' ';

  // Header Flag Fields
  hdr.hff[0] = (SINT16) 0x0100;   // Version field
  hdr.hff[1] = (SINT16) 'M';      // Endian indicator field ("MI")
  hdr.hff[1] <<= 8;
  hdr.hff[1] += 'I';

  hdr.adf[0] = (SINT32) 14;       // Matlab array data type value
  hdr.adf[1] = (SINT32) 0;        // Size of file after this point to end (in bytes)
                                 // Don't know size yet.

  // Numeric Array Subelements (4):
  // 1. Array Flags
  hdr.adf[2] = (SINT32) 6;        // Matlab 32-bit unsigned integer data type value
  hdr.adf[3] = (SINT32) 8;        // 8 bytes of data to follow
  hdr.adf[4] = (SINT32) 6;        // Double-precision array, no array flags set
  hdr.adf[5] = (SINT32) 0;        // 4 bytes undefined
  // 2. Array Dimensions
  hdr.adf[6] = (SINT32) 5;        // Matlab 32-bit signed integer data type value
  hdr.adf[7] = (SINT32) 8;        // 8 bytes of data to follow (2D array)
  hdr.adf[8] = (SINT32) channels; // This is the number of rows
  hdr.adf[9] = (SINT32) 0;        // This is the number of columns

  // 3. Array Name
  // We'll use fileName for the matlab array name (as well as the file name).
  // If fileName is 4 characters or less, we have to use a compressed data element
  // format for the array name data element.  Otherwise, the array name must
  // be formatted in 8-byte increments (up to 31 characters + NULL).
  SINT32 namelength = (SINT32) strlen(fileName);
  if (strstr(fileName, ".mat")) namelength -= 4;
  if (namelength > 31) namelength = 31; // Truncate name to 31 characters.
  char arrayName[64];
  strncpy(arrayName, fileName, namelength);
  arrayName[namelength] = '\0';
  if (namelength > 4) {
    hdr.adf[10] = (SINT32) 1;        // Matlab 8-bit signed integer data type value
  }
  else { // Compressed data element format
    hdr.adf[10] = namelength;
    hdr.adf[10] <<= 16;
    hdr.adf[10] += 1;
  }
  SINT32 headsize = 40;        // Number of bytes in data element so far.

  // Write the fixed portion of the header
  if ( fwrite(&hdr, 172, 1, fd) != 1 ) goto error;

  // Write MATLAB array name
  SINT32 tmp;
  if (namelength > 4) {
    if ( fwrite(&namelength, 4, 1, fd) != 1) goto error;
    if ( fwrite(arrayName, namelength, 1, fd) != 1 ) goto error;
    tmp = (SINT32) ceil((float)namelength / 8);
    if ( fseek(fd, tmp*8-namelength, SEEK_CUR) == -1 ) goto error;
    headsize += tmp * 8;
  }
  else { // Compressed data element format
    if ( fwrite(arrayName, namelength, 1, fd) != 1 ) goto error;
    tmp = 4 - namelength;
    if ( fseek(fd, tmp, SEEK_CUR) == -1 ) goto error;
  }

  // Finish writing known header information
  tmp = 9;        // Matlab IEEE 754 double data type
  if ( fwrite(&tmp, 4, 1, fd) != 1 ) goto error;
  tmp = 0;        // Size of real part subelement in bytes (8 per sample)
  if ( fwrite(&tmp, 4, 1, fd) != 1 ) goto error;
  headsize += 8;  // Total number of bytes in data element so far

  if ( fseek(fd, 132, SEEK_SET) == -1 ) goto error;
  if ( fwrite(&headsize, 4, 1, fd) != 1 ) goto error; // Write header size ... will update at end
  if ( fseek(fd, 0, SEEK_END) == -1 ) goto error;

  byteswap = false;
  printf("\nCreating MAT-file (%s) containing MATLAB array: %s\n", name, arrayName);
  return true;

 error:
  sprintf(msg, "WvOut: Could not write MAT-file header for file %s", name);
  return false;
}
void YahooFinanceNetworkRequest::handleReply(QNetworkReply *pReply)
{
    if (!pReply)
    {
        qDebug() << "YahooFinanceNetworkRequest::handleReply, null handle, ignored";
        return;
    }

    if (pReply == mpNetworkReply.data())
    {
        qDebug() << "YahooFinanceNetworkRequest::handleReply, reply belongs to us, parsing data...";
        const QVariant http_status_code = pReply->attribute(
                    QNetworkRequest::HttpStatusCodeAttribute);
        bool is_error = pReply->error() != QNetworkReply::NoError;

        qDebug() << "YahooFinanceNetworkRequest::handleReply, HTTP status:"
                 << http_status_code.toString()
                 << ", is error:" << is_error;
        if (!is_error && HTTP_REPLY_CODE_OK == http_status_code.toInt())
        {
            int line_index = 0;
            while (pReply->canReadLine() && mTickers.count() > line_index)
            {
                const QString line(pReply->readLine());
                const QString ticker = mTickers.at(line_index);
                const QStringList data = line.simplified().split(",");
                if (mParameters.count() == data.count())
                {
                    QMap<YahooFinance::StockParameter, QString> data_mappings;
                    for (int value_index = 0; value_index < data.count(); value_index++)
                    {
                        const YahooFinance::StockParameter param = mParameters.at(value_index);
                        const QString value = data.at(value_index);
                        qDebug() << "ticker:" << ticker << ", param:" << param << ", value:" << value;
                        data_mappings.insert(param, value);
                    }

                    emit parametersReceived(mQueryIdentifier, ticker, data_mappings);
                }
                else
                {
                    handleError();
                }
                line_index++;
            }
        }
        else if (HTTP_REPLY_MOVED_PERMANENTLY == http_status_code)
        {
            const QVariant redirection_url = pReply->attribute(
                        QNetworkRequest::RedirectionTargetAttribute);
            qDebug() << "Moved permanently, url:" << redirection_url;
            mUrl.setUrl(redirection_url.toString());
            sendRequest();
        }
        else
        {
            handleError();
            qDebug() << "YahooFinanceNetworkRequest::handleReply, ERROR";
        }

        mpNetworkReply.reset();
    }
    else
    {
        qDebug() << "YahooFinanceNetworkRequest::handleReply, unknown handle, not handled";
        pReply->deleteLater();
    }
}
Пример #15
0
// the exposed libscalpel API
// NOTE: This function is deprecated and will be removed. Use the
// libscalpel_* functions instead.
// TODO make the driver in scalpel_exec.c use this (minor refactoring needed)
// TODO add support for the remaining options avail from cmd-line
// returns SCALPEL_OK on no error, can throw runtime_error exception on errors
int scalpel_carveSingleInput(ScalpelInputReader * const reader, const char * const confFilePath,
    const char * const outDir, const unsigned char generateFooterDb,
    const unsigned char handleEmbedded, const unsigned char organizeSubdirs,
    const unsigned char previewMode,
    const unsigned char carveWithMissingFooters,
    const unsigned char noSearchOverlap) throw (std::runtime_error) {

    if (!reader || ! confFilePath || ! outDir) {
        //invalid args
        throw std::runtime_error("Invalid empty arguments");
    }

    if (!reader->dataSource || !reader->id) {
        throw std::runtime_error("Invalid empty input reader arguments");
    }

    //check fns
    if (!reader->open || !reader->read || !reader->seeko || !reader->tello
        || !reader->close || !reader->getError || !reader->getSize) {
            throw std::runtime_error("Reader callbacks not setup");
    }

    struct scalpelState state;

    std::string processorName ("scalpel_carveSingleInput()");
    char * args[5];
    args[0] = const_cast<char*> ( processorName.c_str());
    args[1] = reader->id;
    args[2] = const_cast<char*> (confFilePath);
    args[3] = const_cast<char*> (outDir);
    args[4] = 0;


    initializeState(args, &state);

    //setup input
    state.inReader = reader;

    //setup options
    const size_t outDirLen = strlen(outDir);
    strncpy(state.outputdirectory, outDir, outDirLen);
    state.outputdirectory[outDirLen] = 0;
    const size_t confFilePathLen = strlen(confFilePath);
    strncpy(state.conffile, confFilePath, confFilePathLen);
    state.conffile[confFilePathLen] = 0;
    state.generateHeaderFooterDatabase = generateFooterDb;
    state.handleEmbedded = handleEmbedded;
    state.organizeSubdirectories = organizeSubdirs;
    state.previewMode = previewMode;
    state.carveWithMissingFooters = carveWithMissingFooters;
    state.noSearchOverlap = noSearchOverlap;

    convertFileNames(&state);

    // read configuration file
    int err;
    if ((err = readSearchSpecFile(&state))) {
        // problem with config file
        handleError(&state, err); //can throw
        freeState(&state);
        std::stringstream ss;
        ss << "Error reading spec file, error code: " << err;
        throw std::runtime_error(ss.str());
    }

    // prepare audit file and make sure output directory is empty.
    if ((err = openAuditFile(&state))) {
        handleError(&state, err); //can throw
        freeState(&state);
        std::stringstream ss;
        ss << "Error opening audit file, error code: " << err;
        throw std::runtime_error(ss.str());
    }

    // Initialize the backing store of buffer to read-in, process image data.
    init_store();

    // Initialize threading model for cpu or gpu search.
    init_threading_model(&state);

    if ((err = digImageFile(&state))) {
        handleError(&state, err); //can throw
        closeAuditFile(state.auditFile);
        destroyStore();
        freeState(&state);
        std::stringstream ss;
        ss << "Error digging file, error code: " << err;
        throw std::runtime_error(ss.str());
    }

    if ((err = carveImageFile(&state))) {
        handleError(&state, err); //can throw
        closeAuditFile(state.auditFile);
        destroy_threading_model(&state);
        destroyStore();
        freeState(&state);
        std::stringstream ss;
        ss << "Error carving file, error code: " << err;
        throw std::runtime_error(ss.str());
    }

    closeAuditFile(state.auditFile);
    destroy_threading_model(&state);
    destroyStore();
    freeState(&state);

    return SCALPEL_OK;
}
Пример #16
0
bool ModelBaker::compressMesh(FBXMesh& mesh, bool hasDeformers, FBXNode& dracoMeshNode, GetMaterialIDCallback materialIDCallback) {
    if (mesh.wasCompressed) {
        handleError("Cannot re-bake a file that contains compressed mesh");
        return false;
    }

    Q_ASSERT(mesh.normals.size() == 0 || mesh.normals.size() == mesh.vertices.size());
    Q_ASSERT(mesh.colors.size() == 0 || mesh.colors.size() == mesh.vertices.size());
    Q_ASSERT(mesh.texCoords.size() == 0 || mesh.texCoords.size() == mesh.vertices.size());

    int64_t numTriangles{ 0 };
    for (auto& part : mesh.parts) {
        if ((part.quadTrianglesIndices.size() % 3) != 0 || (part.triangleIndices.size() % 3) != 0) {
            handleWarning("Found a mesh part with invalid index data, skipping");
            continue;
        }
        numTriangles += part.quadTrianglesIndices.size() / 3;
        numTriangles += part.triangleIndices.size() / 3;
    }

    if (numTriangles == 0) {
        return false;
    }

    draco::TriangleSoupMeshBuilder meshBuilder;

    meshBuilder.Start(numTriangles);

    bool hasNormals{ mesh.normals.size() > 0 };
    bool hasColors{ mesh.colors.size() > 0 };
    bool hasTexCoords{ mesh.texCoords.size() > 0 };
    bool hasTexCoords1{ mesh.texCoords1.size() > 0 };
    bool hasPerFaceMaterials = (materialIDCallback) ? (mesh.parts.size() > 1 || materialIDCallback(0) != 0 ) : true;
    bool needsOriginalIndices{ hasDeformers };

    int normalsAttributeID { -1 };
    int colorsAttributeID { -1 };
    int texCoordsAttributeID { -1 };
    int texCoords1AttributeID { -1 };
    int faceMaterialAttributeID { -1 };
    int originalIndexAttributeID { -1 };

    const int positionAttributeID = meshBuilder.AddAttribute(draco::GeometryAttribute::POSITION,
                                                             3, draco::DT_FLOAT32);
    if (needsOriginalIndices) {
        originalIndexAttributeID = meshBuilder.AddAttribute(
            (draco::GeometryAttribute::Type)DRACO_ATTRIBUTE_ORIGINAL_INDEX,
            1, draco::DT_INT32);
    }

    if (hasNormals) {
        normalsAttributeID = meshBuilder.AddAttribute(draco::GeometryAttribute::NORMAL,
                                                      3, draco::DT_FLOAT32);
    }
    if (hasColors) {
        colorsAttributeID = meshBuilder.AddAttribute(draco::GeometryAttribute::COLOR,
                                                     3, draco::DT_FLOAT32);
    }
    if (hasTexCoords) {
        texCoordsAttributeID = meshBuilder.AddAttribute(draco::GeometryAttribute::TEX_COORD,
                                                        2, draco::DT_FLOAT32);
    }
    if (hasTexCoords1) {
        texCoords1AttributeID = meshBuilder.AddAttribute(
            (draco::GeometryAttribute::Type)DRACO_ATTRIBUTE_TEX_COORD_1,
            2, draco::DT_FLOAT32);
    }
    if (hasPerFaceMaterials) {
        faceMaterialAttributeID = meshBuilder.AddAttribute(
            (draco::GeometryAttribute::Type)DRACO_ATTRIBUTE_MATERIAL_ID,
            1, draco::DT_UINT16);
    }

    auto partIndex = 0;
    draco::FaceIndex face;
    uint16_t materialID;
    
    for (auto& part : mesh.parts) {
        materialID = (materialIDCallback) ? materialIDCallback(partIndex) : partIndex;
        
        auto addFace = [&](QVector<int>& indices, int index, draco::FaceIndex face) {
            int32_t idx0 = indices[index];
            int32_t idx1 = indices[index + 1];
            int32_t idx2 = indices[index + 2];

            if (hasPerFaceMaterials) {
                meshBuilder.SetPerFaceAttributeValueForFace(faceMaterialAttributeID, face, &materialID);
            }

            meshBuilder.SetAttributeValuesForFace(positionAttributeID, face,
                                                  &mesh.vertices[idx0], &mesh.vertices[idx1],
                                                  &mesh.vertices[idx2]);

            if (needsOriginalIndices) {
                meshBuilder.SetAttributeValuesForFace(originalIndexAttributeID, face,
                                                      &mesh.originalIndices[idx0],
                                                      &mesh.originalIndices[idx1],
                                                      &mesh.originalIndices[idx2]);
            }
            if (hasNormals) {
                meshBuilder.SetAttributeValuesForFace(normalsAttributeID, face,
                                                      &mesh.normals[idx0], &mesh.normals[idx1],
                                                      &mesh.normals[idx2]);
            }
            if (hasColors) {
                meshBuilder.SetAttributeValuesForFace(colorsAttributeID, face,
                                                      &mesh.colors[idx0], &mesh.colors[idx1],
                                                      &mesh.colors[idx2]);
            }
            if (hasTexCoords) {
                meshBuilder.SetAttributeValuesForFace(texCoordsAttributeID, face,
                                                      &mesh.texCoords[idx0], &mesh.texCoords[idx1],
                                                      &mesh.texCoords[idx2]);
            }
            if (hasTexCoords1) {
                meshBuilder.SetAttributeValuesForFace(texCoords1AttributeID, face,
                                                      &mesh.texCoords1[idx0], &mesh.texCoords1[idx1],
                                                      &mesh.texCoords1[idx2]);
            }
        };

        for (int i = 0; (i + 2) < part.quadTrianglesIndices.size(); i += 3) {
            addFace(part.quadTrianglesIndices, i, face++);
        }

        for (int i = 0; (i + 2) < part.triangleIndices.size(); i += 3) {
            addFace(part.triangleIndices, i, face++);
        }

        partIndex++;
    }

    auto dracoMesh = meshBuilder.Finalize();

    if (!dracoMesh) {
        handleWarning("Failed to finalize the baking of a draco Geometry node");
        return false;
    }

    // we need to modify unique attribute IDs for custom attributes
    // so the attributes are easily retrievable on the other side
    if (hasPerFaceMaterials) {
        dracoMesh->attribute(faceMaterialAttributeID)->set_unique_id(DRACO_ATTRIBUTE_MATERIAL_ID);
    }

    if (hasTexCoords1) {
        dracoMesh->attribute(texCoords1AttributeID)->set_unique_id(DRACO_ATTRIBUTE_TEX_COORD_1);
    }

    if (needsOriginalIndices) {
        dracoMesh->attribute(originalIndexAttributeID)->set_unique_id(DRACO_ATTRIBUTE_ORIGINAL_INDEX);
    }

    draco::Encoder encoder;

    encoder.SetAttributeQuantization(draco::GeometryAttribute::POSITION, 14);
    encoder.SetAttributeQuantization(draco::GeometryAttribute::TEX_COORD, 12);
    encoder.SetAttributeQuantization(draco::GeometryAttribute::NORMAL, 10);
    encoder.SetSpeedOptions(0, 5);

    draco::EncoderBuffer buffer;
    encoder.EncodeMeshToBuffer(*dracoMesh, &buffer);

    FBXNode dracoNode;
    dracoNode.name = "DracoMesh";
    auto value = QVariant::fromValue(QByteArray(buffer.data(), (int)buffer.size()));
    dracoNode.properties.append(value);
    
    dracoMeshNode = dracoNode;
    // Mesh compression successful return true
    return true;
}
Пример #17
0
void Tabla :: noteOn( StkFloat instrument, StkFloat amplitude )
{
  if ( amplitude < 0.0 || amplitude > 1.0 ) {
    oStream_ << "Tabla::noteOn: amplitude parameter is out of bounds!";
    handleError( StkError::WARNING ); return;
  }

  int noteNumber = ( (int) instrument ) % 16;

  // If we already have a wave of this note number loaded, just reset
  // it.  Otherwise, look first for an unused wave or preempt the
  // oldest if already at maximum polyphony.
  int iWave;
  for ( iWave=0; iWave<TABLA_POLYPHONY; iWave++ ) {
    if ( soundNumber_[iWave] == noteNumber ) {
      if ( waves_[iWave].isFinished() ) {
        soundOrder_[iWave] = nSounding_;
        nSounding_++;
      }
      waves_[iWave].reset();
      filters_[iWave].setPole( 0.999 - (amplitude * 0.6) );
      filters_[iWave].setGain( amplitude );
      break;
    }
  }

  if ( iWave == TABLA_POLYPHONY ) { // This note number is not currently loaded.
    if ( nSounding_ < TABLA_POLYPHONY ) {
      for ( iWave=0; iWave<TABLA_POLYPHONY; iWave++ )
        if ( soundOrder_[iWave] < 0 ) break;
      nSounding_ += 1;
    }
    else {
      for ( iWave=0; iWave<TABLA_POLYPHONY; iWave++ )
        if ( soundOrder_[iWave] == 0 ) break;
      // Re-order the list.
      for ( int j=0; j<TABLA_POLYPHONY; j++ ) {
        if ( soundOrder_[j] > soundOrder_[iWave] )
          soundOrder_[j] -= 1;
      }
    }
    soundOrder_[iWave] = nSounding_ - 1;
    soundNumber_[iWave] = noteNumber;

    // Concatenate the rawwave path to the rawwave file
    waves_[iWave].openFile( (std::string("rawwaves/") + tablaWaves[ noteNumber ]).c_str(), true );
    if ( Stk::sampleRate() != 22050.0 )
      waves_[iWave].setRate( 22050.0 / Stk::sampleRate() );
    filters_[iWave].setPole( 0.999 - (amplitude * 0.6) );
    filters_[iWave].setGain( amplitude );
  }

  /*
#if defined(_STK_DEBUG_)
  oStream; errorStream << "Tabla::noteOn: number sounding = " << nSounding_ << '\n';
  for (int i=0; i<nSounding_; i++) oStream << soundNumber_[i] << "  ";
  oStream << '\n'; errorString_ = oStream.str();
  handleError( StkError::DEBUG_WARNING );
#endif
  */
}
Пример #18
0
// hlavna funkcia
int main (int argc, char **argv) {
	unsigned port;
	if ((port = handleArgs (argc, argv)) == -1) {
		handleError (WRONG_PARAMS, "wrong parameters on commandline");
	}

	int listenSocket;
	if((listenSocket = socket( PF_INET, SOCK_STREAM, 0)) < 0) {
		handleError(INTERNAL_ERROR, "cannot create socket");
	}

	sockaddr_in s1, s2;
	socklen_t s2Len = sizeof(s2);
	memset (&s1, 0, sizeof(s1));
	s1.sin_family = AF_INET;
	s1.sin_port = htons(port);
	s1.sin_addr.s_addr = INADDR_ANY;

	int tr = 1;
	if (setsockopt(listenSocket,SOL_SOCKET,SO_REUSEADDR,&tr,sizeof(int)) == -1) {
		close(listenSocket);
		handleError(INTERNAL_ERROR, "setsockopt failed");
	}

	if (bind( listenSocket, reinterpret_cast<sockaddr*>(&s1), sizeof(s1)) != 0) {
		close(listenSocket);
		handleError(INTERNAL_ERROR, "bind() failed");
	}

	if (listen(listenSocket, 0) != 0) {
		close(listenSocket);
		handleError(CONNECTION_FAILED, "listen() failed");
	}

	// otvorenie suboru s datami
	std::ifstream infile;
	infile.open(filename);
	infile.is_open(); 
	// nacitani suboru do vektoru
	std::string line;
	if (infile.is_open()) {
	while (getline(infile, line))
		fileCopy.push_back(line);
	}
	infile.close();

	// vytvoreni threadu pro signaly a mutexov
	pthread_t thread;
	pthread_attr_t attrt;
	pthread_attr_init (&attrt);
	pthread_attr_setdetachstate (&attrt, PTHREAD_CREATE_DETACHED);

	if (pthread_mutex_init (&dataMutex, NULL) != 0) {
		close (listenSocket);
		file.close();
		handleError(INTERNAL_ERROR, "mutex init failed");
	}
	size_t dataSocket;

	pthread_t sigThread;
	sigset_t set;
	int s;
	sigemptyset(&set);
	sigaddset(&set, SIGQUIT);
	sigaddset(&set, SIGINT);
	sigaddset(&set, SIGTERM);
	s = pthread_sigmask(SIG_BLOCK, &set, NULL);
	if (s != 0)
		handleError (INTERNAL_ERROR, "pthread_create");
	s = pthread_create(&sigThread, NULL, sigThreadCatch, &set);
	if (s != 0)
		handleError(INTERNAL_ERROR, "pthread_create");

	while (1) {
		dataSocket = accept(listenSocket, reinterpret_cast<sockaddr*>(&s2), &s2Len);
		if (dataSocket <= 0)
			continue;
		pthread_create (&thread, &attrt, handleConnection, &dataSocket);
	}
}
Пример #19
0
int main(void)
{

   int quit = 0;
   int timer = 0;

   // Set STDIN non-blocking (Still requires Return)
   int flags = fcntl(0, F_GETFL);
   flags |= O_NONBLOCK;
   fcntl(0, F_SETFL, flags);

   handleError("Couldn't open stdin.", 1);

   printf("---Press q and press return to quit---\n");
   printf("   Press another letter and return to start sending.\n");

   //POLLED_UAT Specific Stuff
   uint8_t puat;

// printf("A\n");
   for(puat=0; puat<NUMPUATS; puat++)
      puat_init(puat);

// printf("B\n");

   fflush(stdout);

   while(!quit)
   {
//    printf("OK\n");
      //This worked in 0.10-3! But now 0.10-4?!
//    handleError(" Unhandled Error.", 0);

      char kbChar;
      kbChar = getchar();

      //"Resource Temporarily Unavailable" isn't an error in this case
      if(errno == 35)
         errno = 0;
      else
      {
         switch(kbChar)
         {
            case 'q':
               quit = 1;
               break;
            //POLLED_UAT TESTS:
            case '\n':
               break;
            //^^^ TO HERE
            default:
               //Send Upper-case chars to puat 1
               //     Lower-case to puat 0
//             if((kbChar >= 'A') && (kbChar <= 'Z'))
//                puat = 1;
//             else
                  puat = 0;

               if(puat_dataWaiting(puat))
                  printf("Buffer[%d] Full; Ignoring '%c'\n", 
                        (int)puat, kbChar);
               else
                  puat_sendByte(puat,kbChar);
               //printf("Received: '%c'", kbChar);
         }
      }



//    if(puat_dataWaiting())
//    {
//       unsigned char byte = POLLED_UAT_getByte();
//       printf("POLLED_UAT Received: '%c'=0x%x\n", byte, (int)byte);
//    }

      timer++;

      if(timer == 100)
      {
         TCNT++;
         if(TCNT == TCNTER_SOURCE_OVERFLOW_VAL) //OCR0A)
            TCNT = 0;
         timer=0;

//       printf("TCNT=%d\n", TCNT);
      }

      static int lastTC = -1;

      if(TCNT != lastTC)
      {
         lastTC = TCNT;
         
         //This is just for tracking TCNT:
         //Again not certain if the DMS_OCR_VAL is *matched* and
         //transitions away to 0 or transitions to 0 upon match...
         if((TCNT%100 == 0) || (TCNT == 1599))
            printf("TCNT: %d\n",TCNT);
   
   
         //This simulates tcnter_update (via puat_update) calls that happen
         // spurradically
         if((TCNT%1000) == 0)
         {
            for(puat=0; puat<NUMPUATS; puat++)
               puat_update(puat);

            printf("tcnter=%d\n", tcnter_get());
         }
      }


   }


   return 0;
}
Пример #20
0
int main (int argc, char *argv[])
{
	char fStr[50];
	float version = 0.0;
	long error = 0;
	int i = 0;

	long idnum = -1;  //Using first found U12
	long demo = 0;  //Normal operations
	long channel = 0;  //Channel to be read/set.  Used by multiple functions.
	long state = 0;  //Digital states to set or states read.  Used by digital functions.

	//EAnalogOut specific parameters
	float analogOut0 = 2.0, analogOut1 = 3.5;  //Voltages of AO0 and AO1 to set

	//EAnalogIn specific parameters
	long gain = 0;  //G=1, +-20 V (gain 0 = 1)
	long overVoltage = 0;  //Returns >0 if overvoltage is detected
	float voltage = 0.0;  //Returns the voltage reading

	//EDigitalOut specific paramters
	long writeD = 0;  //Indicates if D line is to be written instead of IO line

	//EDigitalIn specific paramters
	long readD = 0;  //Indicates if D line is read instead of IO line

	//ECount specific parameters
	long resetCounter = 0;  //Indicates if counter is reset to zero after read
	double count = 0;  //Current count before reset
	double ms = 0;  //Returns the number of milliseconds since the Epoch.


	version = GetDriverVersion();
	printf("Driver version: %.3f\n", version);

	version = GetFirmwareVersion(&idnum);
	printf("U12 Firmware version: %.3f\n\n", version);


	/* Setting analog outputs */
	printf("Setting AO0 to %.3f V and AO1 to %.3f V.\n\n", analogOut0, analogOut1);

	error = EAnalogOut(&idnum, demo, 2.0, 3.5);
	handleError(error, "EAnalogOut");

	/* Reading analog inputs */
	printf("Reading some analog inputs:\n");

	/* Reading from single-ended AI0 and AI1 */
	for(i = 0; i < 2; i++)
	{
		channel = i;
		error = EAnalogIn(&idnum, demo, channel, gain, &overVoltage, &voltage);
		sprintf(fStr, "EAnalogIn (%ld)", channel);
		handleError(error, fStr);

		printf("Single-ended AI%ld = %.3f V, overVoltage = %ld\n", channel, voltage, overVoltage);
	}
	printf("\n");

	/* Reading from differential AI0-AI1 (channel 8) and AI2-AI3 (channel 9), G=1 (+-20 V) */
	for(i = 8; i < 10; i+=1)
	{
		channel = i;
		error = EAnalogIn(&idnum, demo, channel, gain, &overVoltage, &voltage);
		sprintf(fStr, "EAnalogIn (%ld) diff.", channel);
		handleError(error, fStr);

		printf("Differential AI%ld-AI%ld = %.3f V, overVoltage = %ld\n", (channel-8)*2, (channel-8)*2+1, voltage, overVoltage);
	}


	/* Setting digital outputs */
	printf("\nSetting digital lines IO1 and D1 to output-low, and IO2 to output-high\n\n");	

	channel = 1;
	writeD = 0;
	state = 0;
	error = EDigitalOut(&idnum, demo, channel, writeD, state);
	handleError(error, "EDigitalOut (IO1)");

	channel = 1;
	writeD = 1;
	state = 0;
	error = EDigitalOut(&idnum, demo, channel, writeD, state);
	handleError(error, "EDigitalOut (D1)");

	channel = 2;
	writeD = 0;
	state = 1;
	error = EDigitalOut(&idnum, demo, channel, writeD, state);
	handleError(error, "EDigitalOut (IO2)");


	/* Reading digital inputs */
	printf("Reading some digital inputs:\n");

	channel = 0;
	readD = 0;
	error = EDigitalIn(&idnum, demo, channel, readD, &state);
	handleError(error, "EDigitalIn (IO0)");
	printf("IO%ld state = %ld\n", channel, state);

	channel = 0;
	readD = 1;
	error = EDigitalIn(&idnum, demo, channel, readD, &state);
	handleError(error, "EDigitalIn (D0)");
	printf("D%ld state = %ld\n\n", channel, state);


	/* Read from the Counter */

	//Reseting counter first
	printf("Reading Counter:\nResetting count and waiting 2 seconds for new data.\n");

	resetCounter = 1;
	error = ECount(&idnum, demo, resetCounter, &count, &ms);
	handleError(error, "ECount (reset)");

	//Wait for 2 seconds for data
	usleep(2000000);

	//Read Counter reading with 2 second timer
	resetCounter = 0;
	error = ECount(&idnum, demo, resetCounter, &count, &ms);
	handleError(error, "ECount (read)");

	printf("Count = %.0f, OS timer = %0.3f ms\n", count, ms);

	return 0;
}
Пример #21
0
int Menu::runNoBlock(const int frame_tmp)
{
    int frame   = frame_tmp;
    int counter = 0;
    int mouseX, mouseY;
    int mouseClickX, mouseClickY;
    bool clicked;
    int status;

    if(this->music != NULL)
    {
        if(Mix_PlayMusic(this->music, -1) == -1)
        {
            handleError("In-game music disabled! Click OK for full error", false);
            handleError(Mix_GetError(), false);
        }
    }
    else if(this->music_chunk != NULL)
    {
        int channel = Mix_PlayChannel(-1, this->music_chunk, -1);
    }

    while(counter < frame && !this->quit)
    {
        counter++;
        this->eventHandler->handleMenuEvents(&this->quit, &mouseX, &mouseY,
            &mouseClickX, &mouseClickY, &clicked);

        this->checkMouseOver(mouseX, mouseY);

        /* Check where the user clicked */
        if(clicked)
            status = this->checkClick(mouseClickX, mouseClickY);
        else
            status = -1;

        if(status != -1)
        {
            if(this->buttons[status]->type == SUB_MENU)
            {
                if(this->buttons[status]->nextMenu->run() == -1)
                    return -1;
            }

            else if(this->buttons[status]->type == ACTION_MENU)
            {
                if(this->buttons[status]->action == QUIT_GAME)
                    return -1;
                else if(this->buttons[status]->action == RETURN_TO_LAST)
                    return 1;
                else if(this->buttons[status]->action == LOAD_GAME)
                    return 3;
                else if(this->buttons[status]->action == PLAY_GAME)
                {
                    Mix_HaltMusic();
                    return 0;
                }
                else if(this->buttons[status]->action == PLAY_MULTI_GAME)
                {
                    Mix_HaltMusic();
                    return 2;
                }
            }

            else if(this->buttons[status]->type == TOGGLE_MENU)
            {
                string tmp(this->buttons[status]->button_text);

                if(this->buttons[status]->switch_status)
                {
                    this->buttons[status]->switch_status = false;
                    tmp = tmp.substr(0, tmp.find("ON"));
                    tmp += "OFF";
                }
                else
                {
                    this->buttons[status]->switch_status = true;
                    tmp = tmp.substr(0, tmp.find("OFF"));
                    tmp += "ON";
                }

                delete[] this->buttons[status]->button_text;
                this->buttons[status]->button_text = new char[tmp.length() + 1];
                strncpy(this->buttons[status]->button_text, tmp.c_str(), tmp.length() + 1);

                if(this->centerText)
                {
                    this->buttons[status]->normalButton = renderMultiLineText(
                        this->font, tmp, this->hlColor, this->fgColor,
                        ALIGN_CENTER | TRANSPARENT_BG | CREATE_SURFACE);

                    this->buttons[status]->highlightedButton = renderMultiLineText(
                        this->font, tmp, this->fgColor, this->hlColor,
                        ALIGN_CENTER | TRANSPARENT_BG | CREATE_SURFACE);

                    this->buttons[status]->x = ((SCREEN_WIDTH / 2) - 
                        (this->buttons[status]->normalButton->clip_rect.w / 2));
                }

                else
                {
                    this->buttons[status]->normalButton = renderMultiLineText(
                        this->font, tmp, this->hlColor, this->fgColor,
                        TRANSPARENT_BG | CREATE_SURFACE);

                    this->buttons[status]->highlightedButton = renderMultiLineText(
                        this->font, tmp, this->fgColor, this->hlColor,
                        TRANSPARENT_BG | CREATE_SURFACE);
                }
            }
        }

        BLIT(this->bg, 0, 0);

        /* Display each menu option */
        for(unsigned int i=0; i < this->buttons.size(); i++)
        {
            BLIT(this->buttons[i]->displayButton,
                this->buttons[i]->x, 
                this->buttons[i]->y);
        }

        /* Update the screen */
        this->display->update();
    }

    /* This means that the user actually wants to
     * quit, not that we just broke out of the while()
     * loop with a break statement.
    */
    if(this->quit == true)
        return -1;
    else
        return 0;
}
Пример #22
0
void ScriptJob::run()
{
    m_mutex->lock();
    if ( !loadScript(&m_data.program) ) {
        kDebug() << "Script could not be loaded correctly";
        m_mutex->unlock();
        return;
    }

    QScriptEngine *engine = m_engine;
    ScriptObjects objects = m_objects;
    m_mutex->unlock();

    // Store start time of the script
    QElapsedTimer timer;
    timer.start();

    // Add call to the appropriate function
    QString functionName;
    QScriptValueList arguments = QScriptValueList() << request()->toScriptValue( engine );
    switch ( request()->parseMode() ) {
    case ParseForDepartures:
    case ParseForArrivals:
        functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETTIMETABLE;
        break;
    case ParseForJourneysByDepartureTime:
    case ParseForJourneysByArrivalTime:
        functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETJOURNEYS;
        break;
    case ParseForStopSuggestions:
        functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETSTOPSUGGESTIONS;
        break;
    case ParseForAdditionalData:
        functionName = ServiceProviderScript::SCRIPT_FUNCTION_GETADDITIONALDATA;
        break;
    default:
        kDebug() << "Parse mode unsupported:" << request()->parseMode();
        break;
    }

    if ( functionName.isEmpty() ) {
        // This should never happen, therefore no i18n
        handleError( "Unknown parse mode" );
        return;
    }

    // Check if the script function is implemented
    QScriptValue function = engine->globalObject().property( functionName );
    if ( !function.isFunction() ) {
        handleError( i18nc("@info/plain", "Function <icode>%1</icode> not implemented by "
                           "the script", functionName) );
        return;
    }

    // Call script function
    QScriptValue result = function.call( QScriptValue(), arguments );
    if ( engine->hasUncaughtException() ) {
        // TODO Get filename where the exception occured, maybe use ScriptAgent for that
        handleError( i18nc("@info/plain", "Error in script function <icode>%1</icode>, "
                           "line %2: <message>%3</message>.",
                           functionName, engine->uncaughtExceptionLineNumber(),
                           engine->uncaughtException().toString()) );
        return;
    }

    GlobalTimetableInfo globalInfo;
    globalInfo.requestDate = QDate::currentDate();
    globalInfo.delayInfoAvailable = !objects.result->isHintGiven( ResultObject::NoDelaysForStop );

    // The called function returned, but asynchronous network requests may have been started.
    // Wait for all network requests to finish, because slots in the script may get called
    if ( !waitFor(objects.network.data(), SIGNAL(allRequestsFinished()), WaitForNetwork) ) {
        return;
    }

    // Wait for script execution to finish
    ScriptAgent agent( engine );
    if ( !waitFor(&agent, SIGNAL(scriptFinished()), WaitForScriptFinish) ) {
        return;
    }

    // Update last download URL
    QMutexLocker locker( m_mutex );
    m_lastUrl = objects.network->lastUrl(); // TODO Store all URLs
    m_lastUserUrl = objects.network->lastUserUrl();

    // Inform about script run time
    DEBUG_ENGINE_JOBS( "Script finished in" << (timer.elapsed() / 1000.0)
            << "seconds: " << m_data.provider.scriptFileName() << request()->parseMode() );

    // If data for the current job has already been published, do not emit
    // xxxReady() with an empty resultset
    if ( m_published == 0 || m_objects.result->count() > m_published ) {
        const bool couldNeedForcedUpdate = m_published > 0;
        const MoreItemsRequest *moreItemsRequest =
                dynamic_cast< const MoreItemsRequest* >( request() );
        const AbstractRequest *_request =
                moreItemsRequest ? moreItemsRequest->request().data() : request();
        switch ( _request->parseMode() ) {
        case ParseForDepartures:
            emit departuresReady( m_objects.result->data().mid(m_published),
                    m_objects.result->features(), m_objects.result->hints(),
                    m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast<const DepartureRequest*>(_request),
                    couldNeedForcedUpdate );
            break;
        case ParseForArrivals: {
            emit arrivalsReady( m_objects.result->data().mid(m_published),
                    m_objects.result->features(), m_objects.result->hints(),
                    m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast< const ArrivalRequest* >(_request),
                    couldNeedForcedUpdate );
            break;
        }
        case ParseForJourneysByDepartureTime:
        case ParseForJourneysByArrivalTime:
            emit journeysReady( m_objects.result->data().mid(m_published),
                    m_objects.result->features(), m_objects.result->hints(),
                    m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast<const JourneyRequest*>(_request),
                    couldNeedForcedUpdate );
            break;
        case ParseForStopSuggestions:
            emit stopSuggestionsReady( m_objects.result->data().mid(m_published),
                    m_objects.result->features(), m_objects.result->hints(),
                    m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast<const StopSuggestionRequest*>(_request),
                    couldNeedForcedUpdate );
            break;

        case ParseForAdditionalData: {
            const QList< TimetableData > data = m_objects.result->data();
            if ( data.isEmpty() ) {
                handleError( i18nc("@info/plain", "Did not find any additional data.") );
                return;
            } else if ( data.count() > 1 ) {
                kWarning() << "The script added more than one result set, only the first gets used";
            }
            emit additionalDataReady( data.first(), m_objects.result->features(),
                    m_objects.result->hints(), m_objects.network->lastUserUrl(), globalInfo,
                    *dynamic_cast<const AdditionalDataRequest*>(_request),
                    couldNeedForcedUpdate );
            break;
        }

        default:
            kDebug() << "Parse mode unsupported:" << _request->parseMode();
            break;
        }
    }

    // Check for exceptions
    if ( m_engine->hasUncaughtException() ) {
        // TODO Get filename where the exception occured, maybe use ScriptAgent for that
        handleError( i18nc("@info/plain", "Error in script function <icode>%1</icode>, "
                            "line %2: <message>%3</message>.",
                            functionName, m_engine->uncaughtExceptionLineNumber(),
                            m_engine->uncaughtException().toString()) );
        return;
    }

    // Cleanup
    m_engine->deleteLater();
    m_engine = 0;
    m_objects.storage->checkLifetime();
    m_objects.clear();
}
Пример #23
0
int ChangePwd (const char *lpszVolume, Password *oldPassword, int old_pkcs5, int old_pim, BOOL truecryptMode, Password *newPassword, int pkcs5, int pim, int wipePassCount, HWND hwndDlg)
{
	int nDosLinkCreated = 1, nStatus = ERR_OS_ERROR;
	char szDiskFile[TC_MAX_PATH], szCFDevice[TC_MAX_PATH];
	char szDosDevice[TC_MAX_PATH];
	char buffer[TC_VOLUME_HEADER_EFFECTIVE_SIZE];
	PCRYPTO_INFO cryptoInfo = NULL, ci = NULL;
	void *dev = INVALID_HANDLE_VALUE;
	DWORD dwError;
	DWORD bytesRead;
	BOOL bDevice;
	unsigned __int64 hostSize = 0;
	int volumeType;
	int wipePass;
	FILETIME ftCreationTime;
	FILETIME ftLastWriteTime;
	FILETIME ftLastAccessTime;
	BOOL bTimeStampValid = FALSE;
	LARGE_INTEGER headerOffset;
	BOOL backupHeader;
	DISK_GEOMETRY driveInfo;

	if (oldPassword->Length == 0 || newPassword->Length == 0) return -1;

	if ((wipePassCount <= 0) || (truecryptMode && (old_pkcs5 == SHA256)))
	{
      nStatus = ERR_PARAMETER_INCORRECT;
      handleError (hwndDlg, nStatus, SRC_POS);
      return nStatus;
	}

   if (!lpszVolume)
   {
      nStatus = ERR_OUTOFMEMORY;
      handleError (hwndDlg, nStatus, SRC_POS);
      return nStatus;
   }

	WaitCursor ();

	CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), lpszVolume, &bDevice);

	if (bDevice == FALSE)
	{
		strcpy (szCFDevice, szDiskFile);
	}
	else
	{
		nDosLinkCreated = FakeDosNameForDevice (szDiskFile, szDosDevice, sizeof(szDosDevice), szCFDevice, sizeof(szCFDevice),FALSE);
		
		if (nDosLinkCreated != 0)
			goto error;
	}

	dev = CreateFile (szCFDevice, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);

	if (dev == INVALID_HANDLE_VALUE) 
		goto error;

	if (bDevice)
	{
		/* This is necessary to determine the hidden volume header offset */

		if (dev == INVALID_HANDLE_VALUE)
		{
			goto error;
		}
		else
		{
			PARTITION_INFORMATION diskInfo;
			DWORD dwResult;
			BOOL bResult;

			bResult = DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0,
				&driveInfo, sizeof (driveInfo), &dwResult, NULL);

			if (!bResult)
				goto error;

			bResult = GetPartitionInfo (lpszVolume, &diskInfo);

			if (bResult)
			{
				hostSize = diskInfo.PartitionLength.QuadPart;
			}
			else
			{
				hostSize = driveInfo.Cylinders.QuadPart * driveInfo.BytesPerSector *
					driveInfo.SectorsPerTrack * driveInfo.TracksPerCylinder;
			}

			if (hostSize == 0)
			{
				nStatus = ERR_VOL_SIZE_WRONG;
				goto error;
			}
		}
	}
	else
	{
		LARGE_INTEGER fileSize;
		if (!GetFileSizeEx (dev, &fileSize))
		{
			nStatus = ERR_OS_ERROR;
			goto error;
		}

		hostSize = fileSize.QuadPart;
	}

	if (Randinit ())
	{
		if (CryptoAPILastError == ERROR_SUCCESS)
			nStatus = ERR_RAND_INIT_FAILED;
		else
			nStatus = ERR_CAPI_INIT_FAILED;
		goto error;
	}

	SetRandomPoolEnrichedByUserStatus (FALSE); /* force the display of the random enriching dialog */

	if (!bDevice && bPreserveTimestamp)
	{
		if (GetFileTime ((HANDLE) dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime) == 0)
			bTimeStampValid = FALSE;
		else
			bTimeStampValid = TRUE;
	}

	for (volumeType = TC_VOLUME_TYPE_NORMAL; volumeType < TC_VOLUME_TYPE_COUNT; volumeType++)
	{
		// Seek the volume header
		switch (volumeType)
		{
		case TC_VOLUME_TYPE_NORMAL:
			headerOffset.QuadPart = TC_VOLUME_HEADER_OFFSET;
			break;

		case TC_VOLUME_TYPE_HIDDEN:
			if (TC_HIDDEN_VOLUME_HEADER_OFFSET + TC_VOLUME_HEADER_SIZE > hostSize)
				continue;

			headerOffset.QuadPart = TC_HIDDEN_VOLUME_HEADER_OFFSET;
			break;

		}

		if (!SetFilePointerEx ((HANDLE) dev, headerOffset, NULL, FILE_BEGIN))
		{
			nStatus = ERR_OS_ERROR;
			goto error;
		}

		/* Read in volume header */
		if (!ReadEffectiveVolumeHeader (bDevice, dev, buffer, &bytesRead))
		{
			nStatus = ERR_OS_ERROR;
			goto error;
		}

		if (bytesRead != sizeof (buffer))
		{
			// Windows may report EOF when reading sectors from the last cluster of a device formatted as NTFS 
			memset (buffer, 0, sizeof (buffer));
		}

		/* Try to decrypt the header */

		nStatus = ReadVolumeHeader (FALSE, buffer, oldPassword, old_pkcs5, old_pim, truecryptMode, &cryptoInfo, NULL);
		if (nStatus == ERR_CIPHER_INIT_WEAK_KEY)
			nStatus = 0;	// We can ignore this error here

		if (nStatus == ERR_PASSWORD_WRONG)
		{
			continue;		// Try next volume type
		}
		else if (nStatus != 0)
		{
			cryptoInfo = NULL;
			goto error;
		}
		else 
			break;
	}

	if (nStatus != 0)
	{
		cryptoInfo = NULL;
		goto error;
	}

	if (cryptoInfo->HeaderFlags & TC_HEADER_FLAG_ENCRYPTED_SYSTEM)
	{
		nStatus = ERR_SYS_HIDVOL_HEAD_REENC_MODE_WRONG;
		goto error;
	}

	// Change the PKCS-5 PRF if requested by user
	if (pkcs5 != 0)
		cryptoInfo->pkcs5 = pkcs5;

	RandSetHashFunction (cryptoInfo->pkcs5);

	NormalCursor();
	UserEnrichRandomPool (hwndDlg);
	EnableElevatedCursorChange (hwndDlg);
	WaitCursor();

	/* Re-encrypt the volume header */ 
	backupHeader = FALSE;

	while (TRUE)
	{
		/* The header will be re-encrypted wipePassCount times to prevent adversaries from using 
		techniques such as magnetic force microscopy or magnetic force scanning tunnelling microscopy
		to recover the overwritten header. According to Peter Gutmann, data should be overwritten 22
		times (ideally, 35 times) using non-random patterns and pseudorandom data. However, as users might
		impatiently interupt the process (etc.) we will not use the Gutmann's patterns but will write the
		valid re-encrypted header, i.e. pseudorandom data, and there will be many more passes than Guttman
		recommends. During each pass we will write a valid working header. Each pass will use the same master
		key, and also the same header key, secondary key (XTS), etc., derived from the new password. The only
		item that will be different for each pass will be the salt. This is sufficient to cause each "version"
		of the header to differ substantially and in a random manner from the versions written during the
		other passes. */

		for (wipePass = 0; wipePass < wipePassCount; wipePass++)
		{
			// Prepare new volume header
			nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE,
				buffer,
				cryptoInfo->ea,
				cryptoInfo->mode,
				newPassword,
				cryptoInfo->pkcs5,
				pim,
				cryptoInfo->master_keydata,
				&ci,
				cryptoInfo->VolumeSize.Value,
				(volumeType == TC_VOLUME_TYPE_HIDDEN) ? cryptoInfo->hiddenVolumeSize : 0,
				cryptoInfo->EncryptedAreaStart.Value,
				cryptoInfo->EncryptedAreaLength.Value,
				truecryptMode? 0 : cryptoInfo->RequiredProgramVersion,
				cryptoInfo->HeaderFlags,
				cryptoInfo->SectorSize,
				wipePass < wipePassCount - 1);

			if (ci != NULL)
				crypto_close (ci);

			if (nStatus != 0)
				goto error;

			if (!SetFilePointerEx ((HANDLE) dev, headerOffset, NULL, FILE_BEGIN))
			{
				nStatus = ERR_OS_ERROR;
				goto error;
			}

			if (!WriteEffectiveVolumeHeader (bDevice, dev, buffer))
			{
				nStatus = ERR_OS_ERROR;
				goto error;
			}

			if (bDevice
				&& !cryptoInfo->LegacyVolume
				&& !cryptoInfo->hiddenVolume
				&& cryptoInfo->HeaderVersion == 4
				&& (cryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC) != 0
				&& (cryptoInfo->HeaderFlags & ~TC_HEADER_FLAG_NONSYS_INPLACE_ENC) == 0)
			{
				nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, cryptoInfo, cryptoInfo->VolumeSize.Value, !backupHeader, backupHeader);
				if (nStatus != ERR_SUCCESS)
					goto error;
			}

			FlushFileBuffers (dev);
		}

		if (backupHeader || cryptoInfo->LegacyVolume)
			break;
			
		backupHeader = TRUE;
		headerOffset.QuadPart += hostSize - TC_VOLUME_HEADER_GROUP_SIZE;
	}

	/* Password successfully changed */
	nStatus = 0;

error:
	dwError = GetLastError ();

	burn (buffer, sizeof (buffer));

	if (cryptoInfo != NULL)
		crypto_close (cryptoInfo);

	if (bTimeStampValid)
		SetFileTime (dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime);

	if (dev != INVALID_HANDLE_VALUE)
		CloseHandle ((HANDLE) dev);

	if (nDosLinkCreated == 0)
		RemoveFakeDosName (szDiskFile, szDosDevice);

	RandStop (FALSE);
	NormalCursor ();

	SetLastError (dwError);

	if (nStatus == ERR_OS_ERROR && dwError == ERROR_ACCESS_DENIED
		&& bDevice
		&& !UacElevated
		&& IsUacSupported ())
		return nStatus;

	if (nStatus != 0)
		handleError (hwndDlg, nStatus, SRC_POS);

	return nStatus;
}
Пример #24
0
PlayerWidget::PlayerWidget( int index, Database *database,
                            ControlWidget *controlWidget, Qt::WindowFlags flags )
: QWidget( controlWidget, flags )
, mPlayer( index )
, mpDatabase( database )
, mpControlWidget( controlWidget )
, mpScrollLine( new ScrollLine( this ) )
, mpStatusDisplay( new QLabel( this ) )
, mpTimeDisplay( new QLabel( this ) )
, mpPlayPosition( new TimeSlider( Qt::Horizontal, this ) )
, mpSocket( new QTcpSocket( this ) )
, mpFSM( new PlayerFSM( this ) )
, mStartOther( false )
, mAutoPlay( false )
, mTotalTime( 0 )
, mFrequency( 44100 )
, mSamples( 0 )
, mHeadStart( 10 )
, mUpdateSlider( true )
, mKioskMode( false )
, mDisplayPattern()
, mTrackInfo()
{
   QVBoxLayout *mainLayout = new QVBoxLayout( this );

   mainLayout->setContentsMargins( 0, 0, 0, 0 );
   mainLayout->setSpacing( 5 );
   mainLayout->addWidget( mpScrollLine );
   mainLayout->addWidget( mpTimeDisplay );
   mainLayout->addWidget( mpStatusDisplay );
   mainLayout->addWidget( mpPlayPosition );
   setLayout( mainLayout );

   mpStatusDisplay->setAlignment( Qt::AlignLeft );
   mpStatusDisplay->setFrameShape( QFrame::Box );
   mpStatusDisplay->setContextMenuPolicy( Qt::CustomContextMenu );
   mpStatusDisplay->setObjectName( QString("StatusLabel") );
   mpTimeDisplay->setAlignment( Qt::AlignRight );
   mpTimeDisplay->setFrameShape( QFrame::Box );
   mpTimeDisplay->setObjectName( QString("TimeLabel") );
   mpPlayPosition->setTickPosition( QSlider::TicksBelow );
   mpPlayPosition->setTickInterval( 60 );
   mpPlayPosition->setMaximum( 1 );

   connect( mpSocket, SIGNAL(connected()),
            this, SLOT(handleConnect()) );
   connect( mpSocket, SIGNAL(disconnected()),
            this, SLOT(handleDisconnect()) );
   connect( mpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(handleError(QAbstractSocket::SocketError)) );
   connect( mpSocket, SIGNAL(readyRead()),
            this, SLOT(handleResponse()) );

   connect( mpPlayPosition, SIGNAL(sliderPressed()),
            this, SLOT(lock()) );
   connect( mpPlayPosition, SIGNAL(sliderReleased()),
            this, SLOT(seek()) );
   connect( mpPlayPosition, SIGNAL(actionTriggered(int)),
            this, SLOT(playPosChange(int)) );
   connect( mpStatusDisplay, SIGNAL(customContextMenuRequested(QPoint)),
            this, SLOT(unload()) );

   mpFSM->changeState( PlayerFSM::disconnected );
}
Пример #25
0
void Serial::processSerial()
{
    connect(SerialPort,SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(handleError(QSerialPort::SerialPortError)));
    connect(SerialPort, SIGNAL(readyRead()),this,SLOT(ReadSerial()));
}
Пример #26
0
void Connection::onTimeout(const boost::system::error_code& error)
{
    if(error != asio::error::operation_aborted)
        handleError(asio::error::timed_out);
}
Пример #27
0
BOOL CALLBACK ExpandVolProgressDlgProc (HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static EXPAND_VOL_THREAD_PARAMS *pProgressDlgParam;
	static BOOL bVolTransformStarted = FALSE;
	static BOOL showRandPool = TRUE;

	WORD lw = LOWORD (wParam);

	switch (msg)
	{
	case WM_INITDIALOG:
		{
			wchar_t szOldHostSize[512], szNewHostSize[512];

			pProgressDlgParam = (EXPAND_VOL_THREAD_PARAMS*)lParam;
			bVolTransformStarted = FALSE;
			showRandPool = TRUE;

			hCurPage = hwndDlg;
			nPbar = IDC_PROGRESS_BAR;

			GetSpaceString(szOldHostSize,sizeof(szOldHostSize),pProgressDlgParam->oldSize,pProgressDlgParam->bIsDevice);
			GetSpaceString(szNewHostSize,sizeof(szNewHostSize),pProgressDlgParam->newSize,pProgressDlgParam->bIsDevice);

			SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_OLDSIZE), szOldHostSize);
			SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NEWSIZE), szNewHostSize);
			SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_NAME), pProgressDlgParam->szVolumeName);
			SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_FILE_SYSTEM), szFileSystemStr[pProgressDlgParam->FileSystem]);
			SetWindowText (GetDlgItem (hwndDlg, IDC_EXPAND_VOLUME_INITSPACE), pProgressDlgParam->bInitFreeSpace?L"Yes":L"No");

			SendMessage (GetDlgItem (hwndDlg, IDC_BOX_STATUS), WM_SETFONT, (WPARAM) hBoldFont, (LPARAM) TRUE);

			SendMessage (GetDlgItem (hwndDlg, IDC_RANDOM_BYTES), WM_SETFONT, (WPARAM) hFixedDigitFont, (LPARAM) TRUE);

			// set status text
			if ( !pProgressDlgParam->bInitFreeSpace && pProgressDlgParam->bIsLegacy )
			{
				showRandPool = FALSE;
				EnableWindow (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS), FALSE);
				EnableWindow (GetDlgItem (hwndDlg, IDC_RANDOM_BYTES), FALSE);
				SetDlgItemText(hwndDlg, IDC_BOX_STATUS, L"Click 'Continue' to expand the volume.");
			}
			else
			{
				SetDlgItemText(hwndDlg, IDC_BOX_STATUS, L"IMPORTANT: Move your mouse as randomly as possible within this window. The longer you move it, the better. This significantly increases the cryptographic strength of the encryption keys. Then click 'Continue' to expand the volume.");
			}

			SendMessage (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS), BM_SETCHECK, showRandPool ? BST_CHECKED : BST_UNCHECKED, 0);
			SetTimer (hwndDlg, TIMER_ID_RANDVIEW, TIMER_INTERVAL_RANDVIEW, NULL);
		}
		return 0;
	case TC_APPMSG_VOL_TRANSFORM_THREAD_ENDED:
		{
			int nStatus = (int)lParam;

			NormalCursor ();
			if (nStatus != 0)
			{
				if ( nStatus != ERR_USER_ABORT )
					AddProgressDlgStatus (hwndDlg, L"Error: volume expansion failed.");
				else
					AddProgressDlgStatus (hwndDlg, L"Error: operation aborted by user.");
			}
			else
			{
				AddProgressDlgStatus (hwndDlg, L"Finished. Volume successfully expanded.");
			}

			SetWindowText (GetDlgItem (hwndDlg, IDOK), L"Exit");
			EnableWindow (GetDlgItem (hwndDlg, IDOK), TRUE);
			EnableWindow (GetDlgItem (hwndDlg, IDCANCEL), FALSE);
		}
		return 1;

	case WM_TIMER:

		switch (wParam)
		{
		case TIMER_ID_RANDVIEW:
			{
				unsigned char tmp[16] = {0};
				wchar_t szRndPool[64] = {0};

				if (!showRandPool)
					return 1;

				RandpeekBytes (hwndDlg, tmp, sizeof (tmp));

				StringCbPrintfW (szRndPool, sizeof(szRndPool), L"%08X%08X%08X%08X", 
					*((DWORD*) (tmp + 12)), *((DWORD*) (tmp + 8)), *((DWORD*) (tmp + 4)), *((DWORD*) (tmp)));

				SetWindowText (GetDlgItem (hwndDlg, IDC_RANDOM_BYTES), szRndPool);

				burn (tmp, sizeof(tmp));
				burn (szRndPool, sizeof(szRndPool));
			}
			return 1;
		}
		return 0;

	case WM_COMMAND:
		if (lw == IDC_DISPLAY_POOL_CONTENTS)
		{
			showRandPool = IsButtonChecked (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS));
			return 1;
		}
		if (lw == IDCANCEL)
		{
			if (bVolTransformStarted)
			{
				if (MessageBoxW (hwndDlg, L"Warning: Volume expansion is in progress!\n\nStopping now may result in a damaged volume.\n\nDo you really want to cancel?", lpszTitle, YES_NO|MB_ICONQUESTION|MB_DEFBUTTON2) == IDNO)
					return 1;

				// tell the volume transform thread to terminate
				bVolTransformThreadCancel = TRUE;
			}
			EndDialog (hwndDlg, lw);
			return 1;
		}

		if (lw == IDOK)
		{
			if (bVolTransformStarted)
			{
				// TransformThreadFunction finished -> OK button is now exit
				EndDialog (hwndDlg, lw);
			}
			else
			{
				showRandPool = FALSE;
				KillTimer (hwndDlg, TIMER_ID_RANDVIEW);
				EnableWindow (GetDlgItem (hwndDlg, IDC_DISPLAY_POOL_CONTENTS), FALSE);
				EnableWindow (GetDlgItem (hwndDlg, IDOK), FALSE);
				SetProgressDlgStatus (hwndDlg, L"Starting volume expansion ...\r\n");
				bVolTransformStarted = TRUE;
				pProgressDlgParam->hwndDlg = hwndDlg;
				if ( _beginthread (volTransformThreadFunction, 0, pProgressDlgParam) == -1L )
				{
					handleError (hwndDlg, ERR_OS_ERROR, SRC_POS);
					EndDialog (hwndDlg, lw);
				}
				WaitCursor();
			}
			return 1;
		}

		return 0;
	}

	return 0;
}
Пример #28
0
int libscalpel_initialize(scalpelState ** state, char * confFilePath, 
                          char * outDir, const scalpelState & options)
{
    std::string funcname("libscalpel_initialize");

    if (state == NULL)
        throw std::runtime_error(funcname + ": state argument must not be NULL.");

    if (*state != NULL)
        throw std::runtime_error(funcname + ": state has already been allocated.");

    if (outDir == NULL || strlen(outDir) == 0)
        throw std::runtime_error(funcname + ": no output directory provided.");

    if (confFilePath == NULL || strlen(confFilePath) == 0)
        throw std::runtime_error(funcname + ": no configuration file path provided.");

    scalpelState * pState = new scalpelState(options);

    char * argv[3];
    argv[0] = confFilePath;
    argv[1] = outDir;
    argv[2] = NULL;

    initializeState(&argv[0], pState);

    const size_t outDirLen = strlen(outDir);
    strncpy(pState->outputdirectory, outDir, outDirLen + 1);
    pState->outputdirectory[outDirLen + 1] = 0;
    const size_t confFilePathLen = strlen(confFilePath);
    strncpy(pState->conffile, confFilePath, confFilePathLen + 1);
    pState->conffile[confFilePathLen + 1] = 0;

    convertFileNames(pState);

    int err = 0;

    // prepare audit file and make sure output directory is empty.
    if ((err = openAuditFile(pState))) {
        handleError(pState, err); //can throw
        std::stringstream ss;
        ss << ": Error opening audit file, error code: " << err;
        throw std::runtime_error(funcname + ss.str());
    }

    // read configuration file
    if ((err = readSearchSpecFile(pState))) {
        // problem with config file
        handleError(pState, err); //can throw
        std::stringstream ss;
        ss << ": Error reading spec file, error code: " << err;
        throw std::runtime_error(funcname + ss.str());
    }

    // Initialize the backing store of buffer to read-in, process image data.
    init_store();

    // Initialize threading model for cpu or gpu search.
    init_threading_model(pState);

    *state = pState;

    return SCALPEL_OK;
}
Пример #29
0
MidiFileIn :: MidiFileIn( std::string fileName )
{
    // Attempt to open the file.
    file_.open( fileName.c_str(), std::ios::in );
    if ( !file_ ) {
        errorString_ << "MidiFileIn: error opening or finding file (" <<  fileName << ").";
        handleError( StkError::FILE_NOT_FOUND );
    }

    // Parse header info.
    char chunkType[4];
    char buffer[4];
    SINT32 *length;
    if ( !file_.read( chunkType, 4 ) ) goto error;
    if ( !file_.read( buffer, 4 ) ) goto error;
#ifdef __LITTLE_ENDIAN__
    swap32((unsigned char *)&buffer);
#endif
    length = (SINT32 *) &buffer;
    if ( strncmp( chunkType, "MThd", 4 ) || ( *length != 6 ) ) {
        errorString_ << "MidiFileIn: file (" <<  fileName << ") does not appear to be a MIDI file!";
        handleError( StkError::FILE_UNKNOWN_FORMAT );
    }

    // Read the MIDI file format.
    SINT16 *data;
    if ( !file_.read( buffer, 2 ) ) goto error;
#ifdef __LITTLE_ENDIAN__
    swap16((unsigned char *)&buffer);
#endif
    data = (SINT16 *) &buffer;
    if ( *data < 0 || *data > 2 ) {
        errorString_ << "MidiFileIn: the file (" <<  fileName << ") format is invalid!";
        handleError( StkError::FILE_ERROR );
    }
    format_ = *data;

    // Read the number of tracks.
    if ( !file_.read( buffer, 2 ) ) goto error;
#ifdef __LITTLE_ENDIAN__
    swap16((unsigned char *)&buffer);
#endif
    if ( format_ == 0 && *data != 1 ) {
        errorString_ << "MidiFileIn: invalid number of tracks (>1) for a file format = 0!";
        handleError( StkError::FILE_ERROR );
    }
    nTracks_ = *data;

    // Read the beat division.
    if ( !file_.read( buffer, 2 ) ) goto error;
#ifdef __LITTLE_ENDIAN__
    swap16((unsigned char *)&buffer);
#endif
    division_ = (int) *data;
    double tickrate;
    usingTimeCode_ = false;
    if ( *data & 0x8000 ) {
        // Determine ticks per second from time-code formats.
        tickrate = (double) -(*data & 0x7F00);
        // If frames per second value is 29, it really should be 29.97.
        if ( tickrate == 29.0 ) tickrate = 29.97;
        tickrate *= (*data & 0x00FF);
        usingTimeCode_ = true;
    }
    else {
        tickrate = (double) (*data & 0x7FFF); // ticks per quarter note
    }

    // Now locate the track offsets and lengths.  If not using time
    // code, we can initialize the "tick time" using a default tempo of
    // 120 beats per minute.  We will then check for tempo meta-events
    // afterward.
    for ( unsigned int i=0; i<nTracks_; i++ ) {
        if ( !file_.read( chunkType, 4 ) ) goto error;
        if ( strncmp( chunkType, "MTrk", 4 ) ) goto error;
        if ( !file_.read( buffer, 4 ) ) goto error;
#ifdef __LITTLE_ENDIAN__
        swap32((unsigned char *)&buffer);
#endif
        length = (SINT32 *) &buffer;
        trackLengths_.push_back( *length );
        trackOffsets_.push_back( (long) file_.tellg() );
        trackPointers_.push_back( (long) file_.tellg() );
        trackStatus_.push_back( 0 );
        file_.seekg( *length, std::ios_base::cur );
        if ( usingTimeCode_ ) tickSeconds_.push_back( (double) (1.0 / tickrate) );
        else tickSeconds_.push_back( (double) (0.5 / tickrate) );
    }

    // Save the initial tickSeconds parameter.
    TempoChange tempoEvent;
    tempoEvent.count = 0;
    tempoEvent.tickSeconds = tickSeconds_[0];
    tempoEvents_.push_back( tempoEvent );

    // If format 1 and not using time code, parse and save the tempo map
    // on track 0.
    if ( format_ == 1 && !usingTimeCode_ ) {
        std::vector<unsigned char> event;
        unsigned long value, count;

        // We need to temporarily change the usingTimeCode_ value here so
        // that the getNextEvent() function doesn't try to check the tempo
        // map (which we're creating here).
        usingTimeCode_ = true;
        count = getNextEvent( &event, 0 );
        while ( event.size() ) {
            if ( ( event.size() == 6 ) && ( event[0] == 0xff ) &&
                    ( event[1] == 0x51 ) && ( event[2] == 0x03 ) ) {
                tempoEvent.count = count;
                value = ( event[3] << 16 ) + ( event[4] << 8 ) + event[5];
                tempoEvent.tickSeconds = (double) (0.000001 * value / tickrate);
                if ( count > tempoEvents_.back().count )
                    tempoEvents_.push_back( tempoEvent );
                else
                    tempoEvents_.back() = tempoEvent;
            }
            count += getNextEvent( &event, 0 );
        }
        rewindTrack( 0 );
        for ( unsigned int i=0; i<nTracks_; i++ ) {
            trackCounters_.push_back( 0 );
            trackTempoIndex_.push_back( 0 );
        }
        // Change the time code flag back!
        usingTimeCode_ = false;
    }

    return;

error:
    errorString_ << "MidiFileIn: error reading from file (" <<  fileName << ").";
    handleError( StkError::FILE_ERROR );
}
Пример #30
0
void Transaction::runBatch(QSqlQuery &query)
{
    if(query.execBatch() == false)
        handleError(query);
}