void AsyncHttpRequest::BeginPut(std::string path, JsonTree reqData, std::function<void(std::string)>&& Callback)
{
	std::string paramstr = reqData.serialize();
	tcp::resolver::query	query(_hostname, "http");

	std::ostream request_stream(&_request);
	request_stream << "PUT " << path << " HTTP/1.1\r\n";
	request_stream << "Host: " << _hostname << "\r\n";
	request_stream << "Accept: */*\r\n";
	request_stream << "Connection: close\r\n";
	request_stream << "Content-Length: " << paramstr.size() << "\r\n\r\n";
	request_stream << paramstr;

	_callback = Callback;
	_resolver.async_resolve(query,
		std::bind(&AsyncHttpRequest::handle_resolve, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
}
Beispiel #2
0
std::vector<Joint *> SkeletonData::LoadSkeleton(std::string filePath) {
	//Not sure about this error catching setup
	std::vector<Joint*> joints;

	if( PathFileExistsA(filePath.c_str()) == TRUE)  { 
		try{
			JsonTree doc = JsonTree(loadFile(filePath));

			JsonTree jointsJson = doc.getChild( "joints" );
			Joint * parent = nullptr;
			unsigned int i = 0;
			for( JsonTree::ConstIter joint = jointsJson.begin(); joint != jointsJson.end(); ++joint ) {
				// Apparently, getKey DOESN't return an index if there is no key? (Even though it says it will in the json.h header...)
				//JsonTree jJson = jointsJson.getChild(joint->getKey());
				JsonTree jJson = jointsJson.getChild(i);
				Joint * j = readJoint(jJson);
				joints.push_back(j);
				i++;
			}
		}catch (std::exception ex) {
			//throw ex;
			throw std::exception("Invalid File Format. File may be out of date.");
		}
	}else{
		throw std::exception("File does not exist!");
	}
	return joints;
}
void OculusSocketServerApp::setup()
{
    mServerPort = 9005;

    string configPath = getAppPath().string() + "/config.json";
    
    if(fs::exists(configPath)) {
        JsonTree::ParseOptions options;
        options.ignoreErrors(true);

        try{
            JsonTree config = JsonTree( loadFile( configPath ));
            
            for( JsonTree::ConstIter cIt = config.begin(); cIt != config.end(); ++cIt )
            {
                if( "port" == (*cIt).getKey()){
                    mServerPort = std::stoi((*cIt).getValue());
                    console() << "Port found: " << mServerPort << std::endl;
                }
            }
            
        } catch(JsonTree::Exception ex){
            console() << "Unable to parse config file." << std::endl;
        }
    } else {
        console() << "No config file found." << std::endl;
    }

    mOculusConnected = false;
    mSocketConnected = false;
    
    mServer.addConnectCallback( &OculusSocketServerApp::onConnect, this );
	mServer.addDisconnectCallback( &OculusSocketServerApp::onDisconnect, this );
   
    mServer.listen(mServerPort);
    mOculusVR = Oculus::create();
    
    mBackgroundTexture = gl::Texture( loadImage( loadResource( RES_BACKGROUND_TEX ) ) );
}
Beispiel #4
0
void ColorCubePoints::fromJson(const JsonTree &tree)
{
    clear();
    mOrigin = tree.getValueForKey<float>("origin");

    const JsonTree& points = tree.getChild("points");
    for (unsigned i = 0; i < points.getNumChildren(); i++) {
        const JsonTree& point = points.getChild(i);
        push(point.getValueAtIndex<float>(0),
             point.getValueAtIndex<float>(1),
             point.getValueAtIndex<float>(2));
    }
}
Beispiel #5
0
std::string Server::sendToServerPrintInfo()
{
	if (!RELEASE_VER) return SERVER_OK;

	std::map<string,string> strings;
	strings.insert(pair<string, string>( "action" , "print_count"));
	strings.insert(pair<string, string>( "cnt" ,  "1"));	
	string request =  Curl::post( SERVER"/save.php", strings);

	JsonTree jTree;

	try 
	{
		jTree = JsonTree(request);
		console()<<"PHOTO NUMS   "<< jTree.getChild("cnt").getValue()<<std::endl;
		return SERVER_OK;
	}
	catch(...)
	{

	}

	return SERVER_ERROR;
}
Beispiel #6
0
std::string   Server::sendFbSharePlus()
{
	if (!RELEASE_VER) return SERVER_OK;

	std::map<string,string> strings;
	strings.insert(pair<string, string>( "action" , "cnt"));
	strings.insert(pair<string, string>( "cnt" ,     "1"));
	strings.insert(pair<string, string>( "type" ,  "fb"));
	string request =  Curl::post( SERVER"/save.php", strings);

	JsonTree jTree;

	try 
	{
		jTree = JsonTree(request);
		console()<<"Facebook PLUS   "<< jTree.getChild("cnt").getValue()<<std::endl;
		return SERVER_OK;
	}
	catch(...)
	{

	}
	return SERVER_ERROR;
}
//! to json
JsonTree	WarpPerspectiveBilinear::toJson() const
{
	JsonTree		json = WarpBilinear::toJson();
	if (json.hasChild("warp")) {
		JsonTree warp(json.getChild("warp"));
		// set corners
		JsonTree	corners = JsonTree::makeArray("corners");
		for (unsigned i = 0; i < 4; ++i) {
			vec2 corner = mWarp->getControlPoint(i);
			JsonTree	cr;
			cr.addChild(ci::JsonTree("corner", i));
			cr.addChild(ci::JsonTree("x", corner.x));
			cr.addChild(ci::JsonTree("y", corner.y));

			corners.pushBack(cr);
		}
		warp.pushBack(corners);
		json.pushBack(warp);
	}
	return json;
}
Beispiel #8
0
void ColorCubePoints::toJson(JsonTree &tree)
{
    JsonTree points = JsonTree::makeArray("points");
 
    for (unsigned i = 0; i < mPoints.size(); i++) {
        JsonTree point;
        point.addChild(JsonTree("", mPoints[i].x));
        point.addChild(JsonTree("", mPoints[i].y));
        point.addChild(JsonTree("", mPoints[i].z));
        points.addChild(point);
    }

    tree.addChild(JsonTree("origin", mOrigin));
    tree.addChild(points);
}
Beispiel #9
0
JsonTree BSplineEditor::save()
{
	JsonTree tree = View::save();
	JsonTree subtree = JsonTree::makeArray( "POINTS" );
	for( auto &it : mControlPoints ) {
		vec2 mapped = norm( it );
		JsonTree subsubtree;
		subsubtree.addChild( JsonTree( "X", mapped.x ) );
		subsubtree.addChild( JsonTree( "Y", mapped.y ) );
		subtree.addChild( subsubtree );
	}
	if( subtree.getNumChildren() ) {
		tree.addChild( subtree );
	}
	return tree;
}
Beispiel #10
0
JsonTree View::save()
{
    JsonTree tree; 
    tree.addChild( JsonTree( "NAME", getName() ) );
    tree.addChild( JsonTree( "ID", getID() ) );
    tree.addChild( JsonTree( "TYPE", getType() ) );
    JsonTree subtree = JsonTree::makeArray( "SUBVIEWS" );
    for ( auto &it : mSubViews )
    {
        if( it->isSaveable() )
        {
            subtree.addChild( it->save() );
        }
    }
    if( subtree.getNumChildren() )
    {
        tree.addChild( subtree );
    }
    return tree;
}
Beispiel #11
0
// Function the background thread lives in
void TweetStream::serviceTweets()
{
	ThreadSetup threadSetup;
	std::string nextQueryString = "?q=" + Url::encode( mSearchPhrase );
	JsonTree searchResults;
	JsonTree::ConstIter resultIt = searchResults.end();

	// This function loops until the app quits. Each iteration a pulls out the next result from the Twitter API query.
	// When it reaches the last result of the current query it issues a new one, based on the "refresh_url" property
	// of the current query.
	// The loop doesn't spin (max out the processor) because ConcurrentCircularBuffer.pushFront() non-busy-waits for a new
	// slot in the circular buffer to become available.
	while( ! mCanceled ) {
		if( resultIt == searchResults.end() ) { 		// are we at the end of the results of this JSON query?
			// issue a new query
			try {
				JsonTree queryResult = queryTwitter( nextQueryString );
				// the next query will be the "refresh_url" of this one.
				nextQueryString = queryResult["refresh_url"].getValue();
				searchResults = queryResult.getChild( "results" );
				resultIt = searchResults.begin();
			}
			catch( ci::Exception &exc ) {
				// our API query failed: put up a "tweet" with our error
				CI_LOG_W( "exception caught parsing query: " << exc.what() );
				mBuffer.pushFront( Tweet( "Twitter API query failed", "sadness", SurfaceRef() ) );
				ci::sleep( 2000 ); // try again in 2 seconds
			}
		}
		if( resultIt != searchResults.end() ) {
			try {
				// get the URL and load the image for this profile
				Url profileImgUrl = (*resultIt)["profile_image_url"].getValue<Url>();
				SurfaceRef userIcon = Surface::create( loadImage( loadUrl( profileImgUrl ) ) );
				// pull out the text of the tweet and replace any XML-style escapes
				string text = replaceEscapes( (*resultIt)["text"].getValue() );
				string userName = (*resultIt)["from_user"].getValue();
				mBuffer.pushFront( Tweet( text, userName, userIcon ) );
			}
			catch( ci::Exception &exc ) {
				CI_LOG_W( "exception caught parsing search results: " << exc.what() );
			}
			++resultIt;
		}
	}
}
Beispiel #12
0
	void PretzelGlobal::loadSettings(fs::path settingsPath){
		fs::path loadPath = settingsPath;
		if (loadPath.string() == ""){
			loadPath = getAppPath() / "guiSettings" / "settings.json";
		}

		if (!fs::exists(loadPath)){
			console() << loadPath << " does not exist" << endl;
		}
		else{
			JsonTree loadTree(loadFile(loadPath));
			JsonTree appSettings = loadTree.getChild(0);

			for (int i = 0; i < mParamList.size(); i++){
				string pName = mParamList[i].name;
				switch (mParamList[i].type){
				case _FLOAT:
					if (appSettings.hasChild(pName)){
						float fVal = appSettings.getChild(pName).getValue<float>();
						*((float*)mParamList[i].value) = fVal;
					}
					break;
				case _INT:
					if (appSettings.hasChild(pName)){
						int fVal = appSettings.getChild(pName).getValue<int>();
						*((int*)mParamList[i].value) = fVal;
					}
					break;
				case _BOOL:
					if (appSettings.hasChild(pName)){
						bool bVal = appSettings.getChild(pName).getValue<float>();
						*((bool*)mParamList[i].value) = bVal;
					}
					break;
				default:
					console() << "Pretzel :: Can't load settings type " << endl;
					break;
				}
			}
		}
	}
Beispiel #13
0
void View::load( const JsonTree &data )
{
    if( data.hasChild( "SUBVIEWS" ) && mLoadSubViews )
    {
        JsonTree tree = data.getChild( "SUBVIEWS" );
        int numSubViews = tree.getNumChildren();
        for(int i = 0; i < numSubViews; i++)
        {
            JsonTree sub = tree[i];
            ViewRef subview = getSubView( sub.getValueForKey( "NAME" ) );
            if( subview )
            {
                subview->load( sub ); 
            }
        }
    }    
}
Beispiel #14
0
	void PretzelGlobal::saveSettings(fs::path settingsPath){
		fs::path appPath = settingsPath;

		if (appPath.string() == ""){
			appPath = getAppPath() / "guiSettings";

			if (!fs::exists(appPath)){
				CI_LOG_W( "Pretzel :: " ) << appPath << " does not exist. Creating it.";
				fs::create_directory(appPath);
			}
			appPath /= "settings.json";
		}

		JsonTree pSettings = JsonTree::makeObject("pretzelSettings");
		std::string tmp;
		for (int i = 0; i < mParamList.size(); i++){
			switch (mParamList[i].type){
                case _FLOAT:{
                    pSettings.pushBack(JsonTree(mParamList[i].name, toString(*(float*)mParamList[i].value)));
                    break;
                }case _INT:{
                    pSettings.pushBack(JsonTree(mParamList[i].name, toString(*(int*)mParamList[i].value)));
                    break;
                }case _BOOL:{
                    tmp = ((*(bool*)mParamList[i].value) == true) ? "1" : "0";
                    pSettings.pushBack(JsonTree(mParamList[i].name, tmp));
                    break;
                }case _STRING:{
                    pSettings.pushBack(JsonTree(mParamList[i].name, (*(std::string*)mParamList[i].value)));
                    break;
                }case _VEC2:{
                    JsonTree tt;
                    tt = tt.makeArray(mParamList[i].name);
                    tt.pushBack( JsonTree("x", toString(((vec2*)mParamList[i].value)->x)) );
                    tt.pushBack( JsonTree("y", toString(((vec2*)mParamList[i].value)->y)) );
                    pSettings.pushBack( tt );
                    break;
                }case _VEC3:{
                    JsonTree tt;
                    tt = tt.makeArray(mParamList[i].name);
                    tt.pushBack( JsonTree("x", toString(((vec3*)mParamList[i].value)->x)) );
                    tt.pushBack( JsonTree("y", toString(((vec3*)mParamList[i].value)->y)) );
                    tt.pushBack( JsonTree("z", toString(((vec3*)mParamList[i].value)->z)) );
                    pSettings.pushBack( tt );
                    break;
                }case _COLOR:{
                    JsonTree tt;
                    tt = tt.makeArray(mParamList[i].name);
                    tt.pushBack( JsonTree("r", toString(((Color*)mParamList[i].value)->r)) );
                    tt.pushBack( JsonTree("g", toString(((Color*)mParamList[i].value)->g)) );
                    tt.pushBack( JsonTree("b", toString(((Color*)mParamList[i].value)->b)) );
                    pSettings.pushBack( tt );
                    break;
                }case _COLORA:{
                    JsonTree tt;
                    tt = tt.makeArray(mParamList[i].name);
                    tt.pushBack( JsonTree("r", toString(((ColorA*)mParamList[i].value)->r)) );
                    tt.pushBack( JsonTree("g", toString(((ColorA*)mParamList[i].value)->g)) );
                    tt.pushBack( JsonTree("b", toString(((ColorA*)mParamList[i].value)->b)) );
                    tt.pushBack( JsonTree("a", toString(((ColorA*)mParamList[i].value)->a)) );
                    pSettings.pushBack( tt );
                    break;
                }default: {
                    break;
                }
			}
		}

		JsonTree root;
		root.pushBack(pSettings);
		root.write(appPath, JsonTree::WriteOptions());
        
        signalOnSettingsSave.emit();
	}
Beispiel #15
0
JsonTree::ExcNonConvertible::ExcNonConvertible( const JsonTree &node ) throw()
{
	sprintf( mMessage, "Unable to convert value for node: %s", node.getPath().c_str() );
}
Beispiel #16
0
JsonTree::ExcChildNotFound::ExcChildNotFound( const JsonTree &node, const string &childPath ) throw()
{
	sprintf( mMessage, "Could not find child: %s for node: %s", childPath.c_str(), node.getPath().c_str() );
}
Beispiel #17
0
//! Find pointer to node at specified path
JsonTree* JsonTree::getNodePtr( const string &relativePath, bool caseSensitive, char separator ) const
{
    // Format path into dotted address
	std::string path = boost::replace_all_copy( relativePath, "[", std::string( 1, separator ) );
	path = boost::replace_all_copy( path, "'", "");
	path = boost::replace_all_copy( path, "]", "");

    // Start search from this node
	JsonTree *curNode = const_cast<JsonTree*>( this );
    
    // Split address at dot and iterate tokens
	vector<string> pathComponents = split( path, separator );
	for( vector<string>::const_iterator pathIt = pathComponents.begin(); pathIt != pathComponents.end(); ++pathIt ) {
        // Declare target node
		ConstIter node;

        // The key is numeric
		if( isIndex( *pathIt ) ) {
            // Find child which uses this index as its key
			uint32_t index = boost::lexical_cast<int32_t>( *pathIt );
			uint32_t i = 0;
			for ( node = curNode->getChildren().begin(); node != curNode->getChildren().end(); ++node, i++ ) {
				if ( i == index ) {
					break;
				}
			}
		} else {	
            // Iterate children
            node = curNode->getChildren().begin();
            while( node != curNode->getChildren().end() ) {  
                // Compare child's key to path component
                bool keysMatch = false;
                string key1 = node->getKey();
                string key2 = *pathIt;
                if( caseSensitive && key1 == key2 ) {
                    keysMatch = true;
                } else if ( !caseSensitive && ( boost::iequals( key1, key2 ) ) ) {
                    keysMatch = true;
                }
                
                // Break if found, advance node if not
                if( keysMatch ) {
                    break;
                } else {
                    ++node;
                }
                
            }
            
		}

        // Return null pointer if we're out of nodes to search, 
        // otherwise assign node and continue to search its children
		if( node == curNode->getChildren().end() ) {
            return 0;
        } else {
			curNode = const_cast<JsonTree*>( &( *node ) );
        }
	}

    // Return child
	return curNode;

}
void FaceController::saveFace()
{/*
 for (size_t i = 0, ilen= facesStoreVector.size(); i<ilen; i++)
	{
		JsonTree oneFaceJson;
		oneFaceJson.addChild( JsonTree( "texname", facesStoreVector[i].getTexName() ) );

		JsonTree facesDataJson = JsonTree::makeArray( "data" );

		auto points =  facesStoreVector[i].getPoints();
		for (size_t j = 0, ilen = points.size() ; j < ilen; j++)
		{
			JsonTree point;
			point.addChild(JsonTree( "x",points[j].x) );	
			point.addChild(JsonTree( "y",points[j].y) );	
			facesDataJson.pushBack(point);
		}
		oneFaceJson.addChild(facesDataJson );

		facesJson.pushBack(oneFaceJson);
	}

	doc.pushBack( facesJson );
	
	writeImage( getAppPath() /FACE_STORAGE_FOLDER/genericName, surf );
	doc.write( writeFile( getAppPath() / DATA_BASE_NAME ), JsonTree::WriteOptions() );	*/

	// SAVE LAST ONLY!!!!


	JsonTree doc;
	JsonTree facesJson = JsonTree::makeArray( "faces" );

	int id = facesStoreVector.size() - 1;

	JsonTree oneFaceJson;
	oneFaceJson.addChild( JsonTree( "texname", facesStoreVector[id].getTexName() ) );

	JsonTree facesDataJson = JsonTree::makeArray( "data" );

		auto points =  facesStoreVector[id].getPoints();
		for (size_t j = 0, ilen = points.size() ; j < ilen; j++)
		{
			JsonTree point;
			point.addChild(JsonTree( "x",points[j].x) );	
			point.addChild(JsonTree( "y",points[j].y) );	
			facesDataJson.pushBack(point);
		}
	oneFaceJson.addChild(facesDataJson );
	facesJson.pushBack(oneFaceJson);

	doc.pushBack( facesJson );

	string jsonName = "base_"+to_string(id) + ".json";	
	
	
	doc.write( writeFile( getAppPath() / JSON_STORAGE_FOLDER / jsonName ), JsonTree::WriteOptions() );

}
void TextureSequenceOptimizer::saveMax( fs::path path )
{
    if ( path == fs::path() ) {
        path = app::App::get()->getFolderPath();
        app::console() << "SAVE MAX: " << path << std::endl;
    }
    if( ! path.empty() ){
        
        fs::path jsonPath = path;
        jsonPath.append("sequence.json");
        JsonTree doc = JsonTree::makeObject();
        
        JsonTree size = JsonTree::makeObject("size");
        size.pushBack(JsonTree("width",  mOriOutline.getWidth()  ));
        size.pushBack(JsonTree("height", mOriOutline.getHeight() ));
        doc.pushBack(size);
        
        JsonTree sequence = JsonTree::makeArray("sequence");
        //go thru each surface
        for (int i = 0; i < mSurfaceRefs.size(); i++) {
            fs::path tempPath = path;
            
            //only clone the non-transparent area based on the offsets
            Surface tempSurf;
            JsonTree curImage = JsonTree::makeObject();
            
            if( mTrimMaxAreas[i].calcArea() == 0 ){
                app::console() << " Image is completely transparent: " << mFileNames[i] << std::endl;
                tempPath.append("transparent.png");
                
                // check if transparent pixel exists
                if( !fs::exists(tempPath) ){
                    // create transparent png if it doesn't exist
                    tempSurf = mSurfaceRefs[i]->clone( Area(0,0,10,10) );
                    writeImage( tempPath, tempSurf );
                }
                
                // point to transparent image
                curImage.pushBack(JsonTree("x", mTrimMaxAreas[i].x1));
                curImage.pushBack(JsonTree("y", mTrimMaxAreas[i].y1));
                curImage.pushBack(JsonTree("fileName", "transparent.png" ));
            }else{
                tempSurf = mSurfaceRefs[i]->clone(mTrimMaxAreas[i]);
                tempPath.append(toString(mFileNames[i]));
                writeImage( tempPath, tempSurf );
                curImage.pushBack(JsonTree("x", mTrimMaxAreas[i].x1));
                curImage.pushBack(JsonTree("y", mTrimMaxAreas[i].y1));
                curImage.pushBack(JsonTree("fileName", mFileNames[i] ));
            }
            sequence.pushBack(curImage);
            
            //app::console() << "saving: " << tempPath << " "<< mTrimMaxAreas[i] << std::endl;
            
            tempPath.clear();
        }
        doc.pushBack(sequence);
        doc.write( jsonPath, JsonTree::WriteOptions());
        //saveJson(path);
    }
}
Beispiel #20
0
// Function the background thread lives in
void InstagramStream::serviceGrams(string url)
{
	ThreadSetup threadSetup;
	std::string nextQueryString = url;
	
	JsonTree searchResults;
	JsonTree::ConstIter resultIt = searchResults.end();
	
	// This function loops until the app quits. Each iteration a pulls out the next result from the Twitter API query.
	// When it reaches the last result of the current query it issues a new one, based on the "refresh_url" property
	// of the current query.
	// The loop doesn't spin (max out the processor) because ConcurrentCircularBuffer.pushFront() non-busy-waits for a new
	// slot in the circular buffer to become available.
	JsonTree queryResult;
	while( ! mCanceled ) {
		if( resultIt == searchResults.end() ) {			// are we at the end of the results of this JSON query?
			// issue a new query
			try {
				queryResult = queryInstagram( nextQueryString );
				// the next query will be the "refresh_url" of this one.
				
				try {
					nextQueryString = queryResult["pagination"].getChild("next_url").getValue();
				}
				catch(...) {
					
				}
				
				searchResults = queryResult.getChild("data");
				resultIt = searchResults.begin();
				mIsConnected = true;
			}
			catch( ... ) {
				
				console() << "something broke" << endl;
				console() << queryResult << endl;
				console() << nextQueryString << endl;
				
				// check if it's a 420 error
				if(queryResult.getChild("meta").getChild("code").getValue() == "420"){
					console() << "420 error" << endl;
					mIsConnected = false;
				}
				
				ci::sleep( 1000 ); // try again in 1 second
			}
		}
		if( resultIt != searchResults.end() ) {
			try {
				
				string userName = (*resultIt)["user"]["username"].getValue();
				
				// get the URL and load this instagram image
				string imageUrl = (*resultIt)["images"]["standard_resolution"]["url"].getValue();
				Surface image( loadImage( loadUrl( imageUrl ) ) );
				// string imageUrl = "http://distilleryimage5.s3.amazonaws.com/1dd174cca14611e1af7612313813f8e8_7.jpg"; // Test image
				mBuffer.pushFront( Instagram( userName, imageUrl, image ) );
			}
			catch( ... ) { // just ignore any errors
				console() << "ERRORS FOUND" << endl;
			}
			++resultIt;
		}
	}
}
Beispiel #21
0
JsonTree Radio::save()
{
    JsonTree tree = View::save();
    if( mActive ) tree.addChild( JsonTree( "ACTIVE", mActive->getValue() ? mActive->getName() : "" ) );
    return tree;
}
Beispiel #22
0
JsonTree DialerT<T>::save()
{
    JsonTree tree = View::save();
    tree.addChild( JsonTree( "VALUE",  getValue() ) );
    return tree;
}
Beispiel #23
0
void TreeHeartbeat::getWorldTree()
{
   getLastEventId();

   try
   {
      JsonTree queryResult = queryWinChattyv2Server("getChatty");

      if(queryResult.hasChild("threads"))
      {
         AppMessageRef worldTreeBuiltMessage = AppMessage::create(AppMessage::message_type::WORLDTREE_BUILT);

         const JsonTree& threads = queryResult.getChild("threads");
         for(size_t thread_i = 0; thread_i < threads.getNumChildren(); thread_i++)
         {
            std::list<ChattyPostDataRef> list_of_posts_in_thread;

            const JsonTree& this_thread = threads.getChild(thread_i);
            if(this_thread.hasChild("posts"))
            {
               const JsonTree& posts = this_thread.getChild("posts");
               for(size_t post_i = 0; post_i < posts.getNumChildren(); post_i++)
               {
                  const JsonTree& post = posts.getChild(post_i);
                  list_of_posts_in_thread.push_back(getChattyPostDataRefFromJSONPost(post));
               }
            }

            // sort list into tree
            chatty_post_id thread_id = fromString<uint32_t>(this_thread["threadId"].getValue());
            ChattyPostDataRef thread_tree;
            
            for(std::list<ChattyPostDataRef>::iterator it = list_of_posts_in_thread.begin();
                it != list_of_posts_in_thread.end();
                it++)
            {
               if((*it)->m_id == thread_id)
               {
                  thread_tree = *it;
                  list_of_posts_in_thread.erase(it);
                  break;
               }
            }

            if(thread_tree)
            {
               thread_tree->adoptChildren(list_of_posts_in_thread);
               CI_ASSERT(list_of_posts_in_thread.size() == 0);
            }

            thread_tree->markAsRead(false);

            // add tree to list of thread trees
            worldTreeBuiltMessage->AsWorldTreeBuilt()->m_thread_tree_list.push_back(thread_tree);
         }

         if(!m_canceled)
         {
            ((LampApp*)app::App::get())->postMessage(worldTreeBuiltMessage);
         }
      }
   }
   catch(ci::Exception& exc)
   {
      CI_LOG_E("Error calling WCv2 method getChatty: " << exc.what());
      m_last_event_id = 0;
   }
}
void TextureSequenceOptimizer::saveJson( const fs::path& path )
{
    fs::path jsonPath = path;
    jsonPath.append("sequence.json");
    
    //save the offsets for each image into a json file
    JsonTree doc = JsonTree::makeObject();
    
    JsonTree size = JsonTree::makeObject();
    size.pushBack(JsonTree("width",  mOriOutline.getWidth()  ));
    size.pushBack(JsonTree("height", mOriOutline.getHeight() ));
    doc.pushBack(size);
    
    JsonTree sequence = JsonTree::makeArray("sequence");
    for (int i = 0; i < mTrimMaxAreas.size(); i ++) {
        JsonTree curImage = JsonTree::makeObject();
        curImage.pushBack(JsonTree("x", mTrimMaxAreas[i].x1));
        curImage.pushBack(JsonTree("y", mTrimMaxAreas[i].y1));
        curImage.pushBack(JsonTree("fileName", mFileNames[i] ));
        sequence.pushBack(curImage);
    }
    doc.pushBack(sequence);
    doc.write( jsonPath, JsonTree::WriteOptions());
}
Beispiel #25
0
	void PretzelGlobal::loadSettings(fs::path settingsPath){
		fs::path loadPath = settingsPath;
		if (loadPath.string() == ""){
			loadPath = getAppPath() / "guiSettings" / "settings.json";
		}

		if (!fs::exists(loadPath)){
			CI_LOG_W("Pretzel :: Can't load ") << loadPath << " Path does not exist.";
		}
		else{
			JsonTree loadTree(loadFile(loadPath));
			JsonTree appSettings = loadTree.getChild(0);

			for (int i = 0; i < mParamList.size(); i++){
				string pName = mParamList[i].name;
				switch (mParamList[i].type){
				case _FLOAT:
					if (appSettings.hasChild(pName)){
						float fVal = appSettings.getChild(pName).getValue<float>();
						*((float*)mParamList[i].value) = fVal;
					}
					break;
				case _INT:
					if (appSettings.hasChild(pName)){
						int fVal = appSettings.getChild(pName).getValue<int>();
						*((int*)mParamList[i].value) = fVal;
					}
					break;
				case _BOOL:
					if (appSettings.hasChild(pName)){
						bool bVal = appSettings.getChild(pName).getValue<float>();
						*((bool*)mParamList[i].value) = bVal;
					}
					break;
				case _STRING:
					if (appSettings.hasChild(pName)){
						std::string sVal = appSettings.getChild(pName).getValue<std::string>();
						*((std::string*)mParamList[i].value) = sVal;
					}
					break;
                case _VEC2:
                    if (appSettings.hasChild(pName)){
                        vec2 p;
                        p.x = appSettings.getChild(pName).getChild("x").getValue<float>();
                        p.y = appSettings.getChild(pName).getChild("y").getValue<float>();
                        *((vec2*)mParamList[i].value) = p;
                    }
                    break;
                case _VEC3:
                    if (appSettings.hasChild(pName)){
                        vec3 p;
                        p.x = appSettings.getChild(pName).getChild("x").getValue<float>();
                        p.y = appSettings.getChild(pName).getChild("y").getValue<float>();
                        p.z = appSettings.getChild(pName).getChild("z").getValue<float>();
                        *((vec3*)mParamList[i].value) = p;
                    }
                    break;
                case _COLOR:
                    if (appSettings.hasChild(pName)){
                        Color p;
                        p.r = appSettings.getChild(pName).getChild("r").getValue<float>();
                        p.g = appSettings.getChild(pName).getChild("g").getValue<float>();
                        p.b = appSettings.getChild(pName).getChild("b").getValue<float>();
                        *((Color*)mParamList[i].value) = p;
                    }
                    break;
                case _COLORA:
                    if (appSettings.hasChild(pName)){
                        ColorA p;
                        p.r = appSettings.getChild(pName).getChild("r").getValue<float>();
                        p.g = appSettings.getChild(pName).getChild("g").getValue<float>();
                        p.b = appSettings.getChild(pName).getChild("b").getValue<float>();
                        p.a = appSettings.getChild(pName).getChild("a").getValue<float>();
                        *((ColorA*)mParamList[i].value) = p;
                    }
                    break;
				default:
					CI_LOG_W( "Pretzel :: Unrecognized settings type.");
					break;
				}
			}
		}
        signalOnSettingsLoad.emit();
	}
void FaceController::loadFaces()
{
	/*

	JsonTree faces( doc.getChild( "faces" ) );
	
	facesStoreVector.clear();

	for( JsonTree::ConstIter face = faces.begin(); face != faces.end(); ++face ) {
		
		FaceObject newFace;	
		vector<Vec2f> points;

		string name =  face->getChild( "texname" ).getValue<string>();
		gl::Texture tex;
		try{
			tex = loadImage(getAppPath() /FACE_STORAGE_FOLDER/name);
		}
		catch(...)
		{
			continue;
		}



		JsonTree datas =JsonTree( face->getChild( "data" ));
		for( JsonTree::ConstIter data = datas.begin(); data != datas.end(); ++data ) {
			float x =  data->getChild( "x" ).getValue<float>();
			float y =  data->getChild( "y" ).getValue<float>();

			points.push_back(Vec2f(x,y));
		}
		newFace.setPoints(points);

		
		newFace.setTexName(name);

		
		newFace.setTexture(tex);
		
		facesStoreVector.push_back(newFace);
	}	*/


	facesStoreVector.clear();

	string path = getAppPath().string() + JSON_STORAGE_FOLDER;
	fs::path p(path);

	

	for (fs::directory_iterator it(p); it != fs::directory_iterator(); ++it)
	{
		if (fs::is_regular_file(*it))
		{
			JsonTree doc;
			try{
				 doc = JsonTree(loadFile(getAppPath() / JSON_STORAGE_FOLDER / it->path().filename().string()));
			}
			catch(...)
			{
				return;
			}

			JsonTree faces( doc.getChild( "faces" ) );

			for( JsonTree::ConstIter face = faces.begin(); face != faces.end(); ++face )
			{		
				FaceObject newFace;	
				vector<Vec2f> points;

				string name =  face->getChild( "texname" ).getValue<string>();
				gl::Texture tex;
				try{
					tex = loadImage(getAppPath() /FACE_STORAGE_FOLDER/name);
				}
				catch(...)
				{
					continue;
				}

				JsonTree datas =JsonTree( face->getChild( "data" ));
				for( JsonTree::ConstIter data = datas.begin(); data != datas.end(); ++data )
				{
					float x =  data->getChild( "x" ).getValue<float>();
					float y =  data->getChild( "y" ).getValue<float>();

					points.push_back(Vec2f(x,y));
				}

				newFace.setPoints(points);		
				newFace.setTexName(name);

				newFace.setTexture(tex);		
				facesStoreVector.push_back(newFace);
			}
		}
	}

}
Beispiel #27
0
void Param::save() {
  JsonTree Position;
  Position = JsonTree::makeObject("Position");
  Position.addChild(JsonTree("x", pos.x));
  Position.addChild(JsonTree("y", pos.y));
  Position.addChild(JsonTree("z", pos.z));
  
  JsonTree Size;
  Size = JsonTree::makeObject("Size");
  Size.addChild(JsonTree("x", size.x));
  Size.addChild(JsonTree("y", size.y));
  Size.addChild(JsonTree("z", size.z));
  
  JsonTree Color;
  Color = JsonTree::makeObject("Color");
  Color.addChild(JsonTree("r", color.r));
  Color.addChild(JsonTree("g", color.g));
  Color.addChild(JsonTree("b", color.b));
  Color.addChild(JsonTree("a", color.a));
  
  JsonTree data;
  data = JsonTree::makeObject(name);
  data.addChild(Position);
  data.addChild(Size);
  data.addChild(Color);
}
Beispiel #28
0
JsonTree TextInput::save()
{
	JsonTree tree = View::save();
	tree.addChild( JsonTree( "VALUE", getValue() ) );
	return tree;
}
Beispiel #29
0
void TreeHeartbeat::getNewEvents()
{
   try
   {
      JsonTree queryResult = queryWinChattyv2Server("waitForEvent?lastEventId=" + toString(m_last_event_id));

      if(queryResult.hasChild("lastEventId"))
      {
         std::string strvalue = queryResult["lastEventId"].getValue();

         if(strvalue.length() > 0)
         {
            m_last_event_id = fromString<uint32_t>(strvalue);
         }

         if(queryResult.hasChild("events"))
         {
            AppMessageRef worldTreeEventMessage = AppMessage::create(AppMessage::message_type::WORLDTREE_EVENT);

            const JsonTree& events = queryResult.getChild("events");
            for(size_t event_i = 0; event_i < events.getNumChildren(); event_i++)
            {
               const JsonTree& this_event = events.getChild(event_i);

               const JsonTree& event_data = this_event.getChild("eventData");

               strvalue = this_event["eventType"].getValue();

               if(strvalue == "newPost")
               {
                  const JsonTree& post = event_data.getChild("post");

                  worldTreeEventMessage->AsWorldTreeEvent()->m_new_posts_list.push_front(getChattyPostDataRefFromJSONPost(post));
               }
               else if(strvalue == "categoryChange")
               {

               }
               else if(strvalue == "serverMessage")
               {

               }
               else if(strvalue == "lolCountsUpdate")
               {

               }
            }

            sortChattyPostDataList(worldTreeEventMessage->AsWorldTreeEvent()->m_new_posts_list);

            if(!m_canceled)
            {
               ((LampApp*)app::App::get())->postMessage(worldTreeEventMessage);
            }
         }
      }
      else
      {
         ci::sleep(2000.0f);
      }
   }
   catch(ci::Exception& exc)
   {
      CI_LOG_E("Error calling WCv2 method waitForEvent: " << exc.what());
      ci::sleep(2000.0f);
   }
}
Beispiel #30
0
ChattyPostDataRef getChattyPostDataRefFromJSONPost(const JsonTree& post)
{
   ChattyPostDataRef post_data_ref = ChattyPostData::create();

   post_data_ref->m_id = fromString<uint32_t>(post["id"].getValue());
   post_data_ref->m_thread_id = fromString<uint32_t>(post["threadId"].getValue());
   post_data_ref->m_parent_id = fromString<uint32_t>(post["parentId"].getValue());
   post_data_ref->m_author = post["author"].getValue();
   post_data_ref->m_body = post["body"].getValue();

   replaceEncodingsInString(post_data_ref->m_body);

   std::string strvalue = post["category"].getValue();
   if(strvalue.length() > 0)
   {
           if(strvalue == "ontopic")        post_data_ref->m_category = category_type::NORMAL;
      else if(strvalue == "nws")            post_data_ref->m_category = category_type::NWS;
      else if(strvalue == "stupid")         post_data_ref->m_category = category_type::STUPID;
      else if(strvalue == "political")      post_data_ref->m_category = category_type::POLITICAL;
      else if(strvalue == "tangent")        post_data_ref->m_category = category_type::OFFTOPIC;
      else if(strvalue == "informative")    post_data_ref->m_category = category_type::INFORMATIVE;
      else if(strvalue == "nuked")          post_data_ref->m_category = category_type::NUKED;
   }

   strvalue = post["date"].getValue();
   if(strvalue.length() > 0)
   {
      std::tm post_time;
      memset(&post_time, 0, sizeof(std::tm));
      
#if defined(CINDER_MSW)
      sscanf_s(strvalue.c_str(), "%d-%d-%dT%d:%d",
               &post_time.tm_year,
               &post_time.tm_mon,
               &post_time.tm_mday,
               &post_time.tm_hour,
               &post_time.tm_min);
#else
      sscanf(strvalue.c_str(), "%d-%d-%dT%d:%d",
               &post_time.tm_year,
               &post_time.tm_mon,
               &post_time.tm_mday,
               &post_time.tm_hour,
               &post_time.tm_min);
#endif

      post_time.tm_year -= 1900;
      post_time.tm_mon -= 1;

#if defined(CINDER_MSW)
      post_data_ref->m_date_time = _mkgmtime(&post_time);
#else
      post_data_ref->m_date_time = timegm(&post_time); // and I have no idea if this is right
#endif
      // if mac doesn't have _mkgmtime, need to find a way to convert UTC to local
      //post_data_ref->m_date_time = std::mktime(&post_time);
   }

   if(post.hasChild("lols"))
   {
      const JsonTree& lols = post.getChild("lols");
      for(size_t lol_i = 0; lol_i < lols.getNumChildren(); lol_i++)
      {
         const JsonTree& lol = lols.getChild(lol_i);
         strvalue = lol["tag"].getValue();
         if(strvalue.length() > 0)
         {
            lol_type which_lol = LOL;
                 if(strvalue == "lol") which_lol = lol_type::LOL;
            else if(strvalue == "inf") which_lol = lol_type::INF;
            else if(strvalue == "unf") which_lol = lol_type::UNF;
            else if(strvalue == "tag") which_lol = lol_type::TAG;
            else if(strvalue == "wtf") which_lol = lol_type::WTF;
            else if(strvalue == "ugh") which_lol = lol_type::UGH;

            post_data_ref->m_lol_count[which_lol] = fromString<unsigned int>(lol["count"].getValue());
         }
      }
   }

   return post_data_ref;
}