示例#1
0
AbstractString * ZeroRankArray::write_to_string()
{
  Thread * thread = current_thread();
  bool print_readably = (thread->symbol_value(S_print_readably) != NIL);
  if (print_readably)
    {
      if (_element_type != T)
        signal_lisp_error(new PrintNotReadable(make_value(this)));
    }
  if (print_readably || thread->symbol_value(S_print_array) != NIL)
    {
      String * s = new String("#0A");
      if (aref(0) == make_value(this) && thread->symbol_value(S_print_circle) != NIL)
        {
          StringOutputStream * stream = new StringOutputStream(S_character);
          thread->execute(the_symbol(S_output_object)->function(), aref(0), make_value(stream));
          s->append(stream->get_string());
        }
      else
        s->append(::write_to_string(aref(0)));
      return s;
    }
  else
    return unreadable_string();
}
示例#2
0
bool BufferedConnectionWriter::applyConvertTextMode()
{
    if (convertTextModePending) {
        convertTextModePending = false;

        Bottle b;
        StringOutputStream sos;
        for (size_t i = 0; i < lst_used; i++) {
            yarp::os::ManagedBytes& m = *(lst[i]);
            sos.write(m.usedBytes());
        }
        const std::string& str = sos.str();
        b.fromBinary(str.c_str(), (int)str.length());
        std::string replacement = b.toString() + "\n";
        for (auto& i : lst) {
            delete i;
        }
        lst_used = 0;
        target = &lst;
        lst.clear();
        stopPool();
        Bytes data((char*)replacement.c_str(), replacement.length());
        appendBlockCopy(data);
    }
    return true;
}
示例#3
0
void CommandLineTestBase::testWriteHelp(ICommandLineModule *module)
{
    StringOutputStream     stream;
    CommandLineHelpContext context(&stream, eHelpOutputFormat_Console, nullptr, "test");
    context.setModuleDisplayName(formatString("%s %s", "test", module->name()));
    module->writeHelp(context);
    TestReferenceChecker   checker(rootChecker());
    checker.checkTextBlock(stream.toString(), "HelpOutput");
}
示例#4
0
void Scene_EntitySetClassname_Selected( const char* classname ){
	if ( GlobalSelectionSystem().countSelected() > 0 ) {
		StringOutputStream command;
		if( string_equal( classname, "worldspawn" ) )
			command << "ungroupSelectedEntities";
		else
			command << "entitySetClass -class " << classname;
		UndoableCommand undo( command.c_str() );
		GlobalSceneGraph().traverse( EntitySetClassnameSelected( classname ) );
	}
}
示例#5
0
int HttpUploader::upload(const StringBuffer& luid, InputStream* inputStream) 
{
    int status = 0;

    // safe checks
    if (!inputStream || !inputStream->getTotalSize()) {
        LOG.error("upload error: no data to transfer");
        return 1;
    }
    if (luid.empty() || syncUrl.empty()  || sourceURI.empty()) {
        LOG.error("upload error: some params are not set");
        return 2;
    }
    
    StringBuffer fullUrl = composeURL();
    URL url(fullUrl.c_str());
    HttpConnection* httpConnection = getHttpConnection();
   
    httpConnection->setCompression(false);
    status = httpConnection->open(url, HttpConnection::MethodPost);
    
    if (status) { 
        delete httpConnection;

        return status;
    }

    httpConnection->setKeepAlive(keepalive);
    httpConnection->setRequestChunkSize(maxRequestChunkSize);
   
    // Set headers (use basic auth)
    HttpAuthentication* auth = new BasicAuthentication(username, password);
    httpConnection->setAuthentication(auth);
    setRequestHeaders(luid, *httpConnection, *inputStream);
    
    // Send the HTTP request
    StringOutputStream response;
    status = httpConnection->request(*inputStream, response);
    LOG.debug("response returned = %s", response.getString().c_str());
    
    // Manage response headers
    if (useSessionID) {
        // Server returns the jsessionId in the Set-Cookie header, can be used for 
        // the subsequent calls of upload().
        StringBuffer hdr = httpConnection->getResponseHeader(HTTP_HEADER_SET_COOKIE);
        sessionID = httpConnection->parseJSessionId(hdr);
    }
    
    httpConnection->close();
    
    delete auth;
    delete httpConnection;
    return status;
}
 void testWrite() {
     report(0,"testing writing...");
     StringOutputStream sos;
     char txt[] = "Hello my friend";
     Bytes b(txt,ACE_OS::strlen(txt));
     sos.write(b);
     checkEqual(txt,sos.toString(),"single write");
     StringOutputStream sos2;
     sos2.write('y');
     sos2.write('o');
     checkEqual("yo",sos2.toString(),"multiple writes");
 }
示例#7
0
void Selection_SnapToGrid (void)
{
	StringOutputStream command;
	command << "snapSelected -grid " << GlobalGrid().getGridSize();
	UndoableCommand undo(command.toString());

	if (GlobalSelectionSystem().Mode() == SelectionSystem::eComponent) {
		GlobalSceneGraph().traverse(ComponentSnappableSnapToGridSelected(GlobalGrid().getGridSize()));
	} else {
		GlobalSceneGraph().traverse(SnappableSnapToGridSelected(GlobalGrid().getGridSize()));
	}
}
示例#8
0
文件: qe3.cpp 项目: raynorpat/cake
void Sys_SetTitle(const char *text, bool modified)
{
  StringOutputStream title;
  title << ConvertLocaleToUTF8(text);

  if(modified)
  {
    title << " *";
  }

  gtk_window_set_title(MainFrame_getWindow(), title.c_str());
}
示例#9
0
std::string MaterialSystem::getBlock (const std::string& texture)
{
	if (texture.empty())
		return "";

	const std::string textureDir = GlobalTexturePrefix_get();
	std::string skippedTextureDirectory = texture.substr(textureDir.length());

	if (skippedTextureDirectory.empty())
		return "";

	MaterialBlockMap::iterator i = _blocks.find(skippedTextureDirectory);
	if (i != _blocks.end())
		return i->second;

	if (!_materialLoaded)
		loadMaterials();

	if (!_materialLoaded)
		return "";

	StringOutputStream outputStream;

	StringInputStream inputStream(_material);
	AutoPtr<Tokeniser> tokeniser(GlobalScriptLibrary().createSimpleTokeniser(inputStream));
	int depth = 0;
	bool found = false;
	std::string token = tokeniser->getToken();
	while (token.length()) {
		if (token == "{") {
			depth++;
		} else if (token == "}") {
			depth--;
		}
		if (depth >= 1) {
			if (depth == 1 && token == "material") {
				token = tokeniser->getToken();
				if (token == skippedTextureDirectory) {
					found = true;
					outputStream << "{ material ";
				}
			}
			if (found)
				outputStream << token << " ";
		} else if (found) {
			outputStream << "}";
			break;
		}
		token = tokeniser->getToken();
	}
	return outputStream.toString();
}
示例#10
0
AbstractString * StandardObject::write_to_string()
{
  if (CL_fboundp(S_print_object) != NIL)
    {
      Thread * const thread = current_thread();
      StringOutputStream * stream = new StringOutputStream(S_character);
      thread->execute(the_symbol(S_print_object)->function(),
                      make_value(this),
                      make_value(stream));
      AbstractString * s = stream->get_string();
      return s;
    }
  else
    return unreadable_string();
}
示例#11
0
void CPointfile::saxEndElement (message_info_t *ctx, const xmlChar *name)
{
  if(string_equal(reinterpret_cast<const char*>(name), "polyline"))
  {
    // we are done
    GenerateDisplayList();
    SceneChangeNotify();
  }
  else if(string_equal(reinterpret_cast<const char*>(name), "point"))
  {
    Vector3 v;  
    sscanf(m_characters.c_str(), "%f %f %f\n", &v[0], &v[1], &v[2]);
    PushPoint(v);
    m_characters.clear();
  }
}
示例#12
0
          void visit(const char* name, Accelerator& accelerator)
          {
            StringOutputStream modifiers;
            modifiers << accelerator;

            {
              GtkTreeIter iter;
              gtk_list_store_append(m_store, &iter);
              gtk_list_store_set(m_store, &iter, 0, name, 1, modifiers.c_str(), -1);
            }
 
            if(!m_commandList.failed())
            {
              m_commandList << makeLeftJustified(name, 25) << " " << modifiers.c_str() << '\n';
            }
          }
示例#13
0
/// moves selected primitives to entity, which is or its primitive is ultimateSelected() or firstSelected()
void Entity_moveSelectedPrimitives( bool toLast ){
	if ( GlobalSelectionSystem().countSelected() < 2 ) {
		globalErrorStream() << "Source and target entity primitives should be selected!\n";
		return;
	}

	const scene::Path& path = toLast? GlobalSelectionSystem().ultimateSelected().path() : GlobalSelectionSystem().firstSelected().path();
	scene::Node& node = ( !Node_isEntity( path.top() ) && path.size() > 1 )? path.parent() : path.top();

	if ( Node_isEntity( node ) && node_is_group( node ) ) {
		StringOutputStream command;
		command << "movePrimitivesToEntity " << makeQuoted( Node_getEntity( node )->getEntityClass().name() );
		UndoableCommand undo( command.c_str() );
		Scene_parentSelectedBrushesToEntity( GlobalSceneGraph(), node );
	}
}
示例#14
0
	void visit( const char* name, Accelerator& accelerator ){
		if ( !strcmp( name, commandName ) ) {
			return;
		}
		if ( !allow ) {
			return;
		}
		if ( accelerator.key == 0 ) {
			return;
		}
		if ( accelerator == newAccel ) {
			StringOutputStream msg;
			msg << "The command " << name << " is already assigned to the key " << accelerator << ".\n\n"
				<< "Do you want to unassign " << name << " first?";
			EMessageBoxReturn r = gtk_MessageBox( widget, msg.c_str(), "Key already used", eMB_YESNOCANCEL );
			if ( r == eIDYES ) {
				// clear the ACTUAL accelerator too!
				disconnect_accelerator( name );
				// delete the modifier
				accelerator = accelerator_null();
				// empty the cell of the key binds dialog
				GtkTreeIter i;
				if ( gtk_tree_model_get_iter_first( GTK_TREE_MODEL( model ), &i ) ) {
					for (;; )
					{
						GValue val;
						memset( &val, 0, sizeof( val ) );
						gtk_tree_model_get_value( GTK_TREE_MODEL( model ), &i, 0, &val );
						const char *thisName = g_value_get_string( &val );;
						if ( !strcmp( thisName, name ) ) {
							gtk_list_store_set( GTK_LIST_STORE( model ), &i, 1, "", -1 );
						}
						g_value_unset( &val );
						if ( !gtk_tree_model_iter_next( GTK_TREE_MODEL( model ), &i ) ) {
							break;
						}
					}
				}
			}
			else if ( r == eIDCANCEL ) {
				// aborted
				allow = false;
			}
		}
	}
示例#15
0
    /**
     * Tests a GET on a specific URL, prints the response.
     */
    void testGET(const URL& testURL) 
    {
        LOG.debug("test GET on %s", testURL.fullURL);
        int ret = httpConnection.open(testURL, HttpConnection::MethodGet);
        LOG.debug("open, ret = %d", ret);
        
        BufferInputStream inputStream("");
        StringOutputStream outputStream;
        
        httpConnection.setRequestHeader(HTTP_HEADER_ACCEPT,          "*/*");
        httpConnection.setRequestHeader(HTTP_HEADER_CONTENT_LENGTH,  0);

        ret = httpConnection.request(inputStream, outputStream);
        LOG.debug("request, ret = %d", ret);
        LOG.debug("response = \n%s", outputStream.getString().c_str());
        
        httpConnection.close();
    }
示例#16
0
				void visit( const char* name, Accelerator& accelerator ){
					StringOutputStream modifiers;
					modifiers << accelerator;

					{
						GtkTreeIter iter;
						gtk_list_store_append( m_store, &iter );
						gtk_list_store_set( m_store, &iter, 0, name, 1, modifiers.c_str(), 2, false, 3, 800, -1 );
					}

					if ( !m_commandList.failed() ) {
						int l = strlen( name );
						m_commandList << name;
						while ( l++ < 25 )
							m_commandList << ' ';
						m_commandList << modifiers.c_str() << '\n';
					}
				}
示例#17
0
// End the move, this freezes the current transforms
void RadiantSelectionSystem::endMove() {
	freezeTransforms();

	// greebo: Deselect all faces if we are in brush and drag mode
	if (Mode() == ePrimitive) {
		if (ManipulatorMode() == eDrag) {
			GlobalSceneGraph().traverse(SelectAllComponentWalker(false, SelectionSystem::eFace));
			//Scene_SelectAll_Component(false, SelectionSystem::eFace);
		}
	}

	// Remove all degenerated brushes from the scene graph (should emit a warning)
	GlobalSceneGraph().traverse(RemoveDegenerateBrushWalker());

	_pivotMoving = false;
	pivotChanged();

	// Update the views
	SceneChangeNotify();

	// If we started an undoable operation, end it now and tell the console what happened
	if (_undoBegun) {
		StringOutputStream command;

		if (ManipulatorMode() == eTranslate) {
			command << "translateTool";
			outputTranslation(command);
		}
		else if (ManipulatorMode() == eRotate) {
			command << "rotateTool";
			outputRotation(command);
		}
		else if (ManipulatorMode() == eScale) {
			command << "scaleTool";
			outputScale(command);
		}
		else if (ManipulatorMode() == eDrag) {
			command << "dragTool";
		}

		// Finish the undo move
		GlobalUndoSystem().finish(command.toString());
	}
}
示例#18
0
bool WireTwiddler::write(yarp::os::Bottle& bot,
                         yarp::os::ManagedBytes& data) {
    StringOutputStream sos;
    if (!writer) {
        writer = ConnectionWriter::createBufferedConnectionWriter();
    }
    if (!writer) {
        return false;
    }
    SizedWriter *buf = writer->getBuffer();
    if (!buf) {
        return false;
    }
    buf->clear();
    bot.write(*writer);
    WireTwiddlerWriter twiddled_output(*buf,*this);
    twiddled_output.write(sos);
    std::string result = sos.toString();
    data = ManagedBytes(Bytes((char*)result.c_str(),result.length()),false);
    data.copy();
    return true;
}
示例#19
0
AbstractString * Condition::write_to_string()
{
  Thread * const thread = current_thread();
  if (CL_fboundp(S_print_object) != NIL)
    {
      StringOutputStream * stream = new StringOutputStream(S_character);
      thread->execute(the_symbol(S_print_object)->function(),
                      make_value(this),
                      make_value(stream));
      AbstractString * s = stream->get_string();
      return s;
    }
  if (thread->symbol_value(S_print_escape) == NIL && thread->symbol_value(S_print_readably) == NIL)
    {
      if (stringp(format_control()))
        {
          if (format_arguments() != NIL)
            return format_to_string(format_control(), format_arguments());
          else
            return the_string(format_control());
        }
    }
  return unreadable_string();
}
示例#20
0
void Brush_ConstructPrefab(Brush& brush, EBrushPrefab type, const AABB& bounds, std::size_t sides, const char* shader, const TextureProjection& projection)
{
  switch(type)
  {
  case eBrushCuboid:
    {
      UndoableCommand undo("brushCuboid");

      Brush_ConstructCuboid(brush, bounds, shader, projection);
    }
    break;
  case eBrushPrism:
    {
      int axis = GetViewAxis();
      StringOutputStream command;
      command << c_brushPrism_name << " -sides " << Unsigned(sides) << " -axis " << axis;
      UndoableCommand undo(command.c_str());

      Brush_ConstructPrism(brush, bounds, sides, axis, shader, projection);
    }
    break;
  case eBrushCone:
    {
      StringOutputStream command;
      command << c_brushCone_name << " -sides " << Unsigned(sides);
      UndoableCommand undo(command.c_str());

      Brush_ConstructCone(brush, bounds, sides, shader, projection);
    }
    break;
  case eBrushSphere:
    {
      StringOutputStream command;
      command << c_brushSphere_name << " -sides " << Unsigned(sides);
      UndoableCommand undo(command.c_str());

      Brush_ConstructSphere(brush, bounds, sides, shader, projection);
    }
    break;
  }
}
示例#21
0
bool XmlRpcCarrier::write(Protocol& proto, SizedWriter& writer) {
    //XmlRpc::setVerbosity(10);
    StringOutputStream sos;
    StringInputStream sis;
    writer.write(sos);
    sis.reset(sos.toString());
    String header;
    if (sender) {
        header = NetType::readLine(sis);
    }
    String body = NetType::readLine(sis);
    //printf("Asked to write: hdr %s body %s\n",
    //     header.c_str(), body.c_str());
    Value v;
    //printf("HEADER %s\n", header.c_str());
    if (header[0]=='q') {
        body = "yarp.quit";
        // XMLRPC does not need a quit message, this should get stripped
        return false;
    }
    Bottle *bot = v.asList();
    //Bottle aux;
    bot->fromString(body.c_str());
    ConstString methodName;
    if (sender) {
        methodName = bot->get(0).toString();
        *bot = bot->tail();
    }
    XmlRpcValue args;
    if (bot->size()==1) {
        toXmlRpcValue(bot->get(0),args);
    } else {
        toXmlRpcValue(v,args);
    }
    //printf("xmlrpc block to write is %s\n", args.toXml().c_str());
    std::string req;
    if (sender) {
        const Address& addr = host.isValid()?host:proto.getStreams().getRemoteAddress();
        XmlRpcClient c(addr.getName().c_str(),(addr.getPort()>0)?addr.getPort():80);
        c.generateRequest(methodName.c_str(),args);
        req = c.getRequest();
    } else {
        XmlRpcServerConnection c(0,NULL);
        c.generateResponse(args.toXml());
        req = c.getResponse();
    }
    int start = 0;
    //printf("converts to %s\n", req.c_str());
    if (sender) {
        if (req.length()<8) {
            fprintf(stderr, "XmlRpcCarrier fail, %s:%d\n", __FILE__, __LINE__);
            return false;
        }
        for (int i=0; i<(int)req.length(); i++) {
            if (req[i] == '\n') {
                start++;
                break;
            }
            start++;
        }
        if (!firstRound) {
            Bytes b((char*)http.c_str(),http.length());
            proto.os().write(b);
        }
        firstRound = false;
    }
    Bytes b((char*)req.c_str()+start,req.length()-start);
    //printf("WRITING [%s]\n", req.c_str()+start);
    proto.os().write(b);

    return proto.os().isOk();
}
示例#22
0
// only "point" is expected to have characters around here
void CPointfile::saxCharacters (message_info_t *ctx, const xmlChar *ch, int len)
{
  m_characters.write(reinterpret_cast<const char*>(ch), len);
}
示例#23
0
bool XmlRpcCarrier::write(ConnectionState& proto, SizedWriter& writer) {
    StringOutputStream sos;
    StringInputStream sis;
    writer.write(sos);
    sis.reset(sos.toString());
    ConstString header;
    if (sender) {
        header = sis.readLine();
    }
    ConstString body = sis.readLine();
    Value v;
    if (header.length()>0 && header[0]=='q') {
        body = "yarp.quit";
        // XMLRPC does not need a quit message, this should get stripped
        return false;
    }
    Bottle *bot = v.asList();
    bot->fromString(body.c_str());
    ConstString methodName;
    if (sender) {
        methodName = bot->get(0).toString();
        *bot = bot->tail();
    }
    XmlRpcValue args;
    if (bot->size()==1) {
        toXmlRpcValue(bot->get(0),args);
    } else {
        toXmlRpcValue(v,args);
    }
    std::string req;
    if (sender) {
        const Contact& addr = host.isValid()?host:proto.getStreams().getRemoteAddress();
        XmlRpcClient c(addr.getHost().c_str(),(addr.getPort()>0)?addr.getPort():80);
        c.generateRequest(methodName.c_str(),args);
        req = c.getRequest();
    } else {
        XmlRpcServerConnection c(0,NULL);
        c.generateResponse(args.toXml());
        req = c.getResponse();
    }
    int start = 0;
    if (sender) {
        if (req.length()<8) {
            fprintf(stderr, "XmlRpcCarrier fail, %s:%d\n", __FILE__, __LINE__);
            return false;
        }
        for (int i=0; i<(int)req.length(); i++) {
            if (req[i] == '\n') {
                start++;
                break;
            }
            start++;
        }
        if (!firstRound) {
            Bytes b((char*)http.c_str(),http.length());
            proto.os().write(b);
        }
        firstRound = false;
    }
    Bytes b((char*)req.c_str()+start,req.length()-start);
    proto.os().write(b);

    return proto.os().isOk();
}
示例#24
0
void Entity_createFromSelection( const char* name, const Vector3& origin ){
#if 0
	if ( string_equal_nocase( name, "worldspawn" ) ) {
		gtk_MessageBox( GTK_WIDGET( MainFrame_getWindow() ), "Can't create an entity with worldspawn.", "info" );
		return;
	}
#else
	const scene::Node* world_node = Map_FindWorldspawn( g_map );
	if ( world_node && string_equal( name, "worldspawn" ) ) {
//		GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( MainFrame_getWindow() ), "There's already a worldspawn in your map!", "Info", eMB_OK, eMB_ICONDEFAULT );
		UndoableCommand undo( "ungroupSelectedPrimitives" );
		Scene_parentSelectedBrushesToEntity( GlobalSceneGraph(), Map_FindOrInsertWorldspawn( g_map ) ); //=no action, if no worldspawn (but one inserted) (since insertion deselects everything)
		//Scene_parentSelectedBrushesToEntity( GlobalSceneGraph(), *Map_FindWorldspawn( g_map ) ); = crash, if no worldspawn
		return;
	}
#endif

	StringOutputStream command;
	command << "entityCreate -class " << name;
	UndoableCommand undo( command.c_str() );

	EntityClass* entityClass = GlobalEntityClassManager().findOrInsert( name, true );

	const bool isModel = entityClass->miscmodel_is
				   || ( GlobalSelectionSystem().countSelected() == 0 && classname_equal( name, "func_static" ) && g_pGameDescription->mGameType == "doom3" );

	const bool brushesSelected = Scene_countSelectedBrushes( GlobalSceneGraph() ) != 0;

	//is important to have retexturing here; if doing in the end, undo doesn't succeed;
	if ( string_compare_nocase_n( name, "trigger_", 8 ) == 0 && brushesSelected && !entityClass->fixedsize ){
		//const char* shader = GetCommonShader( "trigger" ).c_str();
		Scene_PatchSetShader_Selected( GlobalSceneGraph(), GetCommonShader( "trigger" ).c_str() );
		Scene_BrushSetShader_Selected( GlobalSceneGraph(), GetCommonShader( "trigger" ).c_str() );
	}

	if ( !( entityClass->fixedsize || isModel ) && !brushesSelected ) {
		globalErrorStream() << "failed to create a group entity - no brushes are selected\n";
		return;
	}

	AABB workzone( aabb_for_minmax( Select_getWorkZone().d_work_min, Select_getWorkZone().d_work_max ) );


	NodeSmartReference node( GlobalEntityCreator().createEntity( entityClass ) );

	Node_getTraversable( GlobalSceneGraph().root() )->insert( node );

	scene::Path entitypath( makeReference( GlobalSceneGraph().root() ) );
	entitypath.push( makeReference( node.get() ) );
	scene::Instance& instance = findInstance( entitypath );

	if ( entityClass->fixedsize || ( isModel && !brushesSelected ) ) {
		//Select_Delete();

		Transformable* transform = Instance_getTransformable( instance );
		if ( transform != 0 ) {
			transform->setType( TRANSFORM_PRIMITIVE );
			transform->setTranslation( origin );
			transform->freezeTransform();
		}

		GlobalSelectionSystem().setSelectedAll( false );

		Instance_setSelected( instance, true );
	}
	else
	{
		if ( g_pGameDescription->mGameType == "doom3" ) {
			Node_getEntity( node )->setKeyValue( "model", Node_getEntity( node )->getKeyValue( "name" ) );
		}

		Scene_parentSelectedBrushesToEntity( GlobalSceneGraph(), node );
		Scene_forEachChildSelectable( SelectableSetSelected( true ), instance.path() );
	}

	// tweaking: when right click dropping a light entity, ask for light value in a custom dialog box
	// see SF bug 105383

	if ( g_pGameDescription->mGameType == "hl" ) {
		// FIXME - Hydra: really we need a combined light AND color dialog for halflife.
		if ( string_equal_nocase( name, "light" )
			 || string_equal_nocase( name, "light_environment" )
			 || string_equal_nocase( name, "light_spot" ) ) {
			int intensity = g_iLastLightIntensity;

			if ( DoLightIntensityDlg( &intensity ) == eIDOK ) {
				g_iLastLightIntensity = intensity;
				char buf[30];
				sprintf( buf, "255 255 255 %d", intensity );
				Node_getEntity( node )->setKeyValue( "_light", buf );
			}
		}
	}
	else if ( string_equal_nocase( name, "light" ) ) {
		if ( g_pGameDescription->mGameType != "doom3" ) {
			int intensity = g_iLastLightIntensity;

			if ( DoLightIntensityDlg( &intensity ) == eIDOK ) {
				g_iLastLightIntensity = intensity;
				char buf[10];
				sprintf( buf, "%d", intensity );
				Node_getEntity( node )->setKeyValue( "light", buf );
			}
		}
		else if ( brushesSelected ) { // use workzone to set light position/size for doom3 lights, if there are brushes selected
			AABB bounds( Doom3Light_getBounds( workzone ) );
			StringOutputStream key( 64 );
			key << bounds.origin[0] << " " << bounds.origin[1] << " " << bounds.origin[2];
			Node_getEntity( node )->setKeyValue( "origin", key.c_str() );
			key.clear();
			key << bounds.extents[0] << " " << bounds.extents[1] << " " << bounds.extents[2];
			Node_getEntity( node )->setKeyValue( "light_radius", key.c_str() );
		}
	}

	if ( isModel ) {
		const char* model = misc_model_dialog( GTK_WIDGET( MainFrame_getWindow() ) );
		if ( model != 0 ) {
			Node_getEntity( node )->setKeyValue( entityClass->miscmodel_key() , model );
		}
	}
}
示例#25
0
gboolean accelerator_window_key_press( GtkWidget *widget, GdkEventKey *event, gpointer dialogptr ){
	command_list_dialog_t &dialog = *(command_list_dialog_t *) dialogptr;

	if ( !dialog.m_waiting_for_key ) {
		return false;
	}

#if 0
	if ( event->is_modifier ) {
		return false;
	}
#else
	switch ( event->keyval )
	{
	case GDK_Shift_L:
	case GDK_Shift_R:
	case GDK_Control_L:
	case GDK_Control_R:
	case GDK_Caps_Lock:
	case GDK_Shift_Lock:
	case GDK_Meta_L:
	case GDK_Meta_R:
	case GDK_Alt_L:
	case GDK_Alt_R:
	case GDK_Super_L:
	case GDK_Super_R:
	case GDK_Hyper_L:
	case GDK_Hyper_R:
		return false;
	}
#endif

	dialog.m_waiting_for_key = false;

	// 7. find the name of the accelerator
	GValue val;
	memset( &val, 0, sizeof( val ) );
	gtk_tree_model_get_value( GTK_TREE_MODEL( dialog.m_model ), &dialog.m_command_iter, 0, &val );
	const char *commandName = g_value_get_string( &val );;
	Shortcuts::iterator thisShortcutIterator = g_shortcuts.find( commandName );
	if ( thisShortcutIterator == g_shortcuts.end() ) {
		gtk_list_store_set( GTK_LIST_STORE( dialog.m_model ), &dialog.m_command_iter, 2, false, -1 );
		gtk_widget_set_sensitive( GTK_WIDGET( dialog.m_list ), true );
		return true;
	}

	// 8. build an Accelerator
	Accelerator newAccel( event->keyval, (GdkModifierType) event->state );

	// 8. verify the key is still free, show a dialog to ask what to do if not
	class VerifyAcceleratorNotTaken : public CommandVisitor
	{
	const char *commandName;
	const Accelerator &newAccel;
	GtkWidget *widget;
	GtkTreeModel *model;
public:
	bool allow;
	VerifyAcceleratorNotTaken( const char *name, const Accelerator &accelerator, GtkWidget *w, GtkTreeModel *m ) : commandName( name ), newAccel( accelerator ), widget( w ), model( m ), allow( true ){
	}
	void visit( const char* name, Accelerator& accelerator ){
		if ( !strcmp( name, commandName ) ) {
			return;
		}
		if ( !allow ) {
			return;
		}
		if ( accelerator.key == 0 ) {
			return;
		}
		if ( accelerator == newAccel ) {
			StringOutputStream msg;
			msg << "The command " << name << " is already assigned to the key " << accelerator << ".\n\n"
				<< "Do you want to unassign " << name << " first?";
			EMessageBoxReturn r = gtk_MessageBox( widget, msg.c_str(), "Key already used", eMB_YESNOCANCEL );
			if ( r == eIDYES ) {
				// clear the ACTUAL accelerator too!
				disconnect_accelerator( name );
				// delete the modifier
				accelerator = accelerator_null();
				// empty the cell of the key binds dialog
				GtkTreeIter i;
				if ( gtk_tree_model_get_iter_first( GTK_TREE_MODEL( model ), &i ) ) {
					for (;; )
					{
						GValue val;
						memset( &val, 0, sizeof( val ) );
						gtk_tree_model_get_value( GTK_TREE_MODEL( model ), &i, 0, &val );
						const char *thisName = g_value_get_string( &val );;
						if ( !strcmp( thisName, name ) ) {
							gtk_list_store_set( GTK_LIST_STORE( model ), &i, 1, "", -1 );
						}
						g_value_unset( &val );
						if ( !gtk_tree_model_iter_next( GTK_TREE_MODEL( model ), &i ) ) {
							break;
						}
					}
				}
			}
			else if ( r == eIDCANCEL ) {
				// aborted
				allow = false;
			}
		}
	}
	} verify_visitor( commandName, newAccel, widget, dialog.m_model );
	GlobalShortcuts_foreach( verify_visitor );

	gtk_list_store_set( GTK_LIST_STORE( dialog.m_model ), &dialog.m_command_iter, 2, false, -1 );
	gtk_widget_set_sensitive( GTK_WIDGET( dialog.m_list ), true );

	if ( verify_visitor.allow ) {
		// clear the ACTUAL accelerator first
		disconnect_accelerator( commandName );

		thisShortcutIterator->second.first = newAccel;

		// write into the cell
		StringOutputStream modifiers;
		modifiers << newAccel;
		gtk_list_store_set( GTK_LIST_STORE( dialog.m_model ), &dialog.m_command_iter, 1, modifiers.c_str(), -1 );

		// set the ACTUAL accelerator too!
		connect_accelerator( commandName );
	}

	g_value_unset( &val );

	dialog.m_model = NULL;

	return true;
}
/*
    Returns the token for wassup based authentication or an empty string if errors occur
    Parameters:
                username: as inserted by the user
                password: as inserted by the user
                err: output flag to check for errors
 */
std::string WassupTokenRequestManager::getToken(std::string username, std::string password, bool *err, int* requestCode)
{
    std::string token = "";
    *err = false;
    *requestCode = HTTP_OK;
    
    //request token over http
    LOG.debug("Getting wassup token");
    
    StringOutputStream response;
    HttpConnection *httpConnection = NULL;
    URL requestUrl;

    std::string formattedURL(_wassupURI);
    std::stringstream ss;
    std::string xmlResponse;

    //URL encode usr and pwd
    const char * usernameEncoded = URL::urlEncode(username.c_str());
    const char * passwordEncoded = URL::urlEncode(password.c_str());
    
    ss << _wassupURI << "?" << _wassupUsrParam << usernameEncoded << "&" << _wassupPwdParam << passwordEncoded << "&" << _wassupAdditionalParam;
    
    formattedURL = ss.str();
    
    requestUrl.setURL(formattedURL.c_str());
    
    httpConnection = new HttpConnection(_userAgent);
    httpConnection->setSSLVerifyServer(verifyServerSSL);
    
    if (httpConnection->open(requestUrl, HttpConnection::MethodGet, false)!= 0) {
        LOG.error("%s: error opening connection", __FUNCTION__);
        *err = true;
        *requestCode = -1;
        delete httpConnection;
   
        return "";
    } else {
        int requestStatus = HTTP_OK;
        
        if ((requestStatus = httpConnection->request(NULL, response, false)) != HTTP_OK) {
            LOG.error("%s: error sending Wassup access token request", __FUNCTION__);
            *err = true;
            if ((requestStatus == HttpConnection::StatusNetworkError) || 
                (requestStatus == HttpConnection::StatusReadingError) ||
                (requestStatus == HttpConnection::StatusTimeoutError) ||
                (requestStatus == HttpConnection::StatusWritingError)) {
                *requestCode = -1;
            } else {
                *requestCode = requestStatus;
            }
            
            httpConnection->close();
            delete httpConnection;
   
            return "";
        } else {
            xmlResponse.assign(response.getString().c_str());
            //LOG.debug("Wassup access token request response received: %s", xmlResponse.c_str());
        }
    }
    
    httpConnection->close();
    delete httpConnection;
    
    //parse response to extract token
    unsigned int startPos = 0;
    unsigned int endPos   = 0;
    bool found = false;
    while(!found & !*err)
    {
        if(XMLProcessor::getElementAttributes(xmlResponse.c_str(), "ident", &startPos, &endPos)==NULL)
        {
            LOG.error("%s: error parsing XML response", __FUNCTION__);
            *err = true;
        }
        else
        {
            std::string attributeName = xmlResponse.substr(startPos+6, 6);
            int tokenStartIndex = startPos + 21;
            int tokenEndIndex   = endPos - 3;
            int tokenLenght     = tokenEndIndex - tokenStartIndex + 1;
            
            if (attributeName=="cooses") {
                token = xmlResponse.substr(tokenStartIndex, tokenLenght);
                found = true;
            }
            else//try next tag
            {
                xmlResponse = xmlResponse.substr(endPos+1);
            }
        }
    }
        
    return token;
}