Пример #1
0
const char *jsonParse(PJsonObject object,const char *jsonString){
    if(*jsonString=='{'){
        jsonString++;
        jsonString=getItem(object,jsonString);
    }else if(*jsonString=='['){
        jsonString++;
        object->type=ARRAY;
        jsonString=getArrayItem(object,jsonString);
    }else{
        showErrorMessage(jsonString,NO_START);
    }
    if(*jsonString!=']'&&*jsonString!='}')
        showErrorMessage(jsonString,NO_END);
    jsonString++;
    return jsonString;
}
Пример #2
0
static const char *getKey(PJsonObject object,const char *jsonString){
    int size=0;
    const char *tmp=jsonString;
    char *key=NULL;
    while(*tmp!='\"'&&tmp){
        size++;
        tmp++;
    }
    size++;
    if(size==1){
        //print error message that there is no key.
        showErrorMessage(jsonString,NO_KEY);
    }else{
        char *value=(char*)malloc(size*sizeof(char));
        key=value;
        while(*jsonString!='\"'&&jsonString){
            *value=*jsonString;
            value++;
            jsonString++;
        }
        jsonString++;
        *value++='\0';
    }
    object->key=key;
    return jsonString;
}
Пример #3
0
/*
** This function adjusts the cluster map if the file format is FAT32. FAT32 uses logical clusters
** so it is required that the cluster map be adjusted to physical from logical.
*/
void adjustForFAT32(void)
{
	// Read the boot sector if FAT and adjust the cluster map.
	if (fileFormatName[0] == L'F' && fileFormatName[1] == L'A' && fileFormatName[2] == L'T')
	{

		// Open the drive.
		HANDLE device = CreateFile(openDrivePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
		if (device == INVALID_HANDLE_VALUE)
		{
			showErrorMessage(GetLastError());
			exit(30);
		}

		/* Read the boot sector. */
		BOOTSECTOR bs;
		DWORD bytesRead;
		ReadFile(device, &bs, bytesPerSect, &bytesRead, NULL);

		/* Do the calculations. */
		DWORD rootByteOffset = (bs.bpb.reservedSectorCount + bs.ebpb.logicalSectorsPerFat * 2) * bytesPerSect;

		// VERY TEMP
		LARGE_INTEGER seek, there;
		seek.LowPart = rootByteOffset;
		seek.HighPart = 0;
		SetFilePointerEx(device, seek, &there, FILE_BEGIN);

//		DIRECTORY_ENTRY de[512/sizeof(DIRECTORY_ENTRY)];
//		ReadFile(device, de, bytesPerSect, &bytesRead, NULL);

		/* Very important to close the file (really the actually device). */
		CloseHandle(device);

		DWORD sectorOffsetOfRootDirectory = bs.bpb.reservedSectorCount + bs.ebpb.logicalSectorsPerFat * 2;
		DWORD clustersToAddToExtent = sectorOffsetOfRootDirectory / sectPerClust;

		/* Adjust all clusters. */
		for (int i = 0; i < VCN; i++)
		{
			/* Large FAT32 USB devices may have >= 16 sectors per cluster in the data area. */
			if (bs.bpb.sectorsPerCluster == 16)
			{
				buffer[i] *= 2;
			}
			else if (bs.bpb.sectorsPerCluster == 24)
			{
				buffer[i] *= 3;
			}
			else if (bs.bpb.sectorsPerCluster == 32)
			{
				buffer[i] *= 4;
			}
			buffer[i] += clustersToAddToExtent;
		}
	}

}
Пример #4
0
void DirLister::handleError(KIO::Job *job)
{
    if (!autoErrorHandlingEnabled()) {
        emit showErrorMessage(job->errorString());
        return;
    }

    KDirLister::handleError(job);
}
Пример #5
0
//------------------------------------------------------------------------------
bool SqlQuery::exec()
{
    if (!QSqlQuery::exec()) {
        showErrorMessage();
        return false;
    }
    else {
        return true;
    }
}
Пример #6
0
void PinDialog::accept()
{
    if (m_type == PinPuk) {
        if (pin() != pin2()) {
            showErrorMessage(PinCodesDoNotMatch);
            return;
        } else if (puk().length() < 8) {
            showErrorMessage(PukCodeTooShort);
            return;
        }
    }

    if (pin().length() < 4) {
        showErrorMessage(PinCodeTooShort);
        return;
    }

    QDialog::accept();
}
Пример #7
0
void Exchange_BitCurex::sendToApi(int reqType, QByteArray method, bool auth, QByteArray hashData, QByteArray postData)
{
	if(julyHttp==0)
	{ 
        julyHttp=new JulyHttp("api.bitcurex.com","Key: "+getApiKey()+"\r\n",this,true);
		connect(julyHttp,SIGNAL(anyDataReceived()),baseValues_->mainWindow_,SLOT(anyDataReceived()));
		connect(julyHttp,SIGNAL(apiDown(bool)),baseValues_->mainWindow_,SLOT(setApiDown(bool)));
		connect(julyHttp,SIGNAL(setDataPending(bool)),baseValues_->mainWindow_,SLOT(setDataPending(bool)));
		connect(julyHttp,SIGNAL(errorSignal(QString)),baseValues_->mainWindow_,SLOT(showErrorMessage(QString)));
		connect(julyHttp,SIGNAL(sslErrorSignal(const QList<QSslError> &)),this,SLOT(sslErrors(const QList<QSslError> &)));
		connect(julyHttp,SIGNAL(dataReceived(QByteArray,int)),this,SLOT(dataReceivedAuth(QByteArray,int)));
	}
void Exchange_Bitstamp::sendToApi(int reqType, QByteArray method, bool auth, bool sendNow, QByteArray commands)
{
	if(julyHttp==0)
	{ 
		julyHttp=new JulyHttp("www.bitstamp.net","",this);
		connect(julyHttp,SIGNAL(anyDataReceived()),baseValues_->mainWindow_,SLOT(anyDataReceived()));
		connect(julyHttp,SIGNAL(setDataPending(bool)),baseValues_->mainWindow_,SLOT(setDataPending(bool)));
		connect(julyHttp,SIGNAL(apiDown(bool)),baseValues_->mainWindow_,SLOT(setApiDown(bool)));
		connect(julyHttp,SIGNAL(errorSignal(QString)),baseValues_->mainWindow_,SLOT(showErrorMessage(QString)));
		connect(julyHttp,SIGNAL(sslErrorSignal(const QList<QSslError> &)),this,SLOT(sslErrors(const QList<QSslError> &)));
		connect(julyHttp,SIGNAL(dataReceived(QByteArray,int)),this,SLOT(dataReceivedAuth(QByteArray,int)));
	}
Пример #9
0
void Exchange_Cryptsy::sendToApi(int reqType, QByteArray method, bool auth, bool sendNow, QByteArray commands)
{
	if(ShibeHttp==0)
	{
		ShibeHttp=new ShibeHttp("data.mtgox.com","Rest-Key: "+privateRestKey+"\r\n",this);
		connect(ShibeHttp,SIGNAL(anyDataReceived()),baseValues_->mainWindow_,SLOT(anyDataReceived()));
		connect(ShibeHttp,SIGNAL(setDataPending(bool)),baseValues_->mainWindow_,SLOT(setDataPending(bool)));
		connect(ShibeHttp,SIGNAL(apiDown(bool)),baseValues_->mainWindow_,SLOT(setApiDown(bool)));
		connect(ShibeHttp,SIGNAL(errorSignal(QString)),baseValues_->mainWindow_,SLOT(showErrorMessage(QString)));
		connect(ShibeHttp,SIGNAL(sslErrorSignal(const QList<QSslError> &)),this,SLOT(sslErrors(const QList<QSslError> &)));
		connect(ShibeHttp,SIGNAL(dataReceived(QByteArray,int)),this,SLOT(dataReceivedAuth(QByteArray,int)));
	}
Пример #10
0
static const char *getItem(PJsonObject object,const char *jsonString){
    if(*jsonString=='\"'){
        jsonString++;
        jsonString=getKey(object,jsonString);
        if(*jsonString==':'){
            jsonString++;
            jsonString=getObject(jsonString,object);
            if(*jsonString==','){
                jsonString++;
                object->next=createNewItem();
                jsonString=getItem(object->next,jsonString);
            }
        }else{
            //print error message that this is no ':'
            showErrorMessage(jsonString,NO_COLON);
        }
    }else{
        //print error message that string is not started with '"'.
        showErrorMessage(jsonString,NO_QUOTATION);
    }
	return jsonString;
}
Пример #11
0
	bool CServer::executeLastLoadScript(const char *script)
	{
		// Ejecuto el script y hago el manejo de errores.
		int msgHandler = 0;
		int errorType = lua_pcall(_lua, 0, 0, msgHandler);

		// Si es un runtime error, accedo al tipo de error guardado en la pila y lo muestro por consola
		if (errorType == LUA_ERRRUN)
		{
			// Si el handler es distinto de cero, el mensaje de error se encuentra en la pila. Lo recupero y lo muestro.
			if (msgHandler != 0)
			{
				const char* error = lua_tostring(_lua, msgHandler);
				showErrorMessage("ERROR DE LUA! - Error de runtime de lua al ejecutar el script \"" + std::string(script) + "\": " + std::string(error));
			}
			else
				// En teoría esta situación no debería darse nunca, pero no está de más hacer la comprobación.
				showErrorMessage("ERROR DE LUA! - Error desconocido de runtime de lua al ejecutar el script \"" + std::string(script) + "\"");

			return false;
		}
		// Memory allocation error
		else if (errorType == LUA_ERRMEM)
		{
			showErrorMessage("ERROR DE LUA! - Error chungo de lua al ejecutar el script \"" + std::string(script) + "\" : Memory allocation error.");

			return false;
		}
		// Error ejecutando el message handler
		else if (errorType == LUA_ERRERR)
		{
			showErrorMessage("ERROR DE LUA! - Error chungo de lua al ejecutar el script \"" + std::string(script) + "\" : Error ejecutando el message handler.");

			return false;
		}

		return true;

	} // executeLastLoadScript
Пример #12
0
	bool CServer::loadScript(const char *script, bool inmediate)
	{
		// Completo la ruta del script.
		std::stringstream filename;
		filename << "media\\scripts\\" << script << ".lua";

		// Cargo el fichero de script dependiendo del parámetro booleano.
		int errorType = 0;

		if (inmediate)
			errorType = luaL_loadstring(_lua, script);
		else
			errorType = luaL_loadfile(_lua, filename.str().c_str());

		// Error al cargar el fichero de script
		if (errorType == LUA_ERRFILE)
		{
			showErrorMessage("ERROR DE LUA! - Error al cargar el fichero de script \"" + std::string(script) + "\". Comprueba que está bien escrito el nombre y que el fichero existe.");

			return false;
		}
		// Error de sintaxis de lua
		else if (errorType == LUA_ERRSYNTAX)
		{
			showErrorMessage("ERROR DE LUA! - Error de sintaxis de lua al cargar el script \"" + std::string(script) + "\". Comprueba que no hay errores en el fichero de script.");

			return false;
		}
		// Memory allocation error
		else if (errorType == LUA_ERRMEM)
		{
			showErrorMessage("ERROR DE LUA! - Error chungo de lua al cargar el script \"" + std::string(script) + "\" : Memory allocation error.");

			return false;
		}

		return true;
		
	} // loadScript
Пример #13
0
void MediaRoutingView::_deleteSelection()
{
	D_METHOD(("MediaRoutingView::_deleteSelection()\n"));
	if (selectedType() == DiagramItem::M_BOX)
	{
		for (uint32 i = 0; i < countSelectedItems(); i++)
		{
			MediaNodePanel *panel = dynamic_cast<MediaNodePanel *>(selectedItemAt(i));
			if (panel && panel->ref->isInternal())
			{
				status_t error = panel->ref->releaseNode();
				if (error)
				{
					BString s;
					s << "Could not release '" << panel->ref->name() << "'";
					showErrorMessage(s, error);
				}
			}			
		}
	}
	else if (selectedType() == DiagramItem::M_WIRE)
	{
		for (uint32 i = 0; i < countSelectedItems(); i++)
		{
			MediaWire *wire = dynamic_cast<MediaWire *>(selectedItemAt(i));
			if (wire && !(wire->connection.flags() & Connection::LOCKED))
			{
				status_t error = manager->disconnect(wire->connection);
				if (error)
				{
					showErrorMessage("Could not disconnect", error);
				}
			}
		}
	}
	// make sure none of the deleted items is still displaying its mouse cursor !
	be_app->SetCursor(B_HAND_CURSOR);
}
Пример #14
0
void DolphinViewContainer::slotUrlNavigatorLocationChanged(const KUrl& url)
{
    if (KProtocolManager::supportsListing(url)) {
        setSearchModeEnabled(isSearchUrl(url));

        m_view->setUrl(url);
        if (isActive() && !isSearchUrl(url)) {
            // When an URL has been entered, the view should get the focus.
            // The focus must be requested asynchronously, as changing the URL might create
            // a new view widget.
            QTimer::singleShot(0, this, SLOT(requestFocus()));
        }
    } else if (KProtocolManager::isSourceProtocol(url)) {
        QString app = "konqueror";
        if (url.protocol().startsWith(QLatin1String("http"))) {
            showErrorMessage(i18nc("@info:status",
                                   "Dolphin does not support web pages, the web browser has been launched"));
            const KConfigGroup config(KSharedConfig::openConfig("kdeglobals"), "General");
            const QString browser = config.readEntry("BrowserApplication");
            if (!browser.isEmpty()) {
                app = browser;
                if (app.startsWith('!')) {
                    // a literal command has been configured, remove the '!' prefix
                    app = app.mid(1);
                }
            }
        } else {
            showErrorMessage(i18nc("@info:status",
                                   "Protocol not supported by Dolphin, Konqueror has been launched"));
        }

        const QString secureUrl = KShell::quoteArg(url.pathOrUrl());
        const QString command = app + ' ' + secureUrl;
        KRun::runCommand(command, app, app, this);
    } else {
        showErrorMessage(i18nc("@info:status", "Invalid protocol"));
    }
}
Пример #15
0
	bool CServer::executeProcedure(const char *name, const T& param1, const T& param2){
		
		assert(_lua && "No se ha hecho la inicialización de lua");

		// Obtengo el procedimiento definido en lua
		luabind::object obj = luabind::globals(_lua)[name];

		//comprobacion de que el tipo es FUNCTION (que es el que queremos recoger)
		if(!obj.is_valid() || (luabind::type(obj) != LUA_TFUNCTION))
		{
			showErrorMessage("ERROR DE LUA! - El procedimiento \"" + std::string(name) + "\" que se está intentando ejecutar no existe o es un procedimiento.");
			return false;
		}
		// Lo ejecuto y hago comprobación de errores.
		try {
			obj(param1,param2);
		} catch (luabind::error &ex) {
			showErrorMessage("ERROR DE LUA! - Error al ejecutar el procedimiento \"" + std::string(name) + "\". Tipo de error: " + std::string(ex.what()));
			return false;
		}

		return true;

	} //executeProcedure (2 params)
Пример #16
0
QVariant FunctionCall::evaluate()
{
	Scope* scopeToUse;
	QString functionName = context()->findIdentifierAndScope(m_functionName, scopeToUse);

	QVariant returnValue;

	if(scopeToUse->isValidFunction(functionName))
	{
		returnValue = scopeToUse->execute(functionName, m_parameters);
	}
	else
	{
		showErrorMessage(QString("%1 is not a valid function name").arg(functionName));
	}

	return returnValue;
}
void InputDeviceAdapterDeviceDaemon::updateInputDevices(void)
	{
	/* Check for error messages from the device client: */
	{
	Threads::Spinlock::Lock errorMessageLock(errorMessageMutex);
	for(std::vector<std::string>::iterator emIt=errorMessages.begin();emIt!=errorMessages.end();++emIt)
		showErrorMessage("Vrui::InputDeviceAdapterDeviceDaemon",emIt->c_str());
	errorMessages.clear();
	}
	
	/* Update all managed input devices: */
	deviceClient.lockState();
	const VRDeviceState& state=deviceClient.getState();
	for(int deviceIndex=0;deviceIndex<numInputDevices;++deviceIndex)
		{
		/* Get pointer to the input device: */
		InputDevice* device=inputDevices[deviceIndex];
		
		/* Don't update tracker-related state for devices that are not tracked: */
		if(trackerIndexMapping[deviceIndex]>=0)
			{
			/* Get device's tracker state from VR device client: */
			const VRDeviceState::TrackerState& ts=state.getTrackerState(trackerIndexMapping[deviceIndex]);
			
			/* Set device's transformation: */
			device->setTransformation(TrackerState(ts.positionOrientation));
			
			/* Set device's linear and angular velocities: */
			device->setLinearVelocity(Vector(ts.linearVelocity));
			device->setAngularVelocity(Vector(ts.angularVelocity));
			}
		
		/* Update button states: */
		for(int i=0;i<device->getNumButtons();++i)
			device->setButtonState(i,state.getButtonState(buttonIndexMapping[deviceIndex][i]));
		
		/* Update valuator states: */
		for(int i=0;i<device->getNumValuators();++i)
			device->setValuator(i,state.getValuatorState(valuatorIndexMapping[deviceIndex][i]));
		}
	
	deviceClient.unlockState();
	}
Пример #18
0
	const char* CServer::getGlobal(const char *name, const char *defaultValue)
	{
		assert(_lua && "No se ha hecho la inicialización de lua");

		// Obtengo la variable global por el nombre.
		luabind::object obj = luabind::globals(_lua)[name];

		// Hago gestión de errores para asegurarme de que la variable existe y es del tipo correcto.
		if (!obj.is_valid() || (luabind::type(obj) != LUA_TSTRING))
		{
			showErrorMessage("ERROR DE LUA! - La variable de tipo cadena \"" + std::string(name) + "\" a la que se está intentando acceder no existe en ningún script de lua o no es de tipo cadena.");

			return defaultValue;
		}

		// Devuelvo la variable haciendo casting de tipo para adecuar la variable de lua a nuestro C++.
		return luabind::object_cast<const char*>(obj);
		
	} // getGlobal(const char*)
Пример #19
0
int CMP3Info::saveTag( char* title, char* artist, char* album, char* year, char* comment, char* tracknumber, char* genre) {

    int error = 0;

    if (strcmp(title,"n/a"))       tag.setTitle(title);
    if (strcmp(artist,"n/a"))      tag.setArtist(artist);
    if (strcmp(album,"n/a"))       tag.setAlbum(album);
    if (strcmp(year,"n/a"))        tag.setYear(atoi(year));
    if (strcmp(comment,"n/a"))     tag.setComment(comment);
    if (strcmp(tracknumber,"n/a")) tag.setTrackNumber(atoi(tracknumber));
    if (strcmp(genre,"n/a"))       tag.genreString(genre, false);

    char id3tagstring[128] ={""};

    if ( tag.saveTag(id3tagstring) ) {

        ofstream* ofile = new ofstream(fileName, ios::in | ios::out | ios::binary);

        if (ofile) {

            // variable to ensure correct, file, position
            int posalter = (Tagged)?-128:0;
            
            // seek up the correct location
            ofile->seekp(posalter, ios::end);
        
            // write the tag to the file
            ofile->write(id3tagstring, 128);

        } else error = ERR_FILEOPEN;

        ofile->close();

        delete ofile;

    } else error = ERR_ID3TAG;

    if (!error) showErrorMessage(error);
    return error;

}
Пример #20
0
void SketchingTool::saveCurvesCallback(Misc::CallbackData* cbData)
	{
	if(isMaster())
		{
		try
			{
			/* Save all curves to a curve file: */
			Misc::File curveFile(Misc::createNumberedFileName(factory->curveFileName,4).c_str(),"w");
			FILE* cf=curveFile.getFilePtr();
			
			/* Write the curve file header: */
			fprintf(cf,"Vrui Curve Editor Tool Curve File\n");
			
			/* Write all curves: */
			fprintf(cf,"%u\n",(unsigned int)curves.size());
			for(std::vector<Curve*>::const_iterator cIt=curves.begin();cIt!=curves.end();++cIt)
				{
				const Curve* c=*cIt;
				
				/* Write the curve's line width and color: */
				fprintf(cf,"\n");
				fprintf(cf,"%4.1f, %03u %03u %03u\n",c->lineWidth,c->color[0],c->color[1],c->color[2]);
				
				/* Write the curve's control points: */
				fprintf(cf,"%u\n",(unsigned int)c->controlPoints.size());
				for(std::vector<Curve::ControlPoint>::const_iterator cpIt=c->controlPoints.begin();cpIt!=c->controlPoints.end();++cpIt)
					fprintf(cf,"%f, %f %f %f\n",cpIt->t,cpIt->pos[0],cpIt->pos[1],cpIt->pos[2]);
				}
			}
		catch(std::runtime_error err)
			{
			/* Show an error message: */
			showErrorMessage("Curve Editor","Could not create curve file; did not save curves");
			}
		}
	}
GridDisplay::GridDisplay(int winSize, Tracklist *tracklist, Grid* grid_, QWidget *parent)
: MyDisplay(tracklist, parent), _winSize(winSize)
{
	this->grid_ = grid_;
	_cellSize = grid_->getCellSize(_winSize);
	setMinimumSize(winSize, winSize);
	setMouseTracking(true);
	setAcceptDrops(true);
	squareHasInitialized.resize(grid_->getHeight() * grid_->getWidth());
	for(int i = 0; i < grid_->getHeight() * grid_->getWidth(); i++)
		squareHasInitialized[i] = false;
	oldXPos = -1;
	oldYPos = -1;
	oldX1Pos = -1;
	oldY1Pos = -1;
	fullScreenMouseOn = false;
	initDone = false;
	fullScreenTimer = new QTimer(this);
	fullScreenTimer->setInterval(150);
	colourMapMode_ = false;


	connect(this, SIGNAL(clearMode()), grid_, SLOT(clearMode()));
	connect(this, SIGNAL(extractMode()), grid_, SLOT(setExtractMode()));
	connect(this, SIGNAL(trainMode()), grid_, SLOT(setTrainMode()));
	connect(this, SIGNAL(predictMode()), grid_, SLOT(setPredictMode()));
	connect(this, SIGNAL(initMode()), grid_, SLOT(setInitMode()));
	connect(this, SIGNAL(savePredictionGridSignal(QString)), grid_, SLOT(savePredictionGrid(QString)));
	connect(this, SIGNAL(openPredictionGridSignal(QString)), grid_, SLOT(openPredictionGrid(QString)));
	connect(grid_, SIGNAL(repaintSignal()), this, SLOT(repaintSlot()));
	connect(this, SIGNAL(cancelButtonPressed()), grid_, SLOT(cancelPressed()));
	connect(this, SIGNAL(hashLoadPressed()), grid_, SLOT(openHash()));
	connect(fullScreenTimer, SIGNAL(timeout()), this, SLOT(fullScreenMouseMove()));
	connect(grid_, SIGNAL(errorBox(QString)), this, SLOT(showErrorMessage(QString)));
	connect(this, SIGNAL(resetGridAction()), grid_, SLOT(resetGridSlot()));
}
Пример #22
0
    virtual void QCAR_onUpdate(QCAR::State& state)
    {
        // Get the tracker manager:
        QCAR::TrackerManager& trackerManager = QCAR::TrackerManager::getInstance();

        // Get the image tracker:
        QCAR::ImageTracker* imageTracker = static_cast<QCAR::ImageTracker*>(
                trackerManager.getTracker(QCAR::Tracker::IMAGE_TRACKER));

        // Get the target finder:
        QCAR::TargetFinder* finder = imageTracker->getTargetFinder();

        // Check if there are new results available:
        const int statusCode = finder->updateSearchResults();

        // Show a message if we encountered an error:
        if (statusCode < 0)
        {
            showErrorMessage(statusCode, state.getFrame().getTimeStamp());
        }
        else if (statusCode == QCAR::TargetFinder::UPDATE_RESULTS_AVAILABLE)
        {
            // Process new search results
            if (finder->getResultCount() > 0)
            {
                const QCAR::TargetSearchResult* result = finder->getResult(0);

                // Check if this target is suitable for tracking:
                if (result->getTrackingRating() > 0)
                {
                    // Create a new Trackable from the result:
                    QCAR::Trackable* newTrackable = finder->enableTracking(*result);
                    if (newTrackable != 0)
                    {
                        LOG("Successfully created new trackable '%s' with rating '%d'.",
                                newTrackable->getName(), result->getTrackingRating());
                                                
                        // Checks if the targets has changed
                        LOG( "Comparing Strings. currentTargetId: %s  lastTargetId: %s",
                                result->getUniqueTargetId(), lastTargetId);

                        if (strcmp(result->getUniqueTargetId(), lastTargetId) != 0)
                        {
                            // If the target has changed then regenerate the texture
                            // Cleaning this value indicates that the product Texture needs to be generated
                            // again in Java with the new Book data for the new target
                            deleteCurrentProductTexture = true;

                            // Starts the loading state for the product
                            renderState = RS_LOADING;

                            // Copies the new target Metadata
                            snprintf(targetMetadata, CONTENT_MAX, "%s", result->getMetaData());

                            // Calls the Java method with the current product texture
                            createProductTexture(targetMetadata);

                        }
                        else
                            renderState = RS_NORMAL;

                        // Initialize the frames to skip variable, used for waiting
                        // a few frames for getting the chance to tracking before
                        // starting the transition to 2D when there is no target
                        pthread_mutex_lock(&framesToSkipMutex);
                        framesToSkipBeforeRenderingTransition = 10;
                        pthread_mutex_unlock(&framesToSkipMutex);

                        // Initialize state variables
                        showAnimation3Dto2D = true;
                        trackingStarted = false;

                        // Updates the value of the current Target Id with the new target found
                        pthread_mutex_lock(&lastTargetIdMutex);
                        strcpy(lastTargetId, result->getUniqueTargetId());
                        pthread_mutex_unlock(&lastTargetIdMutex);

                        enterContentMode();
                    }
                    else
                        LOG("Failed to create new trackable.");
                }
            }
        }
    }
void Exchange_BTCChina::sendToApi(int reqType, QByteArray method, bool auth, bool sendNow, QByteArray commands)
{
	if(auth)
	{
		if(julyHttpAuth==0)
		{
			julyHttpAuth=new JulyHttp("api.btcchina.com","",this,true,true,"application/json-rpc");
			connect(julyHttpAuth,SIGNAL(anyDataReceived()),baseValues_->mainWindow_,SLOT(anyDataReceived()));
			connect(julyHttpAuth,SIGNAL(setDataPending(bool)),baseValues_->mainWindow_,SLOT(setDataPending(bool)));
			connect(julyHttpAuth,SIGNAL(apiDown(bool)),baseValues_->mainWindow_,SLOT(setApiDown(bool)));
			connect(julyHttpAuth,SIGNAL(errorSignal(QString)),baseValues_->mainWindow_,SLOT(showErrorMessage(QString)));
			connect(julyHttpAuth,SIGNAL(sslErrorSignal(const QList<QSslError> &)),this,SLOT(sslErrors(const QList<QSslError> &)));
			connect(julyHttpAuth,SIGNAL(dataReceived(QByteArray,int)),this,SLOT(dataReceivedAuth(QByteArray,int)));
		}

		QByteArray signatureParams;

		signatureParams=commands;
		signatureParams.replace("\"","");
		signatureParams.replace("true","1");
		signatureParams.replace("false","");

		QByteArray postData;
		QByteArray appendedHeader;

		static int tonceCounter=0;		
        static quint32 lastTonce=QDateTime::currentDateTime().toTime_t();
        quint32 newTonce=QDateTime::currentDateTime().toTime_t();

		if(lastTonce!=newTonce)
		{
			tonceCounter=0;
			lastTonce=newTonce;
		}
		else
		{
			tonceCounter+=10;
			if(tonceCounter>99)tonceCounter=0;
		}

		QByteArray tonceCounterData=QByteArray::number(tonceCounter);
		if(tonceCounter>9)tonceCounterData.append("0000");
		else tonceCounterData.append("00000");

		QByteArray tonce=QByteArray::number(newTonce)+tonceCounterData;

		QByteArray signatureString="tonce="+tonce+"&accesskey="+getApiKey()+"&requestmethod=post&id=1&method="+method+"&params="+signatureParams;

		signatureString=getApiKey()+":"+hmacSha1(getApiSign(),signatureString).toHex();

		if(debugLevel&&reqType>299)logThread->writeLog(postData);

		postData="{\"method\":\""+method+"\",\"params\":["+commands+"],\"id\":1}";

		appendedHeader="Authorization: Basic "+signatureString.toBase64()+"\r\n";
		appendedHeader+="Json-Rpc-Tonce: "+tonce+"\r\n";

		if(sendNow)
			julyHttpAuth->sendData(reqType, "POST /api_trade_v1.php",postData,appendedHeader);
		else
			julyHttpAuth->prepareData(reqType, "POST /api_trade_v1.php",postData,appendedHeader);
	}
void InputDeviceAdapterDeviceDaemon::updateInputDevices(void)
	{
	/* Check for error messages from the device client: */
	{
	Threads::Spinlock::Lock errorMessageLock(errorMessageMutex);
	for(std::vector<std::string>::iterator emIt=errorMessages.begin();emIt!=errorMessages.end();++emIt)
		showErrorMessage("Vrui::InputDeviceAdapterDeviceDaemon",emIt->c_str());
	errorMessages.clear();
	}
	
	/* Update all managed input devices: */
	deviceClient.lockState();
	const VRDeviceState& state=deviceClient.getState();
	
	#ifdef MEASURE_LATENCY
	
	Realtime::TimePointMonotonic now;
	VRDeviceState::TimeStamp ts=VRDeviceState::TimeStamp(now.tv_sec*1000000+(now.tv_nsec+500)/1000);
	
	double staleness=0.0;
	for(int i=0;i<state.getNumTrackers();++i)
		staleness+=double(ts-state.getTrackerTimeStamp(i));
	printf("Tracking data staleness: %f ms\n",staleness*0.001/double(state.getNumTrackers()));
	
	#endif
	
	/* Get the current time for input device motion prediction: */
	Realtime::TimePointMonotonic now;
	VRDeviceState::TimeStamp nowTs=VRDeviceState::TimeStamp(now.tv_sec*1000000+(now.tv_nsec+500)/1000);
	
	for(int deviceIndex=0;deviceIndex<numInputDevices;++deviceIndex)
		{
		/* Get pointer to the input device: */
		InputDevice* device=inputDevices[deviceIndex];
		
		/* Don't update tracker-related state for devices that are not tracked: */
		if(trackerIndexMapping[deviceIndex]>=0)
			{
			/* Get device's tracker state from VR device client: */
			const VRDeviceState::TrackerState& ts=state.getTrackerState(trackerIndexMapping[deviceIndex]);
			
			/* Motion-predict the device's tracker state from its sampling time to the current time: */
			typedef VRDeviceState::TrackerState::PositionOrientation PO;
			
			float predictionDelta=float(nowTs-state.getTrackerTimeStamp(trackerIndexMapping[deviceIndex]))*1.0e-6f+motionPredictionDelta;
			
			PO::Rotation predictRot=PO::Rotation::rotateScaledAxis(ts.angularVelocity*predictionDelta)*ts.positionOrientation.getRotation();
			predictRot.renormalize();
			PO::Vector predictTrans=ts.linearVelocity*predictionDelta+ts.positionOrientation.getTranslation();
			
			#ifdef SAVE_TRACKERSTATES
			predictedFile->write<Misc::UInt32>(nowTs+Misc::UInt32(predictionDelta*1.0e6f+0.5f));
			Misc::Marshaller<PO>::write(PO(predictTrans,predictRot),*predictedFile);
			#endif
			
			/* Set device's transformation: */
			device->setTransformation(TrackerState(predictTrans,predictRot));
			
			/* Set device's linear and angular velocities: */
			device->setLinearVelocity(Vector(ts.linearVelocity));
			device->setAngularVelocity(Vector(ts.angularVelocity));
			}
		
		/* Update button states: */
		for(int i=0;i<device->getNumButtons();++i)
			device->setButtonState(i,state.getButtonState(buttonIndexMapping[deviceIndex][i]));
		
		/* Update valuator states: */
		for(int i=0;i<device->getNumValuators();++i)
			device->setValuator(i,state.getValuatorState(valuatorIndexMapping[deviceIndex][i]));
		}
	
	deviceClient.unlockState();
	}
bool MainWindow::qt_invoke( int _id, QUObject* _o )
{
    switch ( _id - staticMetaObject()->slotOffset() ) {
    case 0:
        showProperties((QObject*)static_QUType_ptr.get(_o+1));
        break;
    case 1:
        updateProperties((QObject*)static_QUType_ptr.get(_o+1));
        break;
    case 2:
        showDialogHelp();
        break;
    case 3:
        showDebugStep((QObject*)static_QUType_ptr.get(_o+1),(int)static_QUType_int.get(_o+2));
        break;
    case 4:
        showStackFrame((QObject*)static_QUType_ptr.get(_o+1),(int)static_QUType_int.get(_o+2));
        break;
    case 5:
        showErrorMessage((QObject*)static_QUType_ptr.get(_o+1),(int)static_QUType_int.get(_o+2),(const QString&)static_QUType_QString.get(_o+3));
        break;
    case 6:
        finishedRun();
        break;
    case 7:
        breakPointsChanged();
        break;
    case 8:
        fileNew();
        break;
    case 9:
        fileNewDialog();
        break;
    case 10:
        fileNewFile();
        break;
    case 11:
        fileClose();
        break;
    case 12:
        fileQuit();
        break;
    case 13:
        fileCloseProject();
        break;
    case 14:
        fileOpen();
        break;
    case 15:
        fileOpen((const QString&)static_QUType_QString.get(_o+1),(const QString&)static_QUType_QString.get(_o+2));
        break;
    case 16:
        fileOpen((const QString&)static_QUType_QString.get(_o+1),(const QString&)static_QUType_QString.get(_o+2),(const QString&)static_QUType_QString.get(_o+3));
        break;
    case 17:
        fileOpen((const QString&)static_QUType_QString.get(_o+1),(const QString&)static_QUType_QString.get(_o+2),(const QString&)static_QUType_QString.get(_o+3),(bool)static_QUType_bool.get(_o+4));
        break;
    case 18:
        static_QUType_bool.set(_o,fileSave());
        break;
    case 19:
        static_QUType_bool.set(_o,fileSaveForm());
        break;
    case 20:
        static_QUType_bool.set(_o,fileSaveProject());
        break;
    case 21:
        static_QUType_bool.set(_o,fileSaveAs());
        break;
    case 22:
        fileSaveAll();
        break;
    case 23:
        fileCreateTemplate();
        break;
    case 24:
        editUndo();
        break;
    case 25:
        editRedo();
        break;
    case 26:
        editCut();
        break;
    case 27:
        editCopy();
        break;
    case 28:
        editPaste();
        break;
    case 29:
        editDelete();
        break;
    case 30:
        editSelectAll();
        break;
    case 31:
        editLower();
        break;
    case 32:
        editRaise();
        break;
    case 33:
        editAdjustSize();
        break;
    case 34:
        editLayoutHorizontal();
        break;
    case 35:
        editLayoutVertical();
        break;
    case 36:
        editLayoutHorizontalSplit();
        break;
    case 37:
        editLayoutVerticalSplit();
        break;
    case 38:
        editLayoutGrid();
        break;
    case 39:
        editLayoutContainerHorizontal();
        break;
    case 40:
        editLayoutContainerVertical();
        break;
    case 41:
        editLayoutContainerGrid();
        break;
    case 42:
        editBreakLayout();
        break;
    case 43:
        editAccels();
        break;
    case 44:
        editFunctions();
        break;
    case 45:
        editConnections();
        break;
    case 46:
        static_QUType_ptr.set(_o,editSource());
        break;
    case 47:
        static_QUType_ptr.set(_o,editSource((SourceFile*)static_QUType_ptr.get(_o+1)));
        break;
    case 48:
        static_QUType_ptr.set(_o,openSourceEditor());
        break;
    case 49:
        static_QUType_ptr.set(_o,createSourceEditor((QObject*)static_QUType_ptr.get(_o+1),(Project*)static_QUType_ptr.get(_o+2)));
        break;
    case 50:
        static_QUType_ptr.set(_o,createSourceEditor((QObject*)static_QUType_ptr.get(_o+1),(Project*)static_QUType_ptr.get(_o+2),(const QString&)static_QUType_QString.get(_o+3)));
        break;
    case 51:
        static_QUType_ptr.set(_o,createSourceEditor((QObject*)static_QUType_ptr.get(_o+1),(Project*)static_QUType_ptr.get(_o+2),(const QString&)static_QUType_QString.get(_o+3),(const QString&)static_QUType_QString.get(_o+4)));
        break;
    case 52:
        static_QUType_ptr.set(_o,createSourceEditor((QObject*)static_QUType_ptr.get(_o+1),(Project*)static_QUType_ptr.get(_o+2),(const QString&)static_QUType_QString.get(_o+3),(const QString&)static_QUType_QString.get(_o+4),(bool)static_QUType_bool.get(_o+5)));
        break;
    case 53:
        editFormSettings();
        break;
    case 54:
        editProjectSettings();
        break;
    case 55:
        editPixmapCollection();
        break;
    case 56:
        editDatabaseConnections();
        break;
    case 57:
        editPreferences();
        break;
    case 58:
        projectInsertFile();
        break;
    case 59:
        searchFind();
        break;
    case 60:
        searchIncremetalFindMenu();
        break;
    case 61:
        searchIncremetalFind();
        break;
    case 62:
        searchIncremetalFindNext();
        break;
    case 63:
        searchReplace();
        break;
    case 64:
        searchGotoLine();
        break;
    case 65:
        previewForm();
        break;
    case 66:
        previewForm((const QString&)static_QUType_QString.get(_o+1));
        break;
    case 67:
        toolsCustomWidget();
        break;
    case 68:
        toolsConfigure();
        break;
    case 69:
        helpContents();
        break;
    case 70:
        helpManual();
        break;
    case 71:
        helpAbout();
        break;
    case 72:
        helpAboutQt();
        break;
    case 73:
        helpRegister();
        break;
    case 74:
        activeWindowChanged((QWidget*)static_QUType_ptr.get(_o+1));
        break;
    case 75:
        updateUndoRedo((bool)static_QUType_bool.get(_o+1),(bool)static_QUType_bool.get(_o+2),(const QString&)static_QUType_QString.get(_o+3),(const QString&)static_QUType_QString.get(_o+4));
        break;
    case 76:
        updateEditorUndoRedo();
        break;
    case 77:
        toolSelected((QAction*)static_QUType_ptr.get(_o+1));
        break;
    case 78:
        clipboardChanged();
        break;
    case 79:
        selectionChanged();
        break;
    case 80:
        windowsMenuActivated((int)static_QUType_int.get(_o+1));
        break;
    case 81:
        setupWindowActions();
        break;
    case 82:
        createNewTemplate();
        break;
    case 83:
        projectSelected((QAction*)static_QUType_ptr.get(_o+1));
        break;
    case 84:
        setupRecentlyFilesMenu();
        break;
    case 85:
        setupRecentlyProjectsMenu();
        break;
    case 86:
        recentlyFilesMenuActivated((int)static_QUType_int.get(_o+1));
        break;
    case 87:
        recentlyProjectsMenuActivated((int)static_QUType_int.get(_o+1));
        break;
    case 88:
        emitProjectSignals();
        break;
    case 89:
        showStartDialog();
        break;
    case 90:
        doFunctionsChanged();
        break;
    case 91:
        static_QUType_bool.set(_o,openProjectSettings((Project*)static_QUType_ptr.get(_o+1)));
        break;
    default:
        return QMainWindow::qt_invoke( _id, _o );
    }
    return TRUE;
}
Пример #26
0
void Exchange_BitCurex::dataReceivedAuth(QByteArray data, int reqType)
{
    if(debugLevel)logThread->writeLog("RCV: "+data);
    if(data.size()<4)return;
    if(data.at(0)==QLatin1Char('<'))return;

    bool success=true;

	switch(reqType)
	{
    case 103: //ticker
        if(data.startsWith("{\"lowest_tx_price_h\": \""))
        {
            QByteArray tickerHigh=getMidData("\"highest_tx_price_h\": \"","\", \"",&data);
			if(!tickerHigh.isEmpty())
			{
                double newTickerHigh=tickerHigh.toDouble();
                if(newTickerHigh!=lastTickerHigh)
                    IndicatorEngine::setValue(baseValues.exchangeName,baseValues.currentPair.symbol,"High",newTickerHigh);
				lastTickerHigh=newTickerHigh;
			}

            QByteArray tickerLow=getMidData("\"lowest_tx_price_h\": \"","\", \"",&data);
			if(!tickerLow.isEmpty())
			{
                double newTickerLow=tickerLow.toDouble();
                if(newTickerLow!=lastTickerLow)
                    IndicatorEngine::setValue(baseValues.exchangeName,baseValues.currentPair.symbol,"Low",newTickerLow);
				lastTickerLow=newTickerLow;
			}

            QByteArray tickerSell=getMidData("\"best_bid_h\": \"","\", \"",&data);
			if(!tickerSell.isEmpty())
            {
                double newTickerSell=tickerSell.toDouble();
                if(newTickerSell!=lastTickerSell)
                    IndicatorEngine::setValue(baseValues.exchangeName,baseValues.currentPair.symbol,"Sell",newTickerSell);
				lastTickerSell=newTickerSell;
			}

            QByteArray tickerBuy=getMidData("\"best_ask_h\": \"","\", \"",&data);
			if(!tickerBuy.isEmpty())
            {
                double newTickerBuy=tickerBuy.toDouble();
                if(newTickerBuy!=lastTickerBuy)
                    IndicatorEngine::setValue(baseValues.exchangeName,baseValues.currentPair.symbol,"Buy",newTickerBuy);
				lastTickerBuy=newTickerBuy;
			}

            QByteArray tickerVolume=getMidData("\"total_volume_h\": \"","\", \"",&data);
			if(!tickerVolume.isEmpty())
			{
                double newTickerVolume=tickerVolume.toDouble();
                if(newTickerVolume!=lastTickerVolume)
                    IndicatorEngine::setValue(baseValues.exchangeName,baseValues.currentPair.symbol,"Volume",newTickerVolume);
				lastTickerVolume=newTickerVolume;
			}

            QByteArray tickerLast=getMidData("\"last_tx_price_h\": \"","\", \"",&data);
            if(!tickerLast.isEmpty())
            {
                double newTickerLast=tickerLast.toDouble();
                if(newTickerLast!=lastTickerLast)
                    IndicatorEngine::setValue(baseValues.exchangeName,baseValues.currentPair.symbol,"Last",newTickerLast);
                lastTickerLast=newTickerLast;
            }
        }
        else success=false;
		break;//ticker
    case 109: //trades
        if(data.startsWith("{\"status\": \"ok\", \"data\": {\"symbol\": \""+baseValues.currentPair.symbol.toLower().toLatin1()+"\", \"trades\": [{\""))
		{
            QStringList tradeList=QString(data).split("}, {");
			QList<TradesItem> *newTradesItems=new QList<TradesItem>;

            TradesItem newItem;
            for(int n=tradeList.count()-1;n>=0;n--)
			{
				QByteArray tradeData=tradeList.at(n).toLatin1()+"}";

                newItem.date=getMidData("\"ts\": ",", \"",&tradeData).toUInt();
                if(newItem.date<startTradesDate)continue;

                quint32 currentTid=getMidData("\"txid\": ",", \"",&tradeData).toUInt();
                if(lastFetchTid>=currentTid)continue;
                lastFetchTid=currentTid;

                newItem.price=getMidData("\"price\": ",", \"",&tradeData).toDouble();
                newItem.amount=getMidData("\"amount\": ",", \"",&tradeData).toDouble();
                newItem.orderType=getMidData("\"type\": \"","\"}",&tradeData)=="ask"?-1:1;
                newItem.symbol=baseValues.currentPair.symbol;

				if(newItem.isValid())(*newTradesItems)<<newItem;
				else if(debugLevel)logThread->writeLog("Invalid trades fetch data line:"+tradeData,2);
			}

            if(newItem.price>0&&lastTradesDate<newItem.date)
            {
                lastTradesDate=newItem.date;
                IndicatorEngine::setValue(baseValues.exchangeName,baseValues.currentPair.symbol,"Last",newItem.price);
                lastTickerLast=newItem.price;
            }
            if(newTradesItems->count())emit addLastTrades(baseValues.currentPair.symbol,newTradesItems);
			else delete newTradesItems;
        }
        else if(!data.startsWith("{\"status\": \"ok\", \"data\": {\"symbol\": \""))success=false;
		break;//trades
	case 111: //depth
        if(data.startsWith("{\"symbol\": \""+baseValues.currentPair.symbol.toLower().toLatin1()+"\", \"bids\": ["))
		{
            emit depthRequestReceived();

			if(lastDepthData!=data)
			{
				lastDepthData=data;
				depthAsks=new QList<DepthItem>;
				depthBids=new QList<DepthItem>;

                QMap<double,double> currentAsksMap;
                QStringList asksList=QString(getMidData("asks\": [[","]]",&data)).split("], [");
                double groupedPrice=0.0;
                double groupedVolume=0.0;
				int rowCounter=0;

				for(int n=0;n<asksList.count();n++)
				{
					if(baseValues.depthCountLimit&&rowCounter>=baseValues.depthCountLimit)break;
                    QStringList currentPair=asksList.at(n).split(", ");
					if(currentPair.count()!=2)continue;
                    double priceDouble=currentPair.first().toDouble();
                    double amount=currentPair.last().toDouble();

					if(baseValues.groupPriceValue>0.0)
					{
						if(n==0)
						{
                            emit depthFirstOrder(baseValues.currentPair.symbol,priceDouble,amount,true);
							groupedPrice=baseValues.groupPriceValue*(int)(priceDouble/baseValues.groupPriceValue);
							groupedVolume=amount;
						}
						else
						{
							bool matchCurrentGroup=priceDouble<groupedPrice+baseValues.groupPriceValue;
							if(matchCurrentGroup)groupedVolume+=amount;
							if(!matchCurrentGroup||n==asksList.count()-1)
							{
                                depthSubmitOrder(baseValues.currentPair.symbol,
                                                 &currentAsksMap,groupedPrice+baseValues.groupPriceValue,groupedVolume,true);
								rowCounter++;
								groupedVolume=amount;
								groupedPrice+=baseValues.groupPriceValue;
							}
						}
					}
					else
					{
                        depthSubmitOrder(baseValues.currentPair.symbol,
                                         &currentAsksMap,priceDouble,amount,true);
						rowCounter++;
					}
				}
                QList<double> currentAsksList=lastDepthAsksMap.keys();
				for(int n=0;n<currentAsksList.count();n++)
                    if(currentAsksMap.value(currentAsksList.at(n),0)==0)depthUpdateOrder(baseValues.currentPair.symbol,
                                                                                         currentAsksList.at(n),0.0,true);
				lastDepthAsksMap=currentAsksMap;

                QMap<double,double> currentBidsMap;
                QStringList bidsList=QString(getMidData("bids\": [[","]]",&data)).split("], [");
				groupedPrice=0.0;
				groupedVolume=0.0;
				rowCounter=0;

				for(int n=0;n<bidsList.count();n++)
				{
					if(baseValues.depthCountLimit&&rowCounter>=baseValues.depthCountLimit)break;
                    QStringList currentPair=bidsList.at(n).split(", ");
					if(currentPair.count()!=2)continue;
                    double priceDouble=currentPair.first().toDouble();
                    double amount=currentPair.last().toDouble();
					if(baseValues.groupPriceValue>0.0)
					{
						if(n==0)
						{
                            emit depthFirstOrder(baseValues.currentPair.symbol,priceDouble,amount,false);
							groupedPrice=baseValues.groupPriceValue*(int)(priceDouble/baseValues.groupPriceValue);
							groupedVolume=amount;
						}
						else
						{
							bool matchCurrentGroup=priceDouble>groupedPrice-baseValues.groupPriceValue;
							if(matchCurrentGroup)groupedVolume+=amount;
							if(!matchCurrentGroup||n==asksList.count()-1)
							{
                                depthSubmitOrder(baseValues.currentPair.symbol,
                                                 &currentBidsMap,groupedPrice-baseValues.groupPriceValue,groupedVolume,false);
								rowCounter++;
								groupedVolume=amount;
								groupedPrice-=baseValues.groupPriceValue;
							}
						}
					}
					else
					{
                        depthSubmitOrder(baseValues.currentPair.symbol,
                                         &currentBidsMap,priceDouble,amount,false);
						rowCounter++;
					}
				}
                QList<double> currentBidsList=lastDepthBidsMap.keys();
				for(int n=0;n<currentBidsList.count();n++)
                    if(currentBidsMap.value(currentBidsList.at(n),0)==0)depthUpdateOrder(baseValues.currentPair.symbol,
                                                                                         currentBidsList.at(n),0.0,false);
				lastDepthBidsMap=currentBidsMap;

                emit depthSubmitOrders(baseValues.currentPair.symbol,depthAsks, depthBids);
				depthAsks=0;
				depthBids=0;
			}
		}
        else if(!data.startsWith("{\"symbol\": \""))
        {
            if(debugLevel)logThread->writeLog("Invalid depth data:"+data,2);
            success=false;
        }
		break;
	case 202: //info
        if(data.startsWith("{\"status\": \"ok\", \"data\": {\""))
        {
            QByteArray fundsData=getMidData("data\": {","}",&data);
            QByteArray btcBalance=getMidData(baseValues.currentPair.currAStrLow+"\": \"","\"",&fundsData);
			if(!btcBalance.isEmpty())
			{
                double newBtcBalance=btcBalance.toDouble();
                if(lastBtcBalance!=newBtcBalance)emit accBtcBalanceChanged(baseValues.currentPair.symbol,newBtcBalance);
				lastBtcBalance=newBtcBalance;
			}

            QByteArray usdBalance=getMidData("\""+baseValues.currentPair.currBStrLow+"\": \"","\"",&fundsData);
			if(!usdBalance.isEmpty())
			{
                double newUsdBalance=usdBalance.toDouble();
                if(newUsdBalance!=lastUsdBalance)emit accUsdBalanceChanged(baseValues.currentPair.symbol,newUsdBalance);
				lastUsdBalance=newUsdBalance;
			}

            QByteArray fee=getMidData("\"fee\": ",",",&data);
            if(!fee.isEmpty())
            {
                double newFee=fee.toDouble();
                if(newFee!=lastFee)emit accFeeChanged(baseValues.currentPair.symbol,newFee);
                lastFee=newFee;
            }
        }
        else success=false;
		break;//info
	case 204://orders
        if(data.startsWith("{\"status\": \"ok\", \"data\": [{\""))
        {
            if(lastOrders!=data)
            {
                lastOrders=data;

                QStringList ordersList=QString(data).split("}, {");
                QList<OrderItem> *orders=new QList<OrderItem>;
                for(int n=0;n<ordersList.count();n++)
                {
                    OrderItem currentOrder;
                    QByteArray currentOrderData=ordersList.at(n).toLatin1()+"}";

                    currentOrder.oid=getMidData("id\": \"","\"}",&currentOrderData);
                    QByteArray tempDate=getMidData("issued\": ",", \"",&currentOrderData);
                    tempDate.chop(3);
                    currentOrder.date=tempDate.toUInt();
                    currentOrder.type=getMidData("type\": \"","\", \"",&currentOrderData)=="ask";
                    currentOrder.amount=getMidData("volume\": \"","\", \"",&currentOrderData).toDouble();
                    currentOrder.price=getMidData("limit\": \"","\", \"",&currentOrderData).toDouble();
                    currentOrder.symbol="BTC"+getMidData("currency\": \"","\", \"",&currentOrderData).toUpper();
                    currentOrder.status=1;

                    if(currentOrder.isValid())(*orders)<<currentOrder;
                }
                emit orderBookChanged(baseValues.currentPair.symbol,orders);
            }
        }
        else if(data.startsWith("{\"status\": \"ok\", \"data\": ["))
            emit ordersIsEmpty();
        else
            success=false;
        break;//orders
	case 305: //order/cancel
        if(data.startsWith("{\"status\": \"ok\", \"data\": [{\""))
        {
            QByteArray oid=getMidData("id\": \"","\"",&data);
            if(!oid.isEmpty())emit orderCanceled(baseValues.currentPair.symbol,oid);
		}
        else success=false;
		break;//order/cancel
    case 306: if(debugLevel)logThread->writeLog("Buy OK: "+data,2);break;//order/buy
    case 307: if(debugLevel)logThread->writeLog("Sell OK: "+data,2);break;//order/sell
    case 208: ///history
        if(data.startsWith("{\"status\": \"ok\", \"data\": {\"symbol\": \""+baseValues.currentPair.symbol.toLower().toLatin1()+"\", \"trades\": ["))
        {
            if(lastHistory!=data)
            {
                lastHistory=data;

                QStringList dataList=QString(data).split("}, {");
                QList<HistoryItem> *historyItems=new QList<HistoryItem>;
                quint32 currentId;
                quint32 maxId=0;
                for(int n=dataList.count()-1;n>=0;n--)
                {
                    QByteArray curLog=dataList.at(n).toLatin1()+"}";

                    currentId=getMidData("txid\": ",", \"",&curLog).toUInt();
                    if(currentId<=lastHistoryId)break;
                    if(n==dataList.count()-1)maxId=currentId;

                    HistoryItem currentHistoryItem;
                    QByteArray logType=getMidData("type\": \"","\"}",&curLog);
                    if(logType=="ask")currentHistoryItem.type=2;
                    else if(logType=="bid")currentHistoryItem.type=1;
				
                    if(currentHistoryItem.type)
                    {
                        currentHistoryItem.symbol=baseValues.currentPair.symbol;
                        currentHistoryItem.dateTimeInt=getMidData("ts\": ",", \"",&curLog).toUInt();
                        currentHistoryItem.price=getMidData("price\": ",", \"",&curLog).toDouble();
                        currentHistoryItem.volume=getMidData("amount\": ",", \"",&curLog).toDouble();
                        if(currentHistoryItem.isValid())(*historyItems)<<currentHistoryItem;
                    }
                }
                if(maxId>lastHistoryId)lastHistoryId=maxId;
                emit historyChanged(historyItems);
            }
        }
        else success=false;
		break;//money/wallet/history
	default: break;
	}

    static int authErrorCount=0;
    if(reqType>=200 && reqType<300)
    {
        if(!success)
        {
            authErrorCount++;
            if(authErrorCount>2)
            {
                QString authErrorString=getMidData("data\": \"","\"",&data);
                if(debugLevel)logThread->writeLog("API error: "+authErrorString.toLatin1()+" ReqType: "+QByteArray::number(reqType),2);

                if(authErrorString=="auth_error")authErrorString=julyTr("TRUNAUTHORIZED","Invalid API key.");
                else if(authErrorString=="nonce_error")authErrorString=julyTr("THIS_PROFILE_ALREADY_USED","Invalid nonce parameter.");
                if(!authErrorString.isEmpty())emit showErrorMessage(authErrorString);
            }
        }
        else authErrorCount=0;
    }

	static int errorCount=0;
	if(!success)
	{
        QString errorString;
        errorString=getMidData("{\"status\": \"error\", \"data\": \"","\"",&data);

        errorCount++;
		if(errorCount<3)return;
		if(debugLevel)logThread->writeLog("API error: "+errorString.toLatin1()+" ReqType:"+QByteArray::number(reqType),2);
		if(errorString.isEmpty())return;
		if(errorString==QLatin1String("no orders"))return;
		if(reqType<300)emit showErrorMessage("I:>"+errorString);
	}
	else errorCount=0;
}
Пример #27
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    MainWindow w;

    QPixmap pixmap(":/app/icons/splash.png");

    SplashScreen *s = new SplashScreen(pixmap);
    s->show();
    s->showMessage("Event Music Machine starten...");

    QString path = Configuration::getStorageLocation();
    if (path == "") {
        QFileDialog dia(s);
        dia.setViewMode(QFileDialog::List);
        dia.setFileMode(QFileDialog::Directory);
        dia.setAcceptMode(QFileDialog::AcceptOpen);
        dia.setOptions(QFileDialog::ShowDirsOnly);
        dia.setWindowTitle(QObject::tr("Bitte selektieren Sie einen Ordner in dem die Konfigurations-Dateien abgelegt werden sollen."));
        if (dia.exec() == 1) {
            path = dia.selectedFiles().at(0);
            Configuration::setStorageLocation(path);
        }
    }

    s->showMessage("Slotspeicher verbinden...");
    if (!QFile(Configuration::getStorageLocation() + "/slotstore.emm").exists())
    {
        QMessageBox::information(s,"Slot-Speicher anlegen",QObject::tr("Es wurde keine gültige Slot-Datenbank gefunden. Sie wurde jetzt angelegt."));
        QFile::copy(":/slot-store.sqlite", Configuration::getStorageLocation() + "/slotstore.emm");
        QFile::setPermissions(Configuration::getStorageLocation() + "/slotstore.emm",QFile::ReadOther | QFile::WriteOther);
    }

    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(Configuration::getStorageLocation() + "/slotstore.emm");
    if (!db.open())
    {
        QMessageBox::warning(s,QObject::tr("Keine Verbindung zum Slot-Speicher"),QObject::tr("Es konnte keine Verbindung zum Slot-Speicher hergestellt werden!"));
    }

    s->showMessage("Verbindung zur Tastatur herstellen...");
    KeyboardController *keyController = KeyboardController::getInstance();
    QObject::connect(keyController, SIGNAL(errorOccured(QString)), s, SLOT(showErrorMessage(QString)));
    QObject::connect(keyController, SIGNAL(keyPressed(int,int)), &w, SLOT(keyboardSignal(int,int)));
    keyController->initializeKeyboardController();

    s->showMessage("Audiogeräte initialisieren...");

    AudioProcessor::getInstance()->initDevices(&w);

    s->showMessage("Audio-Plugins laden...");
    PluginLoader::loadPlugins();

    s->showMessage("Slots laden und überprüfen...");

    int number = 1;
    Configuration *config = Configuration::getInstance();
    for (int i=0;i<config->getLayer();i++)
    {
        for (int j=0;j<config->getVerticalSlots();j++)
        {
            for (int k=0;k<config->getHorizontalSlots();k++)
            {
                CartSlot *slot = AudioProcessor::getInstance()->getCartSlotWithNumber(number);
                s->showMessage("Slots laden und überprüfen...\r\n"+slot->getText1());
                if (slot->isMissing()) {
                    QMessageBox::information(s,"Datei wurde nicht gefunden","Slot "+QString::number(slot->getNumber())+" ("+slot->getText1()+") konnte nicht geladen werden, weil die Datei nicht gefunden wurde!");
                }
                number++;
            }
        }
    }
    s->showMessage("Benutzeroberfläche initialisieren...");
    w.init();
    s->close();


    w.show();
    return a.exec();
}
Пример #28
0
Window::Window(QWidget *parent)
    : KMainWindow(parent)
{
    QWidget* widget = new QWidget;
    setCentralWidget(widget);
    resize(500, 400);

    m_actions
            << new QAction(KIcon("document-save"), i18n("Save"), this)
            << new QAction(i18n("Discard"), this)
            ;

    QVBoxLayout* mainLayout = new QVBoxLayout(widget);

    // KMessageWidget
    m_messageWidget = new KMessageWidget(this);
    m_messageWidget->hide();
    mainLayout->addWidget(m_messageWidget);

    // Message buttons
    {
        QGroupBox* groupBox = new QGroupBox();
        groupBox->setTitle(i18n("Show/hide message widget"));
        mainLayout->addWidget(groupBox);
        QVBoxLayout* layout = new QVBoxLayout(groupBox);

        createMessageButton(layout, i18n("Error"), SLOT(showErrorMessage()));
        createMessageButton(layout, i18n("Warning"), SLOT(showWarningMessage()));
        createMessageButton(layout, i18n("Information"), SLOT(showInformationMessage()));
        createMessageButton(layout, i18n("Positive"), SLOT(showPositiveMessage()));
    }

    // Text
    {
        QGroupBox* groupBox = new QGroupBox();
        groupBox->setTitle(i18n("Text"));
        mainLayout->addWidget(groupBox);
        QVBoxLayout* layout = new QVBoxLayout(groupBox);

        m_edit = new KTextEdit;
        m_edit->setClickMessage(i18n("Use default text"));
        layout->addWidget(m_edit);
    }

    // Options
    {
        QGroupBox* groupBox = new QGroupBox();
        groupBox->setTitle(i18n("Options"));
        mainLayout->addWidget(groupBox);
        QVBoxLayout* layout = new QVBoxLayout(groupBox);

        QCheckBox* wordwrapCheckBox = new QCheckBox(i18n("Word wrap"));
        layout->addWidget(wordwrapCheckBox);
        connect(wordwrapCheckBox, SIGNAL(toggled(bool)), m_messageWidget, SLOT(setWordWrap(bool)));

        QCheckBox* showActionsCheckBox = new QCheckBox(i18n("Show action buttons"));
        layout->addWidget(showActionsCheckBox);
        connect(showActionsCheckBox, SIGNAL(toggled(bool)), SLOT(showActions(bool)));

        QCheckBox* showCloseButtonCheckBox = new QCheckBox(i18n("Show close button"));
        showCloseButtonCheckBox->setChecked(true);
        layout->addWidget(showCloseButtonCheckBox);
        connect(showCloseButtonCheckBox, SIGNAL(toggled(bool)),m_messageWidget, SLOT(setCloseButtonVisible(bool)));

        m_animatedShowCheckBox = new QCheckBox(i18n("Animated"));
        m_animatedShowCheckBox->setChecked(true);
        layout->addWidget(m_animatedShowCheckBox);

        QLabel* iconLabel = new QLabel("Icon:");
        layout->addWidget(iconLabel);

        m_iconComboBox = new QComboBox;
        iconLabel->setBuddy(m_iconComboBox);
        QStringList names = QStringList() << QString() << "preferences-system-network" << "document-save" << "system-users";
        Q_FOREACH(const QString &name, names) {
            QIcon icon = QIcon::fromTheme(name);
            m_iconComboBox->addItem(icon, name.isEmpty() ? "none" : name);
        }
        connect(m_iconComboBox, SIGNAL(activated(int)), SLOT(setIconFromComboBox(int)));
        layout->addWidget(m_iconComboBox);
    }
Пример #29
0
        connect(mainClass,SIGNAL(apiBuy(QString, double, double)),this,SLOT(buy(QString, double, double)));
        connect(mainClass,SIGNAL(apiSell(QString, double, double)),this,SLOT(sell(QString, double, double)));
        connect(mainClass,SIGNAL(cancelOrderByOid(QString, QByteArray)),this,SLOT(cancelOrder(QString, QByteArray)));
        connect(mainClass,SIGNAL(getHistory(bool)),this,SLOT(getHistory(bool)));

        connect(this,SIGNAL(orderBookChanged(QString, QList<OrderItem> *)),mainClass,SLOT(orderBookChanged(QString, QList<OrderItem> *)));
		connect(this,SIGNAL(historyChanged(QList<HistoryItem>*)),mainClass,SLOT(historyChanged(QList<HistoryItem>*)));
        connect(this,SIGNAL(orderCanceled(QString, QByteArray)),mainClass,SLOT(orderCanceled(QString, QByteArray)));
		connect(this,SIGNAL(ordersIsEmpty()),mainClass,SLOT(ordersIsEmpty()));
	}

	connect(this,SIGNAL(depthRequested()),mainClass,SLOT(depthRequested()));
	connect(this,SIGNAL(depthRequestReceived()),mainClass,SLOT(depthRequestReceived()));
    connect(this,SIGNAL(depthSubmitOrders(QString, QList<DepthItem> *, QList<DepthItem> *)),mainClass,SLOT(depthSubmitOrders(QString, QList<DepthItem> *, QList<DepthItem> *)));
    connect(this,SIGNAL(depthFirstOrder(QString, double,double,bool)),mainClass,SLOT(depthFirstOrder(QString, double,double,bool)));
	connect(this,SIGNAL(showErrorMessage(QString)),mainClass,SLOT(showErrorMessage(QString)));

    connect(this,SIGNAL(availableAmountChanged(QString, double)),mainClass,SLOT(availableAmountChanged(QString, double)));
	connect(mainClass,SIGNAL(clearValues()),this,SLOT(clearValues()));
	connect(mainClass,SIGNAL(reloadDepth()),this,SLOT(reloadDepth()));

    connect(this,SIGNAL(accVolumeChanged(double)),mainClass->ui.accountVolume,SLOT(setValue(double)));
    connect(this,SIGNAL(accFeeChanged(QString, double)),mainClass,SLOT(accFeeChanged(QString,double)));
    connect(this,SIGNAL(accBtcBalanceChanged(QString, double)),mainClass,SLOT(accBtcBalanceChanged(QString, double)));
    connect(this,SIGNAL(accUsdBalanceChanged(QString, double)),mainClass,SLOT(accUsdBalanceChanged(QString, double)));

    connect(this,SIGNAL(loginChanged(QString)),mainClass,SLOT(loginChanged(QString)));

    connect(this,SIGNAL(addLastTrades(QString, QList<TradesItem> *)),mainClass,SLOT(addLastTrades(QString, QList<TradesItem> *)));

	start();
Пример #30
0
void doExtract(int argc, char *argv[])
{

	if (argc < 3)
	{
		usage();
	}

	SetUpDriveAccessVariables(argv[2]);
	CreateClusterMap(argv[2]);
	SetupDiskAccessValues();

	HANDLE readDevice = CreateFile(openDrivePath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
	if (readDevice == INVALID_HANDLE_VALUE)
	{
		showErrorMessage(GetLastError());
		exit(9);
	}

	LARGE_INTEGER there;
	SetFilePointerEx(readDevice, seekTo, &there, FILE_BEGIN);

	unsigned char *message = (unsigned char *)calloc(bytesPerClust.LowPart, sizeof(unsigned char));
	
	DWORD bytes;
	/* Read the first sector so that we can get the size. (This is the first 5 bytes). */
	ReadFile(readDevice, message, bytesPerSect, &bytes, NULL);

	char size[6];
	memcpy(size, message, 5);
	size[5] = 0;

	int messageSize = atoi(size) + 5;

	/* Calculate the remaining bytes that we need to read. */
	int sectorsToRead = messageSize / bytesPerSect;
	/* Normally the integer math will give use on less sector. This is good
	   since we have already read in one sector. But if the message size
	   is an even multiple of bytesPerSect then we need to decrement. */
	if ((messageSize % bytesPerSect) == 0) sectorsToRead--;

	/* Loop through and read the remaining sectors. */
	for (int i = 1; i < sectorsToRead; i++)
	{
		ReadFile(readDevice, &message[i*bytesPerSect], bytesPerSect, &bytes, NULL);
	}

	/* Important to close the handle. */
	CloseHandle(readDevice);

	/* See if we have any optional command line parameters. */
	for (int i = 3; i < argc; i++)
	{
		/* Check for DISPLAY */
		if (_stricmp(argv[i], "DISPLAY") == 0)
		{
			printf("%s\n", &message[5]);
		}
		/* Otherwise this is a save file. */
		else
		{
			FILE *fp = fopen(argv[i], "wb");
			if (fp != NULL)
			{
				fwrite(&message[5], sizeof(unsigned char), messageSize-5, fp);
				fclose(fp);
			}
		}
	}

	/* Free the buffers. */
	free(message);
	free(outbuffer);
	free(buffer);
}