Ejemplo n.º 1
0
void DialogNode::setLabTitleContent(std::string text)
{
	Label *labContent = (Label*)this->getChildByTag((int)ChildTag::LAB_CONTENT);
	labContent->setString(text);
}
Ejemplo n.º 2
0
ProjectSettings::ProjectSettings(EditorData *p_data) {


	singleton=this;
	set_title("Project Settings (engine.cfg)");
	undo_redo=&p_data->get_undo_redo();
	data=p_data;


	TabContainer *tab_container = memnew( TabContainer );
	add_child(tab_container);
	set_child_rect(tab_container);

	//tab_container->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_BEGIN, 15 );
	//tab_container->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END, 15 );
	//tab_container->set_anchor_and_margin(MARGIN_TOP,ANCHOR_BEGIN, 15 );
	//tab_container->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END, 35 );

	Control *props_base = memnew( Control );
	tab_container->add_child(props_base);
	props_base->set_name("General");
	globals_editor = memnew( PropertyEditor );
	props_base->add_child(globals_editor);
	globals_editor->set_area_as_parent_rect();
	globals_editor->hide_top_label();
	globals_editor->set_anchor_and_margin(MARGIN_TOP,ANCHOR_BEGIN, 55 );
	globals_editor->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END, 35 );
	globals_editor->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_BEGIN, 5 );
	globals_editor->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END, 5 );
	globals_editor->set_capitalize_paths(false);
	globals_editor->get_tree()->connect("cell_selected",this,"_item_selected");
	globals_editor->connect("property_toggled",this,"_item_checked");
	globals_editor->connect("property_edited",this,"_settings_prop_edited");


	Label *l = memnew( Label );
	props_base->add_child(l);
	l->set_pos(Point2(6,5));
	l->set_text("Category:");


	l = memnew( Label );
	l->set_anchor(MARGIN_LEFT,ANCHOR_RATIO);
	props_base->add_child(l);
	l->set_begin(Point2(0.21,5));
	l->set_text("Property:");

	l = memnew( Label );
	l->set_anchor(MARGIN_LEFT,ANCHOR_RATIO);
	props_base->add_child(l);
	l->set_begin(Point2(0.51,5));
	l->set_text("Type:");

	category = memnew( LineEdit );
	props_base->add_child(category);
	category->set_anchor(MARGIN_RIGHT,ANCHOR_RATIO);
	category->set_begin( Point2(5,25) );
	category->set_end( Point2(0.20,26) );
	category->connect("text_entered",this,"_item_adds");

	property = memnew( LineEdit );
	props_base->add_child(property);
	property->set_anchor(MARGIN_LEFT,ANCHOR_RATIO);
	property->set_anchor(MARGIN_RIGHT,ANCHOR_RATIO);
	property->set_begin( Point2(0.21,25) );
	property->set_end( Point2(0.50,26) );
	property->connect("text_entered",this,"_item_adds");


	type = memnew( OptionButton );
	props_base->add_child(type);
	type->set_anchor(MARGIN_LEFT,ANCHOR_RATIO);
	type->set_anchor(MARGIN_RIGHT,ANCHOR_RATIO);
	type->set_begin( Point2(0.51,25) );
	type->set_end( Point2(0.70,26) );
	type->add_item("bool");
	type->add_item("int");
	type->add_item("float");
	type->add_item("string");

	Button *add = memnew( Button );
	props_base->add_child(add);
	add->set_anchor(MARGIN_LEFT,ANCHOR_RATIO);
	add->set_anchor(MARGIN_RIGHT,ANCHOR_RATIO);
	add->set_begin( Point2(0.71,25) );
	add->set_end( Point2(0.85,26) );
	add->set_text("Add");
	add->connect("pressed",this,"_item_add");

	Button *del = memnew( Button );
	props_base->add_child(del);
	del->set_anchor(MARGIN_LEFT,ANCHOR_RATIO);
	del->set_anchor(MARGIN_RIGHT,ANCHOR_END);
	del->set_begin( Point2(0.86,25) );
	del->set_end( Point2(5,26) );
	del->set_text("Del");
	del->connect("pressed",this,"_item_del");

	Button *save = memnew( Button );
	props_base->add_child(save);
	save->set_anchor(MARGIN_LEFT,ANCHOR_END);
	save->set_anchor(MARGIN_RIGHT,ANCHOR_END);
	save->set_anchor(MARGIN_TOP,ANCHOR_END);
	save->set_anchor(MARGIN_BOTTOM,ANCHOR_END);
	save->set_begin( Point2(80,28) );
	save->set_end( Point2(10,20) );
	save->set_text("Save");
	save->connect("pressed",this,"_save");

	popup_platform = memnew( MenuButton );
	popup_platform->set_text("Copy To Platform..");
	popup_platform->set_disabled(true);
	props_base->add_child(popup_platform);

	popup_platform->set_anchor(MARGIN_LEFT,ANCHOR_BEGIN);
	popup_platform->set_anchor(MARGIN_RIGHT,ANCHOR_BEGIN);
	popup_platform->set_anchor(MARGIN_TOP,ANCHOR_END);
	popup_platform->set_anchor(MARGIN_BOTTOM,ANCHOR_END);
	popup_platform->set_begin( Point2(10,28) );
	popup_platform->set_end( Point2(150,20) );

	List<StringName> ep;
	EditorImportExport::get_singleton()->get_export_platforms(&ep);
	ep.sort_custom<StringName::AlphCompare>();

	for(List<StringName>::Element *E=ep.front();E;E=E->next()) {

		popup_platform->get_popup()->add_item( E->get() );

	}

	popup_platform->get_popup()->connect("item_pressed",this,"_copy_to_platform");
	get_ok()->set_text("Close");
	set_hide_on_ok(true);

	message = memnew( ConfirmationDialog );
	add_child(message);
//	message->get_cancel()->hide();
	message->set_hide_on_ok(true);

	Control *input_base = memnew( Control );
	input_base->set_name("Input Map");
	input_base->set_area_as_parent_rect();;
	tab_container->add_child(input_base);

	l = memnew( Label );
	input_base->add_child(l);
	l->set_pos(Point2(6,5));
	l->set_text("Action:");

	action_name = memnew( LineEdit );
	action_name->set_anchor(MARGIN_RIGHT,ANCHOR_RATIO);
	action_name->set_begin( Point2(5,25) );
	action_name->set_end( Point2(0.85,26) );
	input_base->add_child(action_name);
	action_name->connect("text_entered",this,"_action_adds");

	add = memnew( Button );
	input_base->add_child(add);
	add->set_anchor(MARGIN_LEFT,ANCHOR_RATIO);
	add->set_begin( Point2(0.86,25) );
	add->set_anchor(MARGIN_RIGHT,ANCHOR_END);
	add->set_end( Point2(5,26) );
	add->set_text("Add");
	add->connect("pressed",this,"_action_add");

	input_editor = memnew( Tree );
	input_base->add_child(input_editor);
	input_editor->set_area_as_parent_rect();
	input_editor->set_anchor_and_margin(MARGIN_TOP,ANCHOR_BEGIN, 55 );
	input_editor->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END, 35 );
	input_editor->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_BEGIN, 5 );
	input_editor->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END, 5 );
	input_editor->connect("item_edited",this,"_action_persist_toggle");
	input_editor->connect("button_pressed",this,"_action_button_pressed");
	popup_add = memnew( PopupMenu );
	add_child(popup_add);
	popup_add->connect("item_pressed",this,"_add_item");

	press_a_key = memnew( ConfirmationDialog );
	press_a_key->set_focus_mode(FOCUS_ALL);
	add_child(press_a_key);



	l = memnew( Label );
	l->set_text("Press a Key..");
	l->set_area_as_parent_rect();
	l->set_align(Label::ALIGN_CENTER);
	l->set_margin(MARGIN_TOP,20);
	l->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_BEGIN,30);
	press_a_key_label=l;
	press_a_key->add_child(l);
	press_a_key->connect("input_event",this,"_wait_for_key");
	press_a_key->connect("confirmed",this,"_press_a_key_confirm");


	device_input=memnew( ConfirmationDialog );
	add_child(device_input);
	device_input->get_ok()->set_text("Add");
	device_input->connect("confirmed",this,"_device_input_add");

	l = memnew( Label );
	l->set_text("Device:");
	l->set_pos(Point2(15,10));
	device_input->add_child(l);

	l = memnew( Label );
	l->set_text("Index:");
	l->set_pos(Point2(90,10));
	device_input->add_child(l);
	device_index_label=l;

	device_id = memnew( SpinBox );
	device_id->set_pos(Point2(20,30));
	device_id->set_size(Size2(70,10));
	device_id->set_val(0);

	device_input->add_child(device_id);

	device_index = memnew( OptionButton );
	device_index->set_pos(Point2(95,30));
	device_index->set_size(Size2(300,10));
	device_index->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,10);

	device_input->add_child(device_index);

	save = memnew( Button );
	input_base->add_child(save);
	save->set_anchor(MARGIN_LEFT,ANCHOR_END);
	save->set_anchor(MARGIN_RIGHT,ANCHOR_END);
	save->set_anchor(MARGIN_TOP,ANCHOR_END);
	save->set_anchor(MARGIN_BOTTOM,ANCHOR_END);
	save->set_begin( Point2(80,28) );
	save->set_end( Point2(10,20) );
	save->set_text("Save");
	save->connect("pressed",this,"_save");

	setting=false;

	//translations
	TabContainer *translations = memnew( TabContainer );
	translations->set_name("Localization");
	tab_container->add_child(translations);

	{

		VBoxContainer *tvb = memnew( VBoxContainer );
		translations->add_child(tvb);
		tvb->set_name("Translations");
		HBoxContainer *thb = memnew( HBoxContainer);
		tvb->add_child(thb);
		thb->add_child( memnew( Label("Translations:")));
		thb->add_spacer();
		Button *addtr = memnew( Button("Add..") );
		addtr->connect("pressed",this,"_translation_file_open");
		thb->add_child(addtr);
		MarginContainer *tmc = memnew( MarginContainer );
		tvb->add_child(tmc);
		tmc->set_v_size_flags(SIZE_EXPAND_FILL);
		translation_list = memnew( Tree );
		translation_list->set_v_size_flags(SIZE_EXPAND_FILL);
		tmc->add_child(translation_list);

		translation_file_open=memnew( FileDialog );
		add_child(translation_file_open);
		translation_file_open->set_mode(FileDialog::MODE_OPEN_FILE);
		translation_file_open->connect("file_selected",this,"_translation_add");

	}

	{
		VBoxContainer *tvb = memnew( VBoxContainer );
		translations->add_child(tvb);
		tvb->set_name("Remaps");
		HBoxContainer *thb = memnew( HBoxContainer);
		tvb->add_child(thb);
		thb->add_child( memnew( Label("Resources:")));
		thb->add_spacer();
		Button *addtr = memnew( Button("Add..") );
		addtr->connect("pressed",this,"_translation_res_file_open");
		thb->add_child(addtr);
		MarginContainer *tmc = memnew( MarginContainer );
		tvb->add_child(tmc);
		tmc->set_v_size_flags(SIZE_EXPAND_FILL);
		translation_remap = memnew( Tree );
		translation_remap->set_v_size_flags(SIZE_EXPAND_FILL);
		translation_remap->connect("cell_selected",this,"_translation_res_select");
		tmc->add_child(translation_remap);
		translation_remap->connect("button_pressed",this,"_translation_res_delete");

		translation_res_file_open=memnew( FileDialog );
		add_child(translation_res_file_open);
		translation_res_file_open->set_mode(FileDialog::MODE_OPEN_FILE);
		translation_res_file_open->connect("file_selected",this,"_translation_res_add");

		thb = memnew( HBoxContainer);
		tvb->add_child(thb);
		thb->add_child( memnew( Label("Remaps by Locale:")));
		thb->add_spacer();
		addtr = memnew( Button("Add..") );
		addtr->connect("pressed",this,"_translation_res_option_file_open");
		translation_res_option_add_button=addtr;
		thb->add_child(addtr);
		tmc = memnew( MarginContainer );
		tvb->add_child(tmc);
		tmc->set_v_size_flags(SIZE_EXPAND_FILL);
		translation_remap_options = memnew( Tree );
		translation_remap_options->set_v_size_flags(SIZE_EXPAND_FILL);
		tmc->add_child(translation_remap_options);

		translation_remap_options->set_columns(2);
		translation_remap_options->set_column_title(0,"Path");
		translation_remap_options->set_column_title(1,"Locale");
		translation_remap_options->set_column_titles_visible(true);
		translation_remap_options->set_column_expand(0,true);
		translation_remap_options->set_column_expand(1,false);
		translation_remap_options->set_column_min_width(1,200);
		translation_remap_options->connect("item_edited",this,"_translation_res_option_changed");
		translation_remap_options->connect("button_pressed",this,"_translation_res_option_delete");

		translation_res_option_file_open=memnew( FileDialog );
		add_child(translation_res_option_file_open);
		translation_res_option_file_open->set_mode(FileDialog::MODE_OPEN_FILE);
		translation_res_option_file_open->connect("file_selected",this,"_translation_res_option_add");

	}


	{
		VBoxContainer *avb = memnew( VBoxContainer );
		tab_container->add_child(avb);
		avb->set_name("AutoLoad");
		HBoxContainer *ahb = memnew( HBoxContainer);
		avb->add_child(ahb);

		VBoxContainer *avb_name = memnew( VBoxContainer );
		avb_name->set_h_size_flags(SIZE_EXPAND_FILL);
		autoload_add_name = memnew(LineEdit);
		avb_name->add_margin_child("Node Name:",autoload_add_name);
		ahb->add_child(avb_name);

		VBoxContainer *avb_path = memnew( VBoxContainer );
		avb_path->set_h_size_flags(SIZE_EXPAND_FILL);
		HBoxContainer *ahb_path = memnew( HBoxContainer );
		autoload_add_path = memnew(LineEdit);
		autoload_add_path->set_h_size_flags(SIZE_EXPAND_FILL);
		ahb_path->add_child(autoload_add_path);
		Button *browseaa = memnew( Button("..") );
		ahb_path->add_child(browseaa);
		browseaa->connect("pressed",this,"_autoload_file_open");
		Button *addaa = memnew( Button("Add") );
		ahb_path->add_child(addaa);
		addaa->connect("pressed",this,"_autoload_add");

		avb_path->add_margin_child("Path:",ahb_path);
		ahb->add_child(avb_path);

		autoload_list = memnew( Tree );
		autoload_list->set_v_size_flags(SIZE_EXPAND_FILL);
		avb->add_margin_child("List:",autoload_list,true);

		autoload_file_open=memnew( FileDialog );
		add_child(autoload_file_open);
		autoload_file_open->set_mode(FileDialog::MODE_OPEN_FILE);
		autoload_file_open->connect("file_selected",this,"_autoload_file_callback");

		autoload_list->set_columns(2);
		autoload_list->set_column_titles_visible(true);
		autoload_list->set_column_title(0,"name");
		autoload_list->set_column_title(1,"path");
		autoload_list->connect("button_pressed",this,"_autoload_delete");

	}

	timer = memnew( Timer );
	timer->set_wait_time(1.5);
	timer->connect("timeout",Globals::get_singleton(),"save");
	timer->set_one_shot(true);
	add_child(timer);

	updating_translations=false;


	/*
	Control * es = memnew( Control );
	es->set_name("Export");
	tab_container->add_child(es);
	export_settings = memnew( ProjectExportSettings );
	es->add_child(export_settings);
	export_settings->set_area_as_parent_rect();
	export_settings->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_END, 35 );
*/
}
void Prog::draw_sample()
{
   const int i = source_list.get_cur_value();
   const int j = dest_list.get_cur_value();
   ALLEGRO_BITMAP *bitmap1;
   ALLEGRO_BITMAP *bitmap2;
   bool use_memory = use_memory_button.get_pushed();
   bool enable_timing = enable_timing_button.get_pushed();
   
   if (use_memory)
      al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);
   else
      al_set_new_bitmap_flags(ALLEGRO_VIDEO_BITMAP);

   al_set_new_bitmap_format(formats[i].format);

   bitmap1 = al_load_bitmap("data/allegro.pcx");
   if (!bitmap1) {
      printf("Could not load image, bitmap format = %d\n", formats[i].format);
   }

   al_set_new_bitmap_format(formats[j].format);

   bitmap2 = al_create_bitmap(320, 200);
   if (!bitmap2) {
      printf("Could not create bitmap, format = %d\n", formats[j].format);
   }

   al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_ZERO);

   if (bitmap1 && bitmap2) {
      ALLEGRO_BITMAP *target = al_get_target_bitmap();

      al_set_target_bitmap(bitmap2);
      if (enable_timing) {
         double t0, t1;
         char str[256];
         int frames = 0;

         t0 = al_get_time();
         printf("Timing...\n");
         do {
           al_draw_bitmap(bitmap1, 0, 0, 0);
           frames++;
           t1 = al_get_time();
         } while (t1 - t0 < 0.25);
         printf("    ...done.\n");
         sprintf(str, "%.0f FPS", (double)frames / (t1 - t0));
         time_label.set_text(str);
      }
      else {
         al_draw_bitmap(bitmap1, 0, 0, 0);
         time_label.set_text("");
      }

      al_set_target_bitmap(target);
      al_draw_bitmap(bitmap2, 0, 0, 0);
   }
   else {
      al_draw_line(0, 0, 320, 200, al_map_rgb_f(1, 0, 0), 0);
      al_draw_line(0, 200, 320, 0, al_map_rgb_f(1, 0, 0), 0);
   }

   std::string s = get_format_name(bitmap1);
   s += " -> ";
   s += get_format_name(bitmap2);
   true_formats.set_text(s);

   al_destroy_bitmap(bitmap1);
   al_destroy_bitmap(bitmap2);
}
Ejemplo n.º 4
0
Archivo: Sym.cpp Proyecto: drenfro87/TD
//-----------------------------------------------------------------------------
//class SubprogramSymbol
//-----------------------------------------------------------------------------
SubprogramSymbol::SubprogramSymbol(symkind sk,string id,Typ* t)
    :Sym(sk,id,t){elabel=L.New();splabel=L.New();eplabel=L.New();}
Ejemplo n.º 5
0
int main(){

//	{
//		const std::string mAlign = "xxx,<><,--x";
//		const int mRepeatRow = 1;
//
//		int row = 0;
//		int ibeg=0, iend=0;
//		for(int i=0; i<mAlign.size(); ++i){
//			if(mAlign[i] == ','){
//				++row;
//				
//			}
//		}
//	}

	#define SET4(x, a,b,c,d) x[0]=a; x[1]=b; x[2]=c; x[3]=d
	#define EQ4(x, a,b,c,d) (x[0]==a && x[1]==b && x[2]==c && x[3]==d)

	// Multidimensional data array
	{
	
		// basics
		{
			const int s1=5, s2=4, s3=3, s4=2;
			Data d(Data::INT, s1,s2,s3,s4);

			assert(d.hasData());
			assert(d.type() == Data::INT);
			assert(d.sizeType() == sizeof(int));
			assert(d.isNumerical());
			assert(d.offset() == 0);
			assert(d.order() == 4);
			assert(d.stride() == 1);

			assert(d.size(0) == s1);
			assert(d.size(1) == s2);
			assert(d.size(2) == s3);
			assert(d.size(3) == s4);
			assert(d.size(0,1) == s1*s2);
			assert(d.size(0,1,2) == s1*s2*s3);
			assert(d.size(0,1,2,3) == d.size());
		
			assert(d.indexFlat(0,0,0,0) ==          0);
			assert(d.indexFlat(1,0,0,0) ==          1);
			assert(d.indexFlat(0,1,0,0) ==       s1*1);
			assert(d.indexFlat(0,2,0,0) ==       s1*2);
			assert(d.indexFlat(0,0,1,0) ==    s2*s1*1);
			assert(d.indexFlat(0,0,2,0) ==    s2*s1*2);
			assert(d.indexFlat(0,0,0,1) == s3*s2*s1*1);
			assert(d.indexFlat(0,0,0,2) == s3*s2*s1*2);
			
			for(int i=0; i<d.size(); ++i){
				int i1,i2,i3,i4;
				d.indexDim(i1,i2,i3,i4, i);
				assert(d.inBounds(i1,i2,i3,i4));
				assert(d.indexFlat(i1,i2,i3,i4) == i);
			}
			
			for(int i=0; i<d.size(); ++i) d.assign(i, i);
			for(int i=0; i<d.size(); ++i) assert(d.elem<int>(i) == i);
			
			// resizing
			{
				Data e(Data::INT, 8);
				int N; // resize change, in bytes

				for(int i=0; i<e.size(); ++i) e.assign(i,i);
				
				N=e.resize(16);			assert(e.sizeType()*8==N);
				
				// old elements should be copied over; extras should be zero
				for(int i=0; i<8 ; ++i) assert(e.at<int>(i) == i);
				for(int i=8; i<16; ++i) assert(e.at<int>(i) == 0);

				N=e.resize(0);			assert(e.sizeType()*-16==N);
				N=e.resize(8);			assert(e.sizeType()*  8==N);
				for(int i=0; i<e.size(); ++i) assert(e.at<int>(i) == 0);
			}
			
			// cloning data
			{
				Data e = d;
				assert(e == d);
				
				e.clone();
				assert(d.elems<int>() != e.elems<int>());
				assert(e == d);
			}
			
			// reversed slice
			{				
				Data e = d.reversed();
				for(int i=0; i<e.size(); ++i)
					assert(d.elem<int>(d.size()-1-i) == e.elem<int>(i));

				e.clone();
				for(int i=0; i<e.size(); ++i)
					assert(d.elem<int>(d.size()-1-i) == e.elem<int>(i));
				
				e += d;
				for(int i=0; i<e.size(); ++i)
					assert(e.elem<int>(i) == e.size()-1);
			}
		}


		// reference counting
		{
			Data d1(Data::INT, 4,4);
			assert(Data::references(d1.elems<int>()) == 1);

			{
				Data d2 = d1;
				assert(d1.elems<int>() == d2.elems<int>());
				assert(Data::references(d1.elems<int>()) == 2);
			}
			assert(Data::references(d1.elems<int>()) == 1);

			{
				Data d2 = d1.slice(1);
				Data d3 = d2.slice(1);
				assert(Data::references(d1.elems<int>()) == 3);
			}
			assert(Data::references(d1.elems<int>()) == 1);
		}
		
	
		const float cf = 10;
		float f = 10;
		std::string s = "hello";
		
		Data d(cf);

		assert(d.hasData());
		assert(d.size() == 1);
		assert(d.type() == Data::FLOAT);
		assert(d.at<float>(0) == cf);
		assert(d.toString() == "10");
		assert(d.at<std::string>(0) == "10");
		
//		d.put(std::string("8"));
//		assert(d.at<float>(0) == 8);

		// Getting/setting values
		d.assign(11.f);
		assert(d.at<float>(0) == 11.f);
		
		d.clone();
		assert(d.hasData());
		assert(d.size() == 1);
		assert(d.type() == Data::FLOAT);

		d.assign(11.f);
		assert(d.at<float>(0) == 11.f);

		d.assign(100);
		assert(d.at<float>(0) == 100);
		
		d.set(f);
		assert(d.elems<float>() == &f);
		assert(d.at<float>(0) == f);
		
		d.set(s);
		assert(d.type() == Data::STRING);
		assert(d.size() == 1);
		assert(d.elems<std::string>() == &s);
		assert(d.at<std::string>(0) == s);
		
		d.clone();
		assert(d.elems<std::string>() != &s);
		assert(d.at<std::string>(0) == s);

		d.set("hello");
		assert(d.type() == Data::STRING);
		assert(d.at<std::string>(0) == "hello");

		{
			std::string s = "d2";
			Data d2(s);
			
			d.set("d");
			d2.assign(d);
			assert(d2.at<std::string>(0) == d.at<std::string>(0));
		}
		
		{
			Data a(Data::FLOAT, 3);
			a.assign(10,0);
			a.assign(20,1);
			a.assign(30,2);
			float b[3];
			a.copyTo(b);
			for(int i=0;i<3;++i) assert(b[i] == a.at<float>(i));
		}
		
		// checking elements
		{
			Data::Type types[] = {Data::BOOL, Data::INT, Data::FLOAT, Data::DOUBLE};
			for(int i=0;i<4;++i){
				Data a(types[i], 8);
				a.assignAll(0);
				assert(a.isZero());
				a.assign(1, 1);
				assert(!a.isZero());
				a.assign(1, 3);
				a.assign(1, 5);
				a.assign(1, 7);
				assert(a.slice(0,4,2).isZero());
			}
		}
		
		// searching
		{
			Data e(Data::STRING, 3);
			std::string s1 = "test1", s2 = "test2", s3 = "test3";
			e.assign(s1, 0);
			e.assign(s2, 1);
			e.assign(s3, 2);
			
			assert(e.indexOf(s1) == 0);
			assert(e.indexOf(s2) == 1);
			assert(e.indexOf(s3) == 2);
			assert(e.indexOf(std::string("invalid")) == Data::npos);
		}
		
		// multiple element assignment
		{
			#define ASSERT_EQUALS(a,b,c,d,e)\
				assert(d1.at<int>(0) == a);\
				assert(d1.at<int>(1) == b);\
				assert(d1.at<int>(2) == c);\
				assert(d1.at<int>(3) == d);\
				assert(d1.at<int>(4) == e)

			Data d1(Data::INT, 5);
			d1.assignAll(-1);
			ASSERT_EQUALS(-1,-1,-1,-1,-1);
			
			d1.assignAll(0);
			ASSERT_EQUALS(0,0,0,0,0);
			
			{
				float t[] = {1,2,3,4,5};
				d1.assignFromArray(t,2);
				ASSERT_EQUALS(1,2,0,0,0);
				
				d1.assignFromArray(t+2,2,1,2);
				ASSERT_EQUALS(1,2,3,4,0);
				
				d1.assignAll(0);
				d1.assignFromArray(t,3, 2);
				ASSERT_EQUALS(1,3,5,0,0);
				
				d1.assignFromArray(t+1,2, 2,3);
				ASSERT_EQUALS(1,3,5,2,4);
			}
			#undef ASSERT_EQUALS
		}
	}


	// stringification
	{	//for(int i=0;i<4;++i) printf("%g\n", f4[i]);
		//printf("%s\n", s1.c_str());
		bool b1;
		float f1;
		double d1;
		std::string s1;
		
		bool b4[4];
		float f4[4];
		double d4[4];
		std::string s4[4];
		
		int N;	// number of elements converted

		N=fromToken(f1, "1e-2");		assert(1==N && f1 == float(1e-2));
		N=fromToken(f1, "1000");		assert(1==N && f1 == float(1000));
		N=fromToken(d1, "1e-2");		assert(1==N && d1 == double(1e-2));
		N=fromToken(d1, "1000");		assert(1==N && d1 == double(1000));
		N=fromToken(b1, "0");			assert(1==N && b1 == 0);
		N=fromToken(b1, "1");			assert(1==N && b1 == 1);
		N=fromToken(s1, "\"test\"");	assert(1==N && s1 == "test");
		
		N=fromToken(b4,4,1, "{1,0,1,1}");				assert(4==N && EQ4(b4, 1,0,1,1));
		N=fromToken(b4,4,1, "{0,  1, 0,0}");			assert(4==N && EQ4(b4, 0,1,0,0));
		N=fromToken(f4,4,1, "{1, -1.2, 1e10, +.1}");	assert(4==N && EQ4(f4, 1.f,-1.2f,1e10f,+.1f));
		N=fromToken(d4,4,1, "{1, -1.2, 1e10, +.1}");	assert(4==N && EQ4(d4, 1,-1.2,1e10,+.1));
		N=fromToken(s4,4,1, "{\"one\", \"two\", \"three\", \"four\"}");
														assert(4==N && EQ4(s4, "one","two","three","four"));

		N=toToken(s1, 1000.f);			assert(1==N && s1 == "1000");
		N=toToken(s1, 2000.0);			assert(1==N && s1 == "2000");
		N=toToken(s1, true);			assert(1==N && s1 == "1");
		N=toToken(s1, false);			assert(1==N && s1 == "0");
		N=toToken(s1, "test");			assert(1==N && s1 == "\"test\"");
		N=toToken(s1, std::string("test"));
										assert(1==N && s1 == "\"test\"");		

		SET4(b4, 1,0,1,1);		N=toToken(s1, b4,4,1);	assert(4==N && s1 == "{1, 0, 1, 1}");
		SET4(f4,-1,0.1,3,1e10);	N=toToken(s1, f4,4,1);	assert(4==N && s1 == "{-1, 0.1, 3, 1e+10}");
		SET4(d4,-1,0.1,3,1e10);	N=toToken(s1, d4,4,1);	assert(4==N && s1 == "{-1, 0.1, 3, 1e+10}");
		SET4(s4,"one","two","three","four"); N=toToken(s1,s4,4,1);
														assert(4==N && s1 == "{\"one\", \"two\", \"three\", \"four\"}");
	}


	// test View linked list implementation
	{
		View n00, n10, n11, n20;

		n00.add(n10);
		n00.add(n11);
		n10.add(n20);
		
		// check all of our links
		assert( n00.child == &n10);
		assert(!n00.parent);
		assert(!n00.sibling);
		assert( n10.parent == &n00);
		assert( n10.sibling == &n11);
		assert( n10.child == &n20);
		assert( n11.parent == &n00);
		assert(!n11.child);
		assert(!n11.sibling);
		assert( n20.parent == &n10);
		assert(!n20.child);
		assert(!n20.sibling);
		
		n10.makeLastSibling();
		assert(!n10.sibling);
		assert(n11.sibling == &n10);
		n11.makeLastSibling();

		n10.remove();
		assert(!n10.parent);
		assert(!n10.sibling);
		assert(!n00.child->sibling);
		
		n11.remove();
		assert(!n00.child);

		assert(n10.child == &n20);
	}

	
	// test View memory management
	{
		View * v0d = new View;
		View v1s;
		View * v1d = new View;
		
		assert(v0d->dynamicAlloc());
		assert(!v1s.dynamicAlloc());

		*v0d << v1s << v1d;
		
		delete v0d;
	}



	// Notifications	
	{
		bool bv1=false, bv2=false, bf=false;
		Notifier n;
	
		assert(n.numObservers(Update::Value) == 0);

		n.attach(ntSetBool1, Update::Value, &bv1);
		n.attach(ntSetBool2, Update::Value, &bv2);
		n.attach(ntSetBool1, Update::Focus, &bf);

		assert(n.numObservers(Update::Value) == 2);
		assert(n.numObservers(Update::Focus) == 1);

		n.notify(Update::Value);
		assert(bv1);
		assert(bv2);
		assert(!bf);

		n.notify(Update::Focus);
		assert(bf);
		
		bv1=bv2=false;
		n.detach(ntSetBool1, Update::Value, &bv1);
		n.notify(Update::Value);
		assert(!bv1);
		assert(bv2);

		bv1=bv2=false;
		n.detach(ntSetBool2, Update::Value, &bv2);
		n.notify(Update::Value);
		assert(!bv1);
		assert(!bv2);
	}
	
	{
		bool b=false;
		Button w;
		w.attach(ntValue, Update::Value, &b);
		w.setValue(true);
		assert(b);
		assert(w.getValue() == true);

// Setting to current value should NOT send notification to avoid infinite loops
		b=false;
		w.setValue(w.getValue());
		assert(!b);

// Boolean model variable
		bool v = false;
		w.attachVariable(v);
		w.setValue(true);		assert(v == true);
		w.setValue(false);		assert(v == false);
		
		v = true;
		w.onDataModelSync();		assert(w.getValue() == true);

		w.setValue(true);

		assert(w.data().toToken() == "1");
		w.setValue(false);
		assert(w.data().toToken() == "0");
		w.setDataFromString("0");	assert(w.getValue() == false);
		w.setDataFromString("1");	assert(w.getValue() == true);

		assert(!w.setDataFromString("invalid"));
	}

	{
		Buttons w;
		bool b=false;
		w.attach(ntValue, Update::Value, &b);
		w.setValue(true, 0);
		assert(b);
		assert(w.getValue(0) == true);
		
		w.data().resize(2,2);
		w.data().assignAll(0);

		bool v1 = false;
		bool v2 = false;
		w.attachVariable(v1, 0);
		w.attachVariable(v2, 2);

		w.setValue(true, 0);		assert(v1 == true);
		w.setValue(true, 2);		assert(v2 == true);
		w.setValue(false, 0);		assert(v1 == false);
		w.setValue(false, 2);		assert(v2 == false);

		w.setValue(false, 0);
		w.setValue(false, 1);
		w.setValue(false, 2);
		w.setValue(false, 3);
		assert(w.data().toToken() == "{0, 0, 0, 0}");
		
		v1 = v2 = false;
		w.setDataFromString("{1,1,1,1}");
		assert(w.getValue(0) && w.getValue(1) && w.getValue(2) && w.getValue(3));
		assert(v1 && v2);
	}

	{
		bool b=false;
		Slider w;
		w.attach(ntValue, Update::Value, &b);
		w.setValue(0.99f);
		assert(b);
		assert(w.getValue() == 0.99f);

// Setting to current value should NOT send notification to avoid infinite loops
		b=false;
		w.setValue(w.getValue());
		assert(!b);

		float v;
		w.attachVariable(v);
		w.setValue(0.99);
		assert(v == 0.99f);
		
		v = 0;
		w.onDataModelSync();
		assert(w.getValue() == 0);

		std::string s;
		w.setValue(0.25);
		assert(w.data().toToken() == "0.25");
		w.setDataFromString("0.5");	assert(w.getValue() == 0.5);
									assert(v == 0.5);

		assert(!w.setDataFromString("invalid"));
		assert(w.getValue() == 0.5);
	}

	{
		bool b=false;
		Sliders w(Rect(1), 2,2);
		w.attach(ntValue, Update::Value, &b);
		w.setValue(0.99f, 3);
		assert(b);
		assert(w.getValue(3) == 0.99f);

		float v1, v2;
		w.attachVariable(v1, 0);
		w.attachVariable(v2, 1);

		w.setValue(0.1f, 0); assert(v1 == 0.1f);
		w.setValue(0.2f, 0); assert(v1 == 0.2f);
		
		v1 = 0.8f; v2 = 0.9f;
		w.onDataModelSync();
		assert(w.getValue(0) == 0.8f);
		assert(w.getValue(1) == 0.9f);

		w.setValue(0.1f, 0);
		w.setValue(0.2f, 1);
		w.setValue(0.3f, 2);
		w.setValue(0.4f, 3);
		assert(w.data().toToken() == "{0.1, 0.2, 0.3, 0.4}");
		
		v1=v2=0;
		w.setDataFromString("{0.4,0.3,0.2,0.1}");
		assert(w.getValue(0) == 0.4);
		assert(w.getValue(1) == 0.3);
		assert(w.getValue(2) == 0.2);
		assert(w.getValue(3) == 0.1);
		assert(v1 == (float)w.getValue(0) && v2 == (float)w.getValue(1));
		
//		double vs[4] = {0.11, 0.22, 0.33, 0.44};
//		w.attachVariable(vs,4);
//		w.onDataModelSync();
//		for(int i=0; i<4; ++i) printf("%f\n", w.values()[i]);
//		
//		w.getValue(0.44, 0);
//		w.getValue(0.33, 0);
//		w.getValue(0.22, 0);
//		w.getValue(0.11, 0);
//		for(int i=0; i<4; ++i) printf("%f\n", vs[i]);
	}

	{
		bool b=false;
		Slider2D w;
		w.attach(ntSetBool1, Update::Value, &b);
		w.setValue(0.01f, 0);
		assert(b);
		assert(w.getValue(0) == 0.01f);

// Setting to current value should NOT send notification to avoid infinite loops
		b=false;
		w.setValue(0.01f, 0);
		assert(!b);
		
		b=false;
		w.setValue(0.00f, 0);
		w.setValue(0.01f, 1);
		assert(b);
		assert(w.getValue(1) == 0.01f);
		
		b=false;
		w.setValueMax();
		assert(b);
		assert(w.getValue(0) == 1.f);
		assert(w.getValue(1) == 1.f);
		
		float v1, v2;
		w.attachVariable(v1, 0);
		w.attachVariable(v2, 1);
		
		w.setValue(0.5f, 0);	assert(v1 == 0.5f);
		w.setValue(0.6f, 1);	assert(v2 == 0.6f);
		
		v1 = 0.1;
		v2 = 0.2;
		
		w.onDataModelSync();
		assert(w.getValue(0) == v1);
		assert(w.getValue(1) == v2);
	
		w.setValue(0.2, 0);
		w.setValue(0.3, 1);
		assert(w.data().toToken() == "{0.2, 0.3}");
		
		v1 = v2 = 0;
		w.setDataFromString("{0.7, 0.8}");
		assert(w.getValue(0)==0.7 && w.getValue(1)==0.8);
		assert(v1==(float)w.getValue(0) && v2==(float)w.getValue(1));
	}

	{
		bool b=false;
		SliderGrid<4> w;
		w.attach(ntValue, Update::Value, &b);
		w.setValue(0.01f, 0);
		assert(b);
		assert(w.getValue(0) == 0.01f);

		float v1, v2;
		w.attachVariable(v1, 0);
		w.attachVariable(v2, 1);

		w.setValue(0.1f, 0); assert(v1 == 0.1f);
		w.setValue(0.2f, 0); assert(v1 == 0.2f);
		
		v1 = 0.8f; v2 = 0.9f;
		w.onDataModelSync();
		assert(w.getValue(0) == 0.8f);
		assert(w.getValue(1) == 0.9f);

		w.setValue(0.1f, 0);
		w.setValue(0.2f, 1);
		w.setValue(0.3f, 2);
		w.setValue(0.4f, 3);
		assert(w.data().toToken() == "{0.1, 0.2, 0.3, 0.4}");
		
		v1=v2=0;
		w.setDataFromString("{0.4,0.3,0.2,0.1}");
		assert(w.getValue(0) == 0.4);
		assert(w.getValue(1) == 0.3);
		assert(w.getValue(2) == 0.2);
		assert(w.getValue(3) == 0.1);
		assert(v1 == (float)w.getValue(0) && v2 == (float)w.getValue(1));
	}
	
	{
		bool b=false;
		SliderRange w;
		w.attach(ntValue, Update::Value, &b);
		w.setValue(0.01f, 0);
		w.setValue(0.02f, 1);
		assert(b);
		assert(w.getValue(0) == 0.01f);
		assert(w.getValue(1) == 0.02f);
		assert(w.center() == 0.015f);
		assert(w.range() == 0.01f);
		
		w.endpoints(0,1);
		assert(w.getValue(0) == 0);
		assert(w.getValue(1) == 1);
		
		w.centerRange(0.5, 0.25);
		assert(w.getValue(0) == (0.5-0.25/2));
		assert(w.getValue(1) == (0.5+0.25/2));

		float v1,v2;
		w.attachVariable(v1, 0);
		w.attachVariable(v2, 1);

		w.setValue(0.2, 0);
		w.setValue(0.3, 1);
		assert(w.data().toToken() == "{0.2, 0.3}");
		
		v1 = v2 = 0;
		w.setDataFromString("{0.7, 0.8}");
		assert(w.getValue(0)==0.7 && w.getValue(1)==0.8);
		assert(v1==(float)w.getValue(0) && v2==(float)w.getValue(1));
	}

	{
		bool b=false;
		Label w;

		w.attach(ntValue, Update::Value, &b);
		w.setValue("test");
		assert(b);
		assert(w.getValue() == "test");
		
		assert(w.data().toToken() == "\"test\"");
		
		w.setValue("");
		w.setDataFromString("\"test\"");	assert(w.getValue() == "test");
	}

	{

//		{
//			double val = 1e14;
//			double inc = 1;
//			printf("%f\n", val + inc*1);
//			printf("%f\n", val + inc*2);
//			printf("%f\n", val + inc*3);
//			printf("%f\n", val + inc*4);
//		}

		bool b=false;
		NumberDialer w(1,2,1,0);
		w.attach(ntValue, Update::Value, &b);
		w.setValue(0.75);
		assert(b);
		assert(w.getValue() == 0.75);

// Setting to current value should NOT send notification to avoid infinite loops
		b=false;
		w.setValue(w.getValue());
		assert(!b);

		double v=0;
		w.attachVariable(v);
		w.setValue(0.5);	assert(v == 0.5);
		
		v = 0.25;
		w.onDataModelSync();
		assert(w.getValue() == v);

		w.setValue(0.2);
		assert(w.data().toToken() == "0.2");
		
		v = 0;
		w.setDataFromString("0.8");
		assert(w.getValue()==0.8 && w.getValue()==v);
	}

	{
		bool b=false;
		TextView w;
		w.attach(ntValue, Update::Value, &b);
		w.setValue("hello");
		assert(b);
		assert(w.getValue() == "hello");
		
		assert(w.data().toToken() == "\"hello\"");

		std::string v = "test";
		w.attachVariable(v);
		
		w.onDataModelSync();
		assert(w.getValue() == "test");

		w.setDataFromString("\"world\"");
		assert(w.getValue() == "world");
		assert(v == "world");
	}



	// model to string conversion
	{
		Label l;
		TextView tv;
		Button b;
		Buttons bs(Rect(), 2, 2);
		Slider s;
		Sliders ss(Rect(), 1, 4);
		Slider2D s2D;
		NumberDialer nd(1,4,1,-1);
		std::string strings[] = {"test1", "test2", "test3"};
	
		l.setValue("Hello Label!").name("l");
		tv.setValue("Hello TextView!").name("tv");
		b.setValue(true).name("b");
		bs.setValue(true, 0,1).name("bs");
		s.setValue(0.5).name("s");
		ss.setValue(0.4, 1).name("ss");
		s2D.setValue(0.5, 0).setValue(0.1, 1).name("s2D");
		nd.setValue(-0.54941).name("nd");

		const View * views[] = {&l, &tv, &b, &bs, &s, &ss, &s2D, &nd};
		for(unsigned i=0; i<sizeof(views)/sizeof(View *); ++i){
			//const Data& d = views[i]->data();
			//printf("%p: %s\n", &d, d.toString().c_str());
			//views[i]->model().print(); printf("\n");
		}

		View top;
		top << l << tv << b << bs << s << ss << s2D << nd;
	
		std::string str1, str2;
//		top.modelToString(str1, "test model");		
//		printf("%s\n", str1.c_str());
//
//		l.setValue("changed...");
//		top.modelFromString(str1);
//		top.modelToString(str2);
//		printf("%s\n", str2.c_str());
//		assert(str1 == str2);

		ModelManager mm;
		
		mm.add("l", l);
		mm.add("tv", tv);
		mm.add("b", b);
		mm.add("bs", bs);
		mm.add("s" , s);
		mm.add("ss", ss);
		mm.add("s2D",s2D);
		mm.add("nd", nd);
		
		Data dat(strings, 3);
		//Data dat(10);
		//dat.print();
		//mm.add("strings", dat);
		//mm.add("strings", *new Data(strings, 3));
		
//		mm.toToken(str1, "test");
//		printf("%s\n", str1.c_str());
//		
//		mm.fromToken(str1);
//		mm.toToken(str2, "test");
//		printf("%s\n", str2.c_str());

		std::string snapshotString1 =
"[\"test 1\"] = {\n\
	l = \"Label 1\",\n\
	tv = \"TextView 1\",\n\
	b = 0,\n\
	bs = {0,0,0,0},\n\
}";

		std::string snapshotString2 =
"[\"test 2\"] = {\n\
	l = \"Label 2\",\n\
	tv = \"TextView 2\",\n\
	b = 1,\n\
	bs = {1,1,1,1},\n\
	s = 1,\n\
	ss = {1,1,1,1},\n\
	s2D = {1,1},\n\
	nd = 1,\n\
}";
		
		mm.snapshotsFromString("{" + snapshotString1 + ",\r\n" + snapshotString2 + "}");

//		mm.snapshots()["test 1"]["l"].print();
//		mm.snapshots()["test 1"]["b"].print();
//		mm.snapshots()["test 1"]["bs"].print();
//		mm.snapshots()["test 1"]["s"].print();
//		mm.snapshots()["test 1"]["ss"].print();
//		mm.snapshots()["test 1"]["s2D"].print();
//		mm.snapshots()["test 1"]["nd"].print();
//		mm.snapshots()["test 2"]["l"].print();
//		mm.snapshots()["test 2"]["b"].print();
//		mm.snapshots()["test 2"]["bs"].print();
//		mm.snapshots()["test 2"]["s"].print();
//		mm.snapshots()["test 2"]["ss"].print();
//		mm.snapshots()["test 2"]["s2D"].print();
//		mm.snapshots()["test 2"]["nd"].print();
//
//		mm.snapshotsToFile("snapshots.txt");
//		
//		mm.clearSnapshots();
//		mm.snapshotsFromFile("snapshots.txt");
//
//		str1.clear();
//		mm.snapshotsToString(str1);
//		printf("%s\n", str1.c_str());
	}

//	{
//		std::string str( "a bc ab ca ab" );
//		std::string searchString("ab"); 
//		std::string replaceString("hello");
//
//		std::string::size_type pos = 0;
//		while((pos = str.find(searchString, pos)) != std::string::npos){
//			str.replace(pos++, searchString.size(), replaceString);
//		}
//		printf("%s\n", str.c_str());
//	}

//	printf("sizeof(Notifier): %d\n", sizeof(Notifier));
//	printf("sizeof(View): %d\n", sizeof(View));
//	printf("sizeof(Data): %d\n", sizeof(Data));
//	printf("sizeof(Model): %d\n", sizeof(Model));
//	printf("sizeof(ModelManager): %d\n", sizeof(ModelManager));

	return 0;
}
Ejemplo n.º 6
0
//-----------------------------------------------------------------------------
// Purpose: sets up the current control to edit
//-----------------------------------------------------------------------------
void BuildModeDialog::SetActiveControl(Panel *controlToEdit)
{	
	if (m_pCurrentPanel == controlToEdit)
	{
		// it's already set, so just update the property data and quit
		if (m_pCurrentPanel)
		{
			UpdateControlData(m_pCurrentPanel);
		}
		return;
	}

	// reset the data
	m_pCurrentPanel = controlToEdit;
	RemoveAllControls();
	m_pPanelList->m_pControls->MoveScrollBarToTop();

	if (!m_pCurrentPanel)
	{
		m_pStatusLabel->SetText("[nothing currently selected]");
		m_pStatusLabel->SetTextColorState(Label::CS_DULL);
		RemoveAllControls();
		return;
	}

	// get the control description string
	const char *controlDesc = m_pCurrentPanel->GetDescription();

	// parse out the control description
	int tabPosition = 1;
	while (1)
	{
		const char *dataType = ParseTokenFromString(&controlDesc);

		// finish when we have no more tokens
		if (*dataType == 0)
			break;

		// default the data type to a string
		int datat = TYPE_STRING;

		if (!stricmp(dataType, "int"))
		{
			datat = TYPE_STRING; //!! just for now
		}
		else if (!stricmp(dataType, "alignment"))
		{
			datat = TYPE_ALIGNMENT;
		}
		else if (!stricmp(dataType, "autoresize"))
		{
			datat = TYPE_AUTORESIZE;
		}
		else if (!stricmp(dataType, "corner"))
		{
			datat = TYPE_CORNER;
		}
		else if (!stricmp(dataType, "localize"))
		{
			datat = TYPE_LOCALIZEDSTRING;
		}

		// get the field name
		const char *fieldName = ParseTokenFromString(&controlDesc);

		int itemHeight = 18;

		// build a control & label
		Label *label = new Label(this, NULL, fieldName);
		label->SetSize(96, itemHeight);
		label->SetContentAlignment(Label::a_east);

		TextEntry *edit = NULL;
		ComboBox *editCombo = NULL;
		Button *editButton = NULL;
		if (datat == TYPE_ALIGNMENT)
		{
			// drop-down combo box
			editCombo = new ComboBox(this, NULL, 9, false);
			editCombo->AddItem("north-west", NULL);
			editCombo->AddItem("north", NULL);
			editCombo->AddItem("north-east", NULL);
			editCombo->AddItem("west", NULL);
			editCombo->AddItem("center", NULL);
			editCombo->AddItem("east", NULL);
			editCombo->AddItem("south-west", NULL);
			editCombo->AddItem("south", NULL);
			editCombo->AddItem("south-east", NULL);
		
			edit = editCombo;
		}
		else if (datat == TYPE_AUTORESIZE)
		{
			// drop-down combo box
			editCombo = new ComboBox(this, NULL, 4, false);
			editCombo->AddItem( "0 - no auto-resize", NULL);
			editCombo->AddItem( "1 - resize right", NULL);
			editCombo->AddItem( "2 - resize down", NULL);
			editCombo->AddItem( "3 - down & right", NULL);
		
			edit = editCombo;
		}
		else if (datat == TYPE_CORNER)
		{
			// drop-down combo box
			editCombo = new ComboBox(this, NULL, 4, false);
			editCombo->AddItem("0 - top-left", NULL);
			editCombo->AddItem("1 - top-right", NULL);
			editCombo->AddItem("2 - bottom-left", NULL);
			editCombo->AddItem("3 - bottom-right", NULL);
		
			edit = editCombo;
		}
		else if (datat == TYPE_LOCALIZEDSTRING)
		{
			editButton = new Button(this, NULL, "...");
			editButton->SetParent(this);
			editButton->AddActionSignalTarget(this);
			editButton->SetTabPosition(tabPosition++);
			editButton->SetTall( itemHeight );
			label->SetAssociatedControl(editButton);
		}
		else
		{
			// normal string edit
			edit = new CSmallTextEntry(this, NULL);
		}

		if (edit)
		{
			edit->SetTall( itemHeight );
			edit->SetParent(this);
			edit->AddActionSignalTarget(this);
			edit->SetTabPosition(tabPosition++);
			label->SetAssociatedControl(edit);
		}

		HFont smallFont = scheme()->GetIScheme( GetScheme() )->GetFont( "DefaultVerySmall" );

		if ( label )
		{
			label->SetFont( smallFont );
		}
		if ( edit )
		{
			edit->SetFont( smallFont );
		}
		if ( editCombo )
		{
			editCombo->SetFont( smallFont );
		}
		if ( editButton )
		{
			editButton->SetFont( smallFont );
		}

		// add to our control list
		m_pPanelList->AddItem(label, edit, editCombo, editButton, fieldName, datat);

		if ( edit )
		{
			m_pPanelList->m_pControls->AddItem(label, edit);
		}
		else
		{
			m_pPanelList->m_pControls->AddItem(label, editButton);
		}
	}

	// check and see if the current panel is a Label
	// iterate through the class hierarchy 
	if ( controlToEdit->IsBuildModeDeletable() )
	{
		m_pDeleteButton->SetEnabled(true);
	}
	else
	{
		m_pDeleteButton->SetEnabled(false);	
	}

	// update the property data in the dialog
	UpdateControlData(m_pCurrentPanel);
	
	// set our title
	if ( m_pBuildGroup->GetResourceName() )
	{
		m_pFileSelectionCombo->SetText(m_pBuildGroup->GetResourceName());
	}
	else
	{
		m_pFileSelectionCombo->SetText("[ no resource file associated with dialog ]");
	}

	m_pApplyButton->SetEnabled(false);
	InvalidateLayout();
	Repaint();
}
Ejemplo n.º 7
0
void SamplesGame::initialize()
{
	LOGI(">SamplesGame::initialize ()");
	LOGI(">SamplesGame::initialize FileSystem::getAssetPath() = '%s'", FileSystem::getAssetPath());
	LOGI(">SamplesGame::initialize FileSystem::getResourcePath() = '%s'", FileSystem::getResourcePath());

	Bundle* bundle = Bundle::create("res/ui/arial.gpb");
	LOGI(">SamplesGame::initialize bundle=%p", bundle);

	_font = bundle->loadFont(bundle->getObjectId(0));
	LOGI(">SamplesGame::initialize _font=%p", _font);

    _font = Font::create("res/ui/arial.gpb");
    LOGI(">SamplesGame::initialize _font=%p", _font);

    for (size_t i = 0; i < _categories->size(); ++i)
    {
        std::sort((*_samples)[i].begin(), (*_samples)[i].end());
    }

    // Load camera script
    getScriptController()->loadScript("res/common/camera.lua");

    // Create the selection form
    _sampleSelectForm = Form::create("sampleSelect", NULL, Layout::LAYOUT_VERTICAL);
    _sampleSelectForm->setWidth(220);
    _sampleSelectForm->setHeight(1, true);
    _sampleSelectForm->setScroll(Container::SCROLL_VERTICAL);
    const size_t size = _samples->size();
    LOGI(">SamplesGame::initialize _samples->size()=%d", size);

    for (size_t i = 0; i < size; ++i)
    {
		Label* categoryLabel = Label::create((*_categories)[i].c_str());
        categoryLabel->setFontSize(22);
        categoryLabel->setText((*_categories)[i].c_str());
        _sampleSelectForm->addControl(categoryLabel);
        categoryLabel->release();

        SampleRecordList list = (*_samples)[i];
        const size_t listSize = list.size();
        for (size_t j = 0; j < listSize; ++j)
        {
            SampleRecord sampleRecord = list[j];
			Button* sampleButton = Button::create(sampleRecord.title.c_str());
            sampleButton->setText(sampleRecord.title.c_str());
            sampleButton->setWidth(1, true);
            sampleButton->setHeight(50);
            sampleButton->addListener(this, Control::Listener::CLICK);
            _sampleSelectForm->addControl(sampleButton);
            sampleButton->release();
        }
    }
    _sampleSelectForm->setFocus();

    // Disable virtual gamepads.
    unsigned int gamepadCount = getGamepadCount();

    for (unsigned int i = 0; i < gamepadCount; i++)
    {
        Gamepad* gamepad = getGamepad(i, false);
        if (gamepad->isVirtual())
        {
            gamepad->getForm()->setEnabled(false);
        }
    }

    /*
    for (size_t i = 0; i < size; ++i)
    {
        SampleRecordList list = (*_samples)[i];
        const size_t listSize = list.size();
        for (size_t j = 0; j < listSize; ++j)
        {
            SampleRecord sampleRecord = list[j];
            // TODO if (sampleRecord.title.compare(control->getId()) == 0)
            {
                _sampleSelectForm->setEnabled(false);
                runSample(sampleRecord.funcPtr);
                LOGI("<SamplesGame::initialize _activeSample=%lx", (long )_activeSample);
                return;
            }
        }
    }
    */
    LOGI("<SamplesGame::initialize _activeSample=%lx", (long )_activeSample);
}
Ejemplo n.º 8
0
/**
 * If there is no list populates the List View Widget with the project data
 * from mProjects vector. Else destroys and deallocates previous list items
 * and creates new ones.
 */
void WorkspaceLayout::updateProjectList(MAUtil::Vector <reloadProject> * projects)
{
	// Remove The ListView and add An Activity Indicator
	lprintfln("Updating Project List");
	mListView->setVisible(false);

	/**
	 * FIXME Removing listView and adding Activity indicator causes
	 * the list view not getting events until some point,
	 * when removing activity indicator to add the list again.
	 */
	//this->removeChild(mListView);
	//this->addChild(mActivityIndicatorContainer);

	// If there was a project Selected before update remove the
	// control buttons
	if(mSelectedProject != -1)
	{
		Widget *h = mListView->getChild(mSelectedProject)->getChild(0);
		h->removeChild(h->getChild(1));
		h->removeChild(h->getChild(1));
	}

	// ReInitialize selected project
	mSelectedProject = -1;
	mSelectedProjectName = "";

	// Delete all the widgets from the ListView
	int prProjects = mListView->countChildWidgets();
	if(prProjects != 0)
	{
		for(int i = 0; i < prProjects; i++)
		{
			Widget *listItemWidget = mListView->getChild(0); // list Item Widget

			Widget *hLayout = listItemWidget->getChild(0); // horizontal layout widget
			for( int j = 0; j < hLayout->countChildWidgets(); j++)
			{
				Widget * w = hLayout->getChild(0);
				hLayout->removeChild(w);
				delete w;
			}

			listItemWidget->removeChild(hLayout);

			delete hLayout;

			mListView->removeChild(listItemWidget);
			delete listItemWidget;
		}
	}

	// Re-populate the ListView with projects
	for (MAUtil::Vector <reloadProject>::iterator i = projects->begin(); i != projects->end(); i++)
	{
		// New List Itemprojects
		ListViewItem* item = new ListViewItem();
		item->setHeight(mWidgetHeight);
		item->fillSpaceHorizontally();

		// New Horizontal Layout
		HorizontalLayout *itemHorizontalLayout = new HorizontalLayout();
		itemHorizontalLayout->fillSpaceHorizontally();
		itemHorizontalLayout->setHeight(mWidgetHeight);

		// New Label
		Label* projectNameLabel = new Label();
		projectNameLabel->setTextHorizontalAlignment(MAW_ALIGNMENT_LEFT);
		projectNameLabel->setTextVerticalAlignment(MAW_ALIGNMENT_CENTER);
		projectNameLabel->setText(i->name);
		projectNameLabel->fillSpaceHorizontally();
		projectNameLabel->fillSpaceVertically();

		if (mOS.find("iPhone") >= 0)
		{
			itemHorizontalLayout->setWidth(item->getWidth());
			projectNameLabel->setFontColor(0xffffff);
		}

		itemHorizontalLayout->addChild(projectNameLabel);

		item->addChild(itemHorizontalLayout);

		mListView->addChild(item);
	}
	mListView->setVisible(true);

	// Remove Indicator and Add Project ListView
	//this->addChild(mListView);
	//this->removeChild(mActivityIndicatorContainer);

}
Ejemplo n.º 9
0
int WaitingMenu::run(sf::RenderWindow &window, CommonData* commonData) {
    // Create background
    sf::Sprite background(commonData->defaultBackgroundTexture);

    // Create menu title
    Label* lobbyTitle = new Label("Lobby", 100, commonData);
    lobbyTitle->setPosition((SCREEN_WIDTH - lobbyTitle->getWidth()) / 2, 50);

    // Teams labels
    Label* blueTeamLabel = new Label("Blue team", 70, 150, 200, commonData);
    blueTeamLabel->setColor(sf::Color::Blue);
    Label* redTeamLabel = new Label("Red team", 70, commonData);
    redTeamLabel->setPosition(SCREEN_WIDTH - redTeamLabel->getWidth() - 150, 200);
    redTeamLabel->setColor(sf::Color::Red);

    // Players labels
    Label** playerLabel = new Label*[4];
    for (int i = 0; i < 4; i++) {
        playerLabel[i] = new Label("", 60, 180, 300 + (i/2)*100, commonData);
        if (i % 2 == 1) {
            playerLabel[i]->setPosition(SCREEN_WIDTH - playerLabel[i]->getWidth() - 180, 300 + (i/2)*100);
        }
    }

    // Countdown label
    Label* countdownLabel = new Label("The game will start in 15 seconds...", 40, commonData);
    countdownLabel->setPosition(SCREEN_WIDTH - countdownLabel->getWidth() - 30, 600);

    // Countdown
    sf::Clock clock;
    sf::Time fiveteenSeconds = sf::seconds(15.0f);
    int amountOfPlayers = 0;

    // Main loop
    while (window.isOpen()) {
        // Position of mouse
        sf::Vector2i position = sf::Mouse::getPosition(window);

        // Process events
        sf::Event event;
        while (window.pollEvent(event)) {
            // Close window: exit
            if (event.type == sf::Event::Closed) {
                window.close();
            }

            // Escape pressed: exit
            if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) {
                window.close();
            }
        }

        // Show players name on labels
        for (int i = 0; i < commonData->map->playersSize(); i++) {
            Player* player = commonData->map->getPlayerAtIndex(i);
            playerLabel[player->getID()]->setString(player->getName());
        }

        // Prepare countdown information
        if ((amountOfPlayers != commonData->map->playersSize()) && (commonData->map->playersSize() == 2 || commonData->map->playersSize() == 4)) {
            clock.restart();
            amountOfPlayers = commonData->map->playersSize();
        }

        // Clear screen
        window.clear(sf::Color::Black);

        // Draw
        window.draw(background);
        lobbyTitle->draw(window);
        blueTeamLabel->draw(window);
        redTeamLabel->draw(window);
        for (int i = 0; i < 4; i++) {
            if (i % 2 == 1) {
                playerLabel[i]->setPosition(SCREEN_WIDTH - playerLabel[i]->getWidth() - 180, 300 + (i/2)*100);
            }
            playerLabel[i]->draw(window);
        }

        // Show information about starting game only when there are 2 or 4 players
        if (commonData->map->playersSize() == 2 || commonData->map->playersSize() == 4) {
            int timeToStart = (int)ceil(fiveteenSeconds.asSeconds() - clock.getElapsedTime().asSeconds());
            if (timeToStart <= 3) {
                timeToStart = 3;
            }
            countdownLabel->setString("The game will start in " + Converter::int2string(timeToStart) + " seconds...");
            countdownLabel->setPosition(SCREEN_WIDTH - countdownLabel->getWidth() - 30, 600);
            countdownLabel->draw(window);
        }

        // Update the window
        window.display();

        // Go to the game if countdown will finish
        if ((amountOfPlayers == 2 || amountOfPlayers == 4) && clock.getElapsedTime().asSeconds() > fiveteenSeconds.asSeconds() - 3.0f && commonData->gameStarted == true) {
            return GAME;
        }
    }

    // Change screen
    return EXIT;
}
Ejemplo n.º 10
0
void TestUnicodePath::onEnter()
{
    FileUtilsDemo::onEnter();
    auto s = Director::getInstance()->getWinSize();
    auto util = FileUtils::getInstance();
    
    int x = s.width/2,
    y = s.height/5;
    Label* label = nullptr;
    
    std::string dir = "中文路径/";
    std::string filename = "测试文件.test";

    std::string act;
    auto getMsg = [&act](bool b, const std::string& path)-> std::string
    {
        char msg[512];
        snprintf((char *)msg, 512, "%s for %s path: \"%s\"", b ? "success" : "failed", act.c_str(), path.c_str());
        return std::string(msg);
    };
    
    // Check whether unicode dir should be create or not
    std::string dirPath = util->getWritablePath() + dir;
    if (!util->isDirectoryExist(dirPath))
    {
        util->createDirectory(dirPath);
    }
    
    act = "create";
    bool isExist = util->isDirectoryExist(dirPath);
    label = Label::createWithSystemFont(getMsg(isExist, dirPath), "", 12, Size(s.width, 0));
    label->setPosition(x, y * 4);
    this->addChild(label);
    
    if (isExist)
    {
        // Check whether unicode file should be create or not
        std::string filePath = dirPath + filename;
        if (! util->isFileExist(filePath))
        {
            std::string writeDataStr = " 测试字符串.";
            Data writeData;
            writeData.copy((unsigned char *)writeDataStr.c_str(), writeDataStr.size());
            util->writeDataToFile(writeData, filePath);
        }
        
        isExist = util->isFileExist(filePath);
        label = Label::createWithSystemFont(getMsg(isExist, filePath), "", 12, Size(s.width, 0));
        label->setPosition(x, y * 3);
        this->addChild(label);
        
        act = "remove";
        if (isExist)
        {
            // read file content and log it
            unsigned char* buffer = nullptr;
            Data readData = util->getDataFromFile(filePath);
            buffer = (unsigned char*)malloc(sizeof(unsigned char) * (readData.getSize() + 1));
            memcpy(buffer, readData.getBytes(), readData.getSize());
            buffer[readData.getSize()] = '\0';
            // vc can't treat unicode string correctly, don't use unicode string in code
            log("The content of file from writable path: %s", buffer);
            free(buffer);
            
            // remove test file
            label = Label::createWithSystemFont(getMsg(util->removeFile(filePath), filePath), "", 12, Size(s.width, 0));
            label->setPosition(x, y * 2);
            this->addChild(label);
        }
        
        // remove test dir
        label = Label::createWithSystemFont(getMsg(util->removeDirectory(dirPath), dirPath), "", 12, Size(s.width, 0));
        label->setPosition(x, y * 1);
        this->addChild(label);
    }
}
AnimationPlayerEditor::AnimationPlayerEditor(EditorNode *p_editor) {
	editor=p_editor;
	singleton=this;

	updating=false;

	set_focus_mode(FOCUS_ALL);

	player=NULL;
	add_style_override("panel", get_stylebox("panel","Panel"));


	Label * l;

	/*l= memnew( Label );
	l->set_text(TTR("Animation Player:"));
	add_child(l);*/

	HBoxContainer *hb = memnew( HBoxContainer );
	add_child(hb);


	play_bw_from = memnew( ToolButton );
	play_bw_from->set_tooltip(TTR("Play backwards selected animation from current pos. (A)"));
	hb->add_child(play_bw_from);

	play_bw = memnew( ToolButton );
	play_bw->set_tooltip(TTR("Play backwards selected animation from end. (Shift+A)"));
	hb->add_child(play_bw);

	stop = memnew( ToolButton );
	stop->set_toggle_mode(true);
	hb->add_child(stop);
	stop->set_tooltip(TTR("Stop animation playback. (S)"));

	play = memnew( ToolButton );
	play->set_tooltip(TTR("Play selected animation from start. (Shift+D)"));
	hb->add_child(play);


	play_from = memnew( ToolButton );
	play_from->set_tooltip(TTR("Play selected animation from current pos. (D)"));
	hb->add_child(play_from);



	//pause = memnew( Button );
	//pause->set_toggle_mode(true);
	//hb->add_child(pause);

	frame = memnew( SpinBox );
	hb->add_child(frame);
	frame->set_custom_minimum_size(Size2(60,0));
	frame->set_stretch_ratio(2);
	frame->set_tooltip(TTR("Animation position (in seconds)."));

	hb->add_child( memnew( VSeparator));

	scale = memnew( LineEdit );
	hb->add_child(scale);
	scale->set_h_size_flags(SIZE_EXPAND_FILL);
	scale->set_stretch_ratio(1);
	scale->set_tooltip(TTR("Scale animation playback globally for the node."));
	scale->hide();


	add_anim = memnew( ToolButton );
	add_anim->set_tooltip(TTR("Create new animation in player."));

	hb->add_child(add_anim);


	load_anim = memnew( ToolButton );
	load_anim->set_tooltip(TTR("Load an animation from disk."));
	hb->add_child(load_anim);

	save_anim = memnew(MenuButton);
	save_anim->set_tooltip(TTR("Save the current animation"));
	save_anim->get_popup()->add_item(TTR("Save"), ANIM_SAVE);
	save_anim->get_popup()->add_item(TTR("Save As.."), ANIM_SAVE_AS);
	save_anim->set_focus_mode(Control::FOCUS_NONE);
	hb->add_child(save_anim);

	accept = memnew(AcceptDialog);
	add_child(accept);
	accept->connect("confirmed", this, "_menu_confirm_current");

	duplicate_anim = memnew( ToolButton );
	hb->add_child(duplicate_anim);
	duplicate_anim->set_tooltip(TTR("Duplicate Animation"));

	rename_anim = memnew( ToolButton );
	hb->add_child(rename_anim);
	rename_anim->set_tooltip(TTR("Rename Animation"));

	remove_anim = memnew( ToolButton );

	hb->add_child(remove_anim);
	remove_anim->set_tooltip(TTR("Remove Animation"));


	animation = memnew( OptionButton );
	hb->add_child(animation);
	animation->set_h_size_flags(SIZE_EXPAND_FILL);
	animation->set_tooltip(TTR("Display list of animations in player."));

	autoplay = memnew( ToolButton );
	hb->add_child(autoplay);
	autoplay->set_tooltip(TTR("Autoplay On Load"));



	blend_anim = memnew( ToolButton );
	hb->add_child(blend_anim);
	blend_anim->set_tooltip(TTR("Edit Target Blend Times"));

	tool_anim = memnew( MenuButton);
	//tool_anim->set_flat(false);
	tool_anim->set_tooltip(TTR("Animation Tools"));
	tool_anim->get_popup()->add_item(TTR("Copy Animation"),TOOL_COPY_ANIM);
	tool_anim->get_popup()->add_item(TTR("Paste Animation"),TOOL_PASTE_ANIM);
	//tool_anim->get_popup()->add_separator();
	//tool_anim->get_popup()->add_item(TTR("Edit Anim Resource"),TOOL_PASTE_ANIM);
	hb->add_child(tool_anim);

	nodename = memnew( Button );
	hb->add_child(nodename);
	pin = memnew( ToolButton );
	pin->set_toggle_mode(true);
	hb->add_child(pin);



	resource_edit_anim= memnew( Button );
	hb->add_child(resource_edit_anim);
	resource_edit_anim->hide();


	file = memnew(EditorFileDialog);
	add_child(file);

	name_dialog = memnew( ConfirmationDialog );
	name_dialog->set_title(TTR("Create New Animation"));
	name_dialog->set_hide_on_ok(false);
	add_child(name_dialog);
	name = memnew( LineEdit );
	name_dialog->add_child(name);
	name->set_pos(Point2(18,30));
	name->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_END,10);
	name_dialog->register_text_enter(name);


	l = memnew( Label );
	l->set_text(TTR("Animation Name:"));
	l->set_pos( Point2(10,10) );

	name_dialog->add_child(l);
	name_title=l;

	error_dialog = memnew( ConfirmationDialog );
	error_dialog->get_ok()->set_text(TTR("Close"));
	//error_dialog->get_cancel()->set_text(TTR("Close"));
	error_dialog->set_text(TTR("Error!"));
	add_child(error_dialog);

	name_dialog->connect("confirmed", this,"_animation_name_edited");

	blend_editor.dialog = memnew( AcceptDialog );
	add_child(blend_editor.dialog);
	blend_editor.dialog->get_ok()->set_text(TTR("Close"));
	blend_editor.dialog->set_hide_on_ok(true);
	VBoxContainer *blend_vb = memnew( VBoxContainer);
	blend_editor.dialog->add_child(blend_vb);
	blend_editor.dialog->set_child_rect(blend_vb);
	blend_editor.tree = memnew( Tree );
	blend_editor.tree->set_columns(2);
	blend_vb->add_margin_child(TTR("Blend Times: "),blend_editor.tree,true);
	blend_editor.next = memnew( OptionButton );
	blend_vb->add_margin_child(TTR("Next (Auto Queue):"),blend_editor.next);
	blend_editor.dialog->set_title(TTR("Cross-Animation Blend Times"));
	updating_blends=false;

	blend_editor.tree->connect("item_edited",this,"_blend_edited");


	autoplay->connect("pressed", this,"_autoplay_pressed");
	autoplay->set_toggle_mode(true);
	play->connect("pressed", this,"_play_pressed");
	play_from->connect("pressed", this,"_play_from_pressed");
	play_bw->connect("pressed", this,"_play_bw_pressed");
	play_bw_from->connect("pressed", this,"_play_bw_from_pressed");
	stop->connect("pressed", this,"_stop_pressed");
	//pause->connect("pressed", this,"_pause_pressed");
	add_anim->connect("pressed", this,"_animation_new");
	rename_anim->connect("pressed", this,"_animation_rename");
	load_anim->connect("pressed", this,"_animation_load");
	duplicate_anim->connect("pressed", this,"_animation_duplicate");
	//frame->connect("text_entered", this,"_seek_frame_changed");

	blend_anim->connect("pressed", this,"_animation_blend");
	remove_anim->connect("pressed", this,"_animation_remove");
	animation->connect("item_selected", this,"_animation_selected",Vector<Variant>(),true);
	resource_edit_anim->connect("pressed", this,"_animation_resource_edit");
	file->connect("file_selected", this,"_dialog_action");
	 frame->connect("value_changed", this, "_seek_value_changed",Vector<Variant>(),true);
	 scale->connect("text_entered", this, "_scale_changed",Vector<Variant>(),true);



	renaming=false;
	last_active=false;

	set_process_unhandled_key_input(true);

	key_editor = memnew( AnimationKeyEditor);
	add_child(key_editor);
	add_constant_override("separation",get_constant("separation","VBoxContainer"));
	key_editor->set_v_size_flags(SIZE_EXPAND_FILL);
	key_editor->connect("timeline_changed",this,"_animation_key_editor_seek");
	key_editor->connect("animation_len_changed",this,"_animation_key_editor_anim_len_changed");
	key_editor->connect("animation_step_changed",this,"_animation_key_editor_anim_step_changed");

	_update_player();
}
Ejemplo n.º 12
0
void TestDirectoryFuncs::onEnter()
{
    FileUtilsDemo::onEnter();
    auto s = Director::getInstance()->getWinSize();
    auto sharedFileUtils = FileUtils::getInstance();

    int x = s.width/2,
    y = s.height/4;
    Label* label = nullptr;

    std::string dir = sharedFileUtils->getWritablePath() + "__test/";
    std::string subDir = "dir1/dir2";
    std::string msg;
    bool ok;

    // Check whether dir can be created
    ok = sharedFileUtils->createDirectory(dir);
    if (ok && sharedFileUtils->isDirectoryExist(dir))
    {
        msg = StringUtils::format("createDirectory: Directory '__test' created");
        label = Label::createWithSystemFont(msg, "", 20);
        label->setPosition(x, y * 3);
        this->addChild(label);

        // Create sub directories recursively
        ok = sharedFileUtils->createDirectory(dir + subDir);
        if (ok && sharedFileUtils->isDirectoryExist(dir + subDir))
        {
            msg = StringUtils::format("createDirectory: Sub directories '%s' created", subDir.c_str());
            label = Label::createWithSystemFont(msg, "", 20);
            label->setPosition(x, y * 2);
            this->addChild(label);
        }
        else
        {
            msg = StringUtils::format("createDirectory: Failed to create sub directories '%s'", subDir.c_str());
            label = Label::createWithSystemFont(msg, "", 20);
            label->setPosition(x, y * 2);
            this->addChild(label);
        }

        // Remove directory
        ok = sharedFileUtils->removeDirectory(dir);
        if (ok && !sharedFileUtils->isDirectoryExist(dir))
        {
            msg = StringUtils::format("removeDirectory: Directory '__test' removed");
            label = Label::createWithSystemFont(msg, "", 20);
            label->setPosition(x, y);
            this->addChild(label);
        }
        else
        {
            msg = StringUtils::format("removeDirectory: Failed to remove directory '__test'");
            label = Label::createWithSystemFont(msg, "", 20);
            label->setPosition(x, y);
            this->addChild(label);
        }
    }
    else
    {
        msg = StringUtils::format("createDirectory: Directory '__test' can not be created");
        label = Label::createWithSystemFont(msg, "", 20);
        label->setPosition(x, y * 2);
        this->addChild(label);
    }
}
Ejemplo n.º 13
0
void TestFileFuncs::onEnter()
{
    FileUtilsDemo::onEnter();
    auto s = Director::getInstance()->getWinSize();
    auto sharedFileUtils = FileUtils::getInstance();

    int x = s.width/2,
        y = s.height/5;
    Label* label = nullptr;

    std::string filename = "__test.test";
    std::string filename2 = "__newtest.test";
    std::string filepath = sharedFileUtils->getWritablePath() + filename;
    std::string content = "Test string content to put into created file";
    std::string msg;

    FILE *out = fopen(filepath.c_str(), "w");
    fputs(content.c_str(), out);
    fclose(out);

    // Check whether file can be created
    if (sharedFileUtils->isFileExist(filepath))
    {
        label = Label::createWithSystemFont("Test file '__test.test' created", "", 20);
        label->setPosition(x, y * 4);
        this->addChild(label);

        // getFileSize Test
        long size = sharedFileUtils->getFileSize(filepath);
        msg = StringUtils::format("getFileSize: Test file size equals %ld", size);
        label = Label::createWithSystemFont(msg, "", 20);
        label->setPosition(x, y * 3);
        this->addChild(label);

        // renameFile Test
        if (sharedFileUtils->renameFile(sharedFileUtils->getWritablePath(), filename, filename2))
        {
            label = Label::createWithSystemFont("renameFile: Test file renamed to  '__newtest.test'", "", 20);
            label->setPosition(x, y * 2);
            this->addChild(label);

            // removeFile Test
            filepath = sharedFileUtils->getWritablePath() + filename2;
            if (sharedFileUtils->removeFile(filepath))
            {
                label = Label::createWithSystemFont("removeFile: Test file removed", "", 20);
                label->setPosition(x, y * 1);
                this->addChild(label);
            }
            else
            {
                label = Label::createWithSystemFont("removeFile: Failed to remove test file", "", 20);
                label->setPosition(x, y * 1);
                this->addChild(label);
            }
        }
        else
        {
            label = Label::createWithSystemFont("renameFile: Failed to rename test file to  '__newtest.test', further test skipped", "", 20);
            label->setPosition(x, y * 2);
            this->addChild(label);
        }
    }
    else
    {
        label = Label::createWithSystemFont("Test file can not be created, test skipped", "", 20);
        label->setPosition(x, y * 4);
        this->addChild(label);
    }
}
Ejemplo n.º 14
0
bool DialogNode::init(std::string title, std::string content, std::string btn1Text, cocos2d::CallFuncN* btn1Callback, std::string btn2Text, cocos2d::CallFuncN* btn2Callback)
{
    if(Node::init())
    {
		this->m_btn1Callback = NULL;
		this->m_btn2Callback = NULL;

		if (btn1Callback)
		{			
			this->m_btn1Callback = btn1Callback;
			this->m_btn1Callback->retain();
		}
		
		if (btn2Callback)
		{			
			this->m_btn2Callback = btn2Callback;
			this->m_btn2Callback->retain();
		}
		
        this->setScale(0);
        
        Sprite *bgSprite = Sprite::create("dialog_bg.png");        
        this->addChild(bgSprite);
		this->setContentSize(bgSprite->getContentSize());
		this->setAnchorPoint(Vec2(0.5, 0.5));
		bgSprite->setPosition(Vec2(this->getContentSize().width / 2, this->getContentSize().height / 2));

		Label *labTitle = Label::createWithSystemFont(title.c_str(), GAME_CONFIG_GLOBAL_FONTNAME_01, 32);
		labTitle->setPosition(Vec2(this->getContentSize().width / 2, 170));
		labTitle->setTag((int)ChildTag::LAB_TITLE);
		this->addChild(labTitle);

		Label *labContent = Label::create(content, GAME_CONFIG_GLOBAL_FONTNAME_01, 25, Size(300, 70), TextHAlignment::LEFT, TextVAlignment::TOP);
		labContent->setPosition(Vec2(this->getContentSize().width / 2, 115));
		labContent->setTag((int)ChildTag::LAB_CONTENT);
		this->addChild(labContent);

		if (btn2Callback)
		{
			//2个按钮

			Button *btn1 = Button::create();
			btn1->loadTextureNormal("dialog_btn_yes_1.png");
			btn1->loadTexturePressed("dialog_btn_yes_2.png");
			btn1->setPosition(Vec2(this->getContentSize().width / 2 - 90, 45));
			btn1->setEnabled(false);
			btn1->addTouchEventListener(CC_CALLBACK_2(DialogNode::onButton, this));
			btn1->setTag((int)ChildTag::BTN_1);
			btn1->setTitleFontName(GAME_CONFIG_GLOBAL_FONTNAME_01);
			btn1->setTitleFontSize(32.0f);
			btn1->setTitleText(btn1Text.c_str());
			btn1->setScale(0.75);
			this->addChild(btn1);

			Button *btn2 = Button::create();
			btn2->loadTextureNormal("dialog_btn_no_1.png");
			btn2->loadTexturePressed("dialog_btn_no_2.png");
			btn2->setPosition(Vec2(this->getContentSize().width / 2 + 90, 45));
			btn2->setEnabled(false);
			btn2->addTouchEventListener(CC_CALLBACK_2(DialogNode::onButton, this));
			btn2->setTag((int)ChildTag::BTN_2);
			btn2->setTitleFontName(GAME_CONFIG_GLOBAL_FONTNAME_01);
			btn2->setTitleFontSize(32.0f);
			btn2->setTitleText(btn2Text.c_str());
			btn2->setScale(0.75);
			this->addChild(btn2);
		}
		else
		{
			//1个按钮

			Button *btn1 = Button::create();
			btn1->loadTextureNormal("dialog_btn_yes_1.png");
			btn1->loadTexturePressed("dialog_btn_yes_2.png");
			btn1->setPosition(Vec2(this->getContentSize().width / 2, 45));
			btn1->setEnabled(false);
			btn1->addTouchEventListener(CC_CALLBACK_2(DialogNode::onButton, this));
			btn1->setTag((int)ChildTag::BTN_1);
			btn1->setTitleFontName(GAME_CONFIG_GLOBAL_FONTNAME_01);
			btn1->setTitleFontSize(32.0f);
			btn1->setTitleText(btn1Text.c_str());
			btn1->setScale(0.75);
			this->addChild(btn1);
		}
		
        this->runAction(Sequence::createWithTwoActions(EaseElasticOut::create(ScaleTo::create(1, 1)), CallFunc::create(CC_CALLBACK_0(DialogNode::showActEnd, this))));
        
        return true;
    }
    return false;
}
Ejemplo n.º 15
0
StepsNewGesture::StepsNewGesture(ExecutionManager *pExecutionManager, int pNumberOfGesture, QWidget *parent)
{
    int labelFontSize = 23;
    QColor labelColor = QColor(210,210,210);

    this->executionManager = pExecutionManager;
    this->commandChooser = new CommandChooser(parent);

    this->stepper = new StepperNewGesture(this->executionManager, this->commandChooser, pNumberOfGesture, parent);

    /* Local */
    QString locale = QLocale::system().name().section('_', 0, 0);
    XmlConf* conf = Xml().importConfig(Utils::getConfigLocation());
    if (conf != NULL)
    {
        if (conf->language != NULL)
        {
            locale = conf->language;
        }
    }
    if (locale.compare("en") != 0 && locale.compare("fr") != 0)
    {
        locale = "en";
    }

    /* STEP 0 */
    QWidget *step = new QWidget(stepper);
    QVBoxLayout* vLayoutStep = new QVBoxLayout(step);
    vLayoutStep->setMargin(0);
    Label* lblStepTop = new Label(tr("\n\nThe recording of a gesture MUST start and end with a neutral stance.\n\n"),step);
    lblStepTop->setTextColor(labelColor);
    lblStepTop->changeFontSize(16);
    lblStepTop->setPaintShadow(false);
    lblStepTop->setFixedHeight(60);
    lblStepTop->setPaintShadow(false);
    QLabel *picNeutral = new QLabel(step);
    QPixmap pix = QPixmap(Utils::getResourcesDirectory() + "/tuto/neutral_" + locale + ".png");
    picNeutral->setPixmap(pix);
    vLayoutStep->addWidget(lblStepTop);
    vLayoutStep->addWidget(picNeutral);
    stepper->addStep(tr("Information"),true,false,true, StepperNewGesture::First ,step);

    /* STEP 1 */
    Label *step1 = new Label(tr("You will have 5 seconds to place\nbefore registering your gesture\n1/") + QString::number(pNumberOfGesture),stepper);
    step1->changeFontSize(labelFontSize);
    step1->setTextColor(labelColor);
    step1->setPaintShadow(false);
    stepper->addStep(tr("Add a new gesture"),true,true,true, StepperNewGesture::StartTimer ,step1);

    /* STEP 2 */
    Label *step2 = new Label(tr("Ready ?"),stepper);
    step2->changeFontSize(labelFontSize);
    step2->setTextColor(labelColor);
    step2->setPaintShadow(false);
    stepper->addStep(tr("Add a new gesture"),false,true,true,StepperNewGesture::StartRecording ,step2);

    /* STEP 3 */
    QWidget* step3 = new QWidget(parent);
    QVBoxLayout* vLayoutStep3 = new QVBoxLayout(step3);
    GlView* glViewStep3= new GlView(step3);
    DAOLayer* dao = DAOLayer::getInstance();
    connect(dao, SIGNAL(skeletonDataReceived(QString)), glViewStep3,SLOT(skeletonDataReceived(QString)));
    Label* labelStep3 = new Label(tr("Realtime visualizer"), step3);
    labelStep3->setFixedHeight(50);
    labelStep3->changeFontSize(labelFontSize);
    labelStep3->setTextColor(labelColor);
    labelStep3->setPaintShadow(false);
    vLayoutStep3->addWidget(labelStep3);
    vLayoutStep3->addWidget(glViewStep3);
    glViewStep3->startAnimating();
    stepper->addStep(tr("Add a new gesture"),false,true,true,StepperNewGesture::VisualizeRecording ,step3);

    /* STEP 4 */
    QWidget* step4 = new QWidget(parent);
    QVBoxLayout* vLayoutStep4 = new QVBoxLayout(step4);
    this->glViewStep4= new GlView(step4);
    connect(this->executionManager, SIGNAL(gestureRecorded(Gesture*)), this, SLOT(gestureReceived(Gesture*)));
    Label *labelStep4 = new Label(tr("Is it the right gesture ?"),stepper);
    labelStep4->setFixedHeight(50);
    labelStep4->changeFontSize(labelFontSize);
    labelStep4->setTextColor(labelColor);
    labelStep4->setPaintShadow(false);
    vLayoutStep4->addWidget(labelStep4);
    vLayoutStep4->addWidget(this->glViewStep4);
    this->glViewStep4->startAnimating();
    stepper->addStep(tr("Add a new gesture"),true,true,true,StepperNewGesture::ConfigureAction,step4);

    /* STEP 5 */
    QWidget* step5 = new QWidget(parent);
    QVBoxLayout* vLayout = new QVBoxLayout(step5);


    QWidget* step5Bottom = new QWidget(step5);
    QHBoxLayout* hLayoutStep5 = new QHBoxLayout(step5Bottom);
    this->commandChooser->setParent(step5Bottom);

    ComboBox *combo = this->commandChooser->getCommandComboBox();
    KeyListener *keyListener = this->commandChooser->getCommandKeyListener();
    TextField *tfNewGesture = this->commandChooser->getCommandTextField();
    ButtonElement *btnCommand = this->commandChooser->getCommandButton();
    Label* labelRecordName = new Label("Record name : ",step5);
    labelRecordName->setPaintShadow(false);
    labelRecordName->setTextColor(labelColor);
    TextField *tfRecordName = this->commandChooser->getRecordNameTextField();


    hLayoutStep5->addWidget(combo);
    hLayoutStep5->addWidget(keyListener);
    hLayoutStep5->addWidget(tfNewGesture);
    hLayoutStep5->addWidget(btnCommand);
    hLayoutStep5->addWidget(labelRecordName);
    hLayoutStep5->addWidget(tfRecordName);

    Label *labelStep5 = new Label(tr("Command linked to your gesture"),step5);
    labelStep5->setPaintShadow(false);
    labelStep5->changeFontSize(labelFontSize);
    labelStep5->setTextColor(labelColor);
    labelStep5->setFixedHeight(50);

    vLayout->addWidget(labelStep5);
    vLayout->addWidget(step5Bottom);

    stepper->addStep(tr("Add a new gesture"),true,false,true,StepperNewGesture::SaveRecord,step5);

    /* STEP 6 */
    QWidget* step6 = new QWidget(parent);
    QLabel* labelLoading = new QLabel(step6);
    QMovie* loading = new QMovie(Utils::getResourcesDirectory() + "loader.gif", QByteArray(), labelLoading);
    labelLoading->resize(128, 128);
    labelLoading->setMovie(loading);
    loading->start();
    stepper->addStep(tr("Add a new gesture"),false,false,false,StepperNewGesture::Close,step6);
    labelLoading->move(step6->width()/2 - labelLoading->width()/2, step6->height()/2 - labelLoading->height()/2);
}
Ejemplo n.º 16
0
// メッセージを生成
Label* CharacterMessageLayer::createMessage()
{
    CharacterMessageData* data {this->datas.front()};
    
    // フレームの位置を戻す
    this->frame->stopAllActions();
    this->frame->setPosition(this->defaultMFramePosition);
    
    // リアクション
    if(data->getOption() == CharacterMessageData::Option::REACTION)
    {
        // 白いエフェクトを出してフェードアウト
        Sprite* white { Sprite::create() };
        white->setTextureRect(Rect(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT));
        white->setColor(Color3B::WHITE);
        white->setPosition(white->getContentSize() / 2);
        this->addChild(white);
        this->reactionEffect = white;
        white->runAction(Sequence::createWithTwoActions(FadeOut::create(1.f), RemoveSelf::create()));
        
        // フレームを揺らす
        Action* swingAction { RepeatForever::create(Sequence::createWithTwoActions(MoveBy::create(0.05f, Vec2(10.f, 0)), MoveBy::create(0.05f, Vec2(-10.f, 0)))) };
        this->frame->runAction(swingAction);
        
        this->runAction(Sequence::create(DelayTime::create(1.5f),CallFunc::create([this, swingAction]
            {
                this->stopAction(swingAction);
                if(_closed) return;
                this->frame->setPosition(this->defaultMFramePosition);
            }), nullptr));
        
        SoundManager::getInstance()->playSE("msg_reaction.mp3", 0.5f);
    }
    
    // ボイスがあれば鳴らす
    string voiceFileName = data->getVoiceFileName();
    if (voiceFileName != "") {
        SoundManager::getInstance()->playVoice(voiceFileName);
    }
 
    // キャラクター画像
    if(this->charaImg)
    {
        this->charaImg->removeFromParent();
        this->charaImg = nullptr;
    }

    if(data->getImageName() == "") {
        string charaImgName = CsvDataManager::getInstance()->getCharacterData()->getFileName(data->getCharaId()) + ((data->isMiniChara())? "_m_" : "_s_") + to_string(data->getImgId()) + ".png" ;
        Point charaImgPoint = (data->isMiniChara())? Point(WINDOW_WIDTH * 4 / 5, WINDOW_HEIGHT * 7 / 40) : Point(WINDOW_WIDTH * 3 / 4, 0);
        
        if(data->getCharaId() != -1 && SpriteFrameCache::getInstance()->getSpriteFrameByName(charaImgName))
        {
            Sprite* img { Sprite::createWithSpriteFrameName(charaImgName)};
            img->setPosition(charaImgPoint);
            img->setLocalZOrder((data->isMiniChara()) ? 1 : -1);
            this->addChild(img);
            this->charaImg = img;
        }
    } else {
        Sprite* img {Sprite::create(Resource::SpriteFrame::BASE_PATH + "disp/" + data->getImageName())};
        img->setPosition(WINDOW_CENTER);
        img->setLocalZOrder((data->isImageOnly()) ? 1 : -1);
        img->setOpacity(0);
        this->addChild(img);
        img->runAction(FadeIn::create(0.5f));
    }
    
    
	// キャラクター名
	this->nameFrame->removeAllChildren();
	Label* name { Label::createWithTTF(data->getCharaName(), "fonts/cinecaption2.28.ttf", 26.f)};
	this->nameFrame->addChild(name);
	
	// キャラクター名の長さによってキャラクター名用枠の大きさ、位置を変える
	this->nameFrame->setContentSize(Size(name->getContentSize().width + H_MARGIN_S * 2, this->nameFrame->getContentSize().height));
	this->nameFrame->setPosition(this->nameFrame->getContentSize().width / 2 + LEFT_MARGIN / 4, this->frame->getContentSize().height + this->nameFrame->getContentSize().height / 2);

	name->setPosition(this->nameFrame->getContentSize() / 2);
	
	// メッセージ本文
	Label* message = Label::createWithTTF(data->getMessage(), "fonts/cinecaption2.28.ttf", 24.f);
    message->setLineHeight(36.f);
    message->setHorizontalAlignment(TextHAlignment::LEFT);
    message->setVerticalAlignment(TextVAlignment::TOP);
	message->setPosition(Point(message->getContentSize().width / 2 + LEFT_MARGIN, this->frame->getContentSize().height - message->getContentSize().height / 2 - TOP_MARGIN));
	this->frame->addChild(message);
    
    if(data->isImageOnly()){
        this->removeChildByTag(MAIN_FRAME_TAG);
        this->removeChildByTag(NAME_FRAME_TAG);
        _closed = true;
    }

    if(!this->datas.front()->hasNextPage())
    {
        CC_SAFE_RELEASE(this->datas.front());
        this->datas.pop();
    }

    return message;
}
Ejemplo n.º 17
0
Archivo: mesos.cpp Proyecto: krux/mesos
bool operator==(const Label& left, const Label& right)
{
  return left.key() == right.key() && left.value() == right.value();
}
Ejemplo n.º 18
0
SceneTreeEditor::SceneTreeEditor(bool p_label,bool p_can_rename, bool p_can_open_instance) {
	

	undo_redo=NULL;
	tree_dirty=true;
	selected=NULL;

	marked_selectable=false;
	marked_children_selectable=false;
	can_rename=p_can_rename;
	can_open_instance=p_can_open_instance;
	display_foreign=false;
	editor_selection=NULL;
	
	if (p_label) {
		Label *label = memnew( Label );
		label->set_pos( Point2(10, 0));
		label->set_text("Scene Tree (Nodes):");
		
		add_child(label);
	}
	
	tree = memnew( Tree );
	tree->set_anchor( MARGIN_RIGHT, ANCHOR_END );
	tree->set_anchor( MARGIN_BOTTOM, ANCHOR_END );	
	tree->set_begin( Point2(0,p_label?18:0 ));
	tree->set_end( Point2(0,0 ));
	
	add_child( tree );
		
	tree->connect("cell_selected", this,"_selected_changed");
	tree->connect("item_edited", this,"_renamed");
	tree->connect("multi_selected",this,"_cell_multi_selected");
	tree->connect("button_pressed",this,"_cell_button_pressed");
//	tree->connect("item_edited", this,"_renamed",Vector<Variant>(),true);

	error = memnew( AcceptDialog );
	add_child(error);

	show_enabled_subscene=false;

	last_hash=0;
	pending_test_update=false;
	updating_tree=false;
	blocked=0;

	instance_menu = memnew( PopupMenu );
	instance_menu->add_check_item("Editable Children",SCENE_MENU_EDITABLE_CHILDREN);
	instance_menu->add_check_item("Load As Placeholder",SCENE_MENU_USE_PLACEHOLDER);
	instance_menu->add_separator();
	instance_menu->add_item("Open in Editor",SCENE_MENU_OPEN);
	instance_menu->connect("item_pressed",this,"_subscene_option");
	add_child(instance_menu);

	inheritance_menu = memnew( PopupMenu );
	inheritance_menu->add_item("Clear Inheritance",SCENE_MENU_CLEAR_INHERITANCE);
	inheritance_menu->add_separator();
	inheritance_menu->add_item("Open in Editor",SCENE_MENU_OPEN_INHERITED);
	inheritance_menu->connect("item_pressed",this,"_subscene_option");

	add_child(inheritance_menu);

	clear_inherit_confirm = memnew( ConfirmationDialog );
	clear_inherit_confirm->set_text("Clear Inheritance? (No Undo!)");
	clear_inherit_confirm->get_ok()->set_text("Clear!");
	add_child(clear_inherit_confirm);


}
Ejemplo n.º 19
0
void TraceWindow::Draw_CallStack(HDC p_hdc) {
  SetScrollMax(GetAllLine());

  HDC hdc = m_dlg->getBackDC();

  HBRUSH hbBG = (HBRUSH)CreateSolidBrush(COLOR_BG);
  HBRUSH hbFixedBG = (HBRUSH)CreateSolidBrush(GetSysColor(COLOR_3DFACE));
  HBRUSH hbSelect = CreateSolidBrush(COLOR_SELECT);

  SetBkColor(p_hdc, RGB(0, 0, 0));
  SetBkMode(p_hdc, TRANSPARENT);
  g_dbg->setFontToFixed(p_hdc);

  RECT clientrect;
  GetClientRect(m_dlg->getHwnd(), &clientrect);

  DrawListFrame();

  SetTextColor(p_hdc, RGB(255, 255, 255));

  char str[1024];
  for (int i = 0; i < GetPageLine() + 1; i++) {
    int left = 0;
    for (u32 j = 0; j < m_col_array.size(); j++) {
      RECT selrect;
      selrect.top    = i * kFontSize + GetListTop();
      selrect.bottom  = (i + 1) * kFontSize + GetListTop();
      selrect.left  = left + 1;
      selrect.right  = left + m_col_array[j]->width;

      // 最後はウィンドウの端まで
      if (j == m_col_array.size() - 1) selrect.right = clientrect.right;

      if (i + m_head < GetAllLine() && m_sel == i + m_head) FillRect(hdc, &selrect, hbSelect);
      else FillRect(hdc, &selrect, hbBG);

      if (i + m_head < GetAllLine()) {
        switch (j) {
        case 0:
          sprintf(str, "%08x", g_dbg->callstack(i + m_head)->jva());
          TextOut(hdc, left + 4, kFontSize * i + GetListTop(), str, strlen(str));
          break;
        case 1:
          sprintf(str, "%08x", g_dbg->callstack(i + m_head)->va());
          TextOut(hdc, left + 4, kFontSize * i + GetListTop(), str, strlen(str));
          break;
        case 2: {
            Label *label = g_dbg->find_codelabel(g_dbg->callstack(i + m_head)->jva());
            if (label) {
              TextOut(hdc, left + 4, kFontSize * i + GetListTop(), label->text(), strlen(label->text()));
            }
          }
          break;
        }
      }
      left += m_col_array[j]->width;
    }
  }

  DeleteObject(hbSelect);
  DeleteObject(hbFixedBG);
  DeleteObject(hbBG);

  m_dlg->update(0, GetListHeaderTop(), clientrect.right, clientrect.bottom);
}
Ejemplo n.º 20
0
bool HeroLayer::init()
{
	Size visibleSize = Director::getInstance()->getVisibleSize();

	//title
	auto title = Sprite::createWithSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("titlename_mycard.png"));
	title->setPosition(visibleSize.width / 2, visibleSize.height / 2 + 225);
	addChild(title);

	//return
	auto returnNode = Node::create();

	auto returnButton = Button::create("button_left_0.png", "button_left_1.png", "button_left_2.png", UI_TEX_TYPE_PLIST);
	returnButton->setPosition(Vec2(84, 696));
	returnButton->addClickEventListener(CC_CALLBACK_1(HeroLayer::returnCallBack, this));
	returnNode->addChild(returnButton, 1);

	auto returnButtonText = Sprite::createWithSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("text_return.png"));
	returnButtonText->setPosition(Vec2(70, 696));
	returnNode->addChild(returnButtonText, 2);

	returnNode->setPosition(Vec2::ZERO);
	returnNode->setName("return");
	addChild(returnNode, 3);

	//heroListView
	m_heroListView = ListView::create();
	m_heroListView->setDirection(ui::ScrollView::Direction::VERTICAL);
	m_heroListView->setBounceEnabled(true);  // ·´µ¯
	m_heroListView->setContentSize(Size(565, 550));
	m_heroListView->ignoreContentAdaptWithSize(false);
	m_heroListView->setAnchorPoint(Vec2(0.5f, 0));
	m_heroListView->setPosition(Vec2(visibleSize.width / 2.0f, 100));
	m_heroListView->addEventListenerListView(this, SEL_ListViewEvent(&HeroLayer::selectedItemEvent));

	addChild(m_heroListView);

	Button* default_button = Button::create("button_public_rank_0.png", "button_public_rank_1.png", "button_public_rank_2.png", UI_TEX_TYPE_PLIST);
	default_button->setName("default button");

	Layout *default_layout = Layout::create();
	default_layout->setTouchEnabled(true);
	default_layout->setContentSize(default_button->getContentSize());
	default_button->setPosition(Vec2(default_layout->getContentSize().width / 2.0f, default_layout->getContentSize().height / 2.0f));
	default_layout->addChild(default_button);

	m_heroListView->setItemModel(default_layout);

	size_t size = Player::getInstance()->getCards().size();
	auto cards = Player::getInstance()->getCards();
	XMLParser* m_xmlparser = XMLParser::parseWithFile("xml/name.xml");
	for (auto i = 0; i < size; ++i)
	{
		Button* button = Button::create("button_public_rank_0.png", "button_public_rank_1.png", "button_public_rank_2.png", UI_TEX_TYPE_PLIST);
		button->setScale9Enabled(true);
		button->setSize(default_button->getSize());
		button->setName("card");

		Layout *layout = Layout::create();
		layout->setSize(button->getSize());
		button->setPosition(Vec2(layout->getContentSize().width / 2.0f, layout->getContentSize().height / 2.0f));
		layout->addChild(button,1);

		//card
		auto card_sprite = cards[i].getLittleSprite();
		card_sprite->setScale(0.8f);
		card_sprite->setPosition(Vec2(50, layout->getContentSize().height / 2.0f));
		layout->addChild(card_sprite,2);

		//cardHP
		Label* cardhp = Label::createWithSystemFont(ValueTool::intToString(cards[i].getHP()), "arial", 20);
		cardhp->setPosition(Vec2(layout->getContentSize().width*0.27f, layout->getContentSize().height*0.3f));
		layout->addChild(cardhp, 2);

		//cardSword
		Label* cardsword = Label::createWithSystemFont(ValueTool::intToString(cards[i].getSword()), "arial", 20);
		cardsword->setPosition(Vec2(layout->getContentSize().width*0.48f, layout->getContentSize().height*0.3f));
		layout->addChild(cardsword, 2);

		//cardType
		string cardTypeFrameName = "icon_occupation_" + cards[i].getType() + "_button.png"; 
		auto type_sprite = Sprite::createWithSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName(cardTypeFrameName));
		type_sprite->setPosition(112, layout->getContentSize().height*0.66f);
		layout->addChild(type_sprite, 2);

		//star
		int star_count = 0;
		if (cards[i].getColor() == 3 || cards[i].getColor() == 4)
		{
			star_count = 3;
		}
		if (cards[i].getColor() == 5 || cards[i].getColor() == 6)
		{
			star_count = 4;
		}
		if (cards[i].getColor() == 7 || cards[i].getColor() == 8)
		{
			star_count = 5;
		}
		auto star_node = Node::create();
		for (int i= 0; i < star_count;++i)
		{
			auto star = Sprite::createWithSpriteFrame(SpriteFrameCache::getInstance()->getSpriteFrameByName("star_5.png"));
			star->setPosition(layout->getContentSize().width-40 - 30*(i), layout->getContentSize().height / 2);
			star->setScale(0.9f);
			layout->addChild(star, 2);
		}

		//nameLabel
		String* m_name = m_xmlparser->getString(cards[i].getName().c_str());
		if (cards[i].getColor() % 2 == 0)
		{
			m_name->append(" +");
		}
		Label* cardName = Label::createWithSystemFont(m_name->getCString(), "arial", 20);
		cardName->setAnchorPoint(Vec2(0, 0.5f));
		cardName->setAlignment(TextHAlignment::LEFT);
		cardName->setPosition(Vec2(130, layout->getContentSize().height*0.67f));
		layout->addChild(cardName, 2);

		m_heroListView->pushBackCustomItem(layout);
	}
	m_heroListView->setGravity(ListView::Gravity::CENTER_VERTICAL);

	return true;
}
Ejemplo n.º 21
0
Widget_editor::Widget_editor()
:widget(NULL)
,editing_attributes(false)
,pressed(false)
,left(false)
,right(false)
,top(false)
,bottom(false)
,move(false)
,selected(false)
{
	float margin = 4;
	attributes_max_y = 0;
	attribute_group = new Group;
	attribute_group->Set_bounding_rect(Rect(0, 0, 200, 400));

	Label* label = new Label;
	label->Set_bounding_rect(Rect(margin, attributes_max_y, 200, 20));
	label->Set_text("Base attributes");
	attribute_group->Add_widget(label);
	attributes_max_y += 20;

	//Attribute Top
	label = new Label;
	label->Set_bounding_rect(Rect(margin, attributes_max_y, 100, 20));
	label->Set_text("Top");
	attribute_group->Add_widget(label);

	w_top.Set_bounding_rect(interface::Rect(100-margin, attributes_max_y, 100, 20));
	attribute_group->Add_widget(&w_top);
	attributes_max_y += 20;

	//Attribute Left
	label = new Label;
	label->Set_bounding_rect(Rect(margin, attributes_max_y, 100, 20));
	label->Set_text("Left");
	attribute_group->Add_widget(label);

	w_left.Set_bounding_rect(interface::Rect(100-margin, attributes_max_y, 100, 20));
	attribute_group->Add_widget(&w_left);
	attributes_max_y += 20;

	//Attribute Width
	label = new Label;
	label->Set_bounding_rect(Rect(margin, attributes_max_y, 100, 20));
	label->Set_text("Width");
	attribute_group->Add_widget(label);

	w_width.Set_bounding_rect(interface::Rect(100-margin, attributes_max_y, 100, 20));
	attribute_group->Add_widget(&w_width);
	attributes_max_y += 20;

	//Attribute Height
	label = new Label;
	label->Set_bounding_rect(Rect(margin, attributes_max_y, 100, 20));
	label->Set_text("Height");
	attribute_group->Add_widget(label);

	w_height.Set_bounding_rect(interface::Rect(100-margin, attributes_max_y, 100, 20));
	attribute_group->Add_widget(&w_height);
	attributes_max_y += 20;

	attributes_height = attributes_max_y;
}
Ejemplo n.º 22
0
//-----------------------------------------------------------------------------
// Purpose: Constructs a message panel
//-----------------------------------------------------------------------------
CMessageWindowPanel::CMessageWindowPanel( const char *szMOTD, const char *szTitle, int iShadeFullscreen, int iRemoveMe, int x, int y, int wide, int tall ) : CMenuPanel( iShadeFullscreen ? 100 : 255, iRemoveMe, x, y, wide, tall )
{
	// Get the scheme used for the Titles
	CSchemeManager *pSchemes = gViewPort->GetSchemeManager();

	// schemes
	SchemeHandle_t hTitleScheme = pSchemes->getSchemeHandle( "Title Font" );
	SchemeHandle_t hMOTDText = pSchemes->getSchemeHandle( "Briefing Text" );

	// color schemes
	int r, g, b, a;

	// Create the window
	m_pBackgroundPanel = new CTransparentPanel( iShadeFullscreen ? 255 : 100, MOTD_WINDOW_X, MOTD_WINDOW_Y, MOTD_WINDOW_SIZE_X, MOTD_WINDOW_SIZE_Y );
	m_pBackgroundPanel->setParent( this );
	m_pBackgroundPanel->setBorder( new LineBorder( Color(255 * 0.7,170 * 0.7,0,0)) );
	m_pBackgroundPanel->setVisible( true );

	int iXSize,iYSize,iXPos,iYPos;
	m_pBackgroundPanel->getPos( iXPos,iYPos );
	m_pBackgroundPanel->getSize( iXSize,iYSize );

	// Create the title
	Label *pLabel = new Label( "", iXPos + MOTD_TITLE_X, iYPos + MOTD_TITLE_Y );
	pLabel->setParent( this );
	pLabel->setFont( pSchemes->getFont(hTitleScheme) );
	pLabel->setFont( Scheme::sf_primary1 );

	pSchemes->getFgColor( hTitleScheme, r, g, b, a );
	pLabel->setFgColor( r, g, b, a );
	pLabel->setFgColor( Scheme::sc_primary1 );
	pSchemes->getBgColor( hTitleScheme, r, g, b, a );
	pLabel->setBgColor( r, g, b, a );
	pLabel->setContentAlignment( vgui::Label::a_west );
	pLabel->setText( "%s", szTitle);

	// Create the Scroll panel
	ScrollPanel *pScrollPanel = new CTFScrollPanel( iXPos + XRES(16), iYPos + MOTD_TITLE_Y*2 + YRES(16), iXSize - XRES(32), iYSize - (YRES(48) + BUTTON_SIZE_Y*2) );
	pScrollPanel->setParent(this);
	
	//force the scrollbars on so clientClip will take them in account after the validate
	pScrollPanel->setScrollBarAutoVisible(false, false);
	pScrollPanel->setScrollBarVisible(true, true);
	pScrollPanel->validate();

	// Create the text panel
	TextPanel *pText = new TextPanel( "", 0,0, 64,64);
	pText->setParent( pScrollPanel->getClient() );

	// get the font and colors from the scheme
	pText->setFont( pSchemes->getFont(hMOTDText) );
	pSchemes->getFgColor( hMOTDText, r, g, b, a );
	pText->setFgColor( r, g, b, a );
	pSchemes->getBgColor( hMOTDText, r, g, b, a );
	pText->setBgColor( r, g, b, a );
	pText->setText( szMOTD);

	// Get the total size of the MOTD text and resize the text panel
	int iScrollSizeX, iScrollSizeY;

	// First, set the size so that the client's wdith is correct at least because the
	//  width is critical for getting the "wrapped" size right.
	// You'll see a horizontal scroll bar if there is a single word that won't wrap in the
	//  specified width.
	pText->getTextImage()->setSize(pScrollPanel->getClientClip()->getWide(), pScrollPanel->getClientClip()->getTall());
	pText->getTextImage()->getTextSizeWrapped( iScrollSizeX, iScrollSizeY );
	
	// Now resize the textpanel to fit the scrolled size
	pText->setSize( iScrollSizeX , iScrollSizeY );

	//turn the scrollbars back into automode
	pScrollPanel->setScrollBarAutoVisible(true, true);
	pScrollPanel->setScrollBarVisible(false, false);

	pScrollPanel->validate();

	CommandButton *pButton = new CommandButton( CHudTextMessage::BufferedLocaliseTextString( "#Menu_OK" ), iXPos + XRES(16), iYPos + iYSize - YRES(16) - BUTTON_SIZE_Y, CMENU_SIZE_X, BUTTON_SIZE_Y);
	pButton->addActionSignal(new CMenuHandler_TextWindow(HIDE_TEXTWINDOW));
	pButton->setParent(this);

}
Ejemplo n.º 23
0
SceneTreeEditor::SceneTreeEditor(bool p_label, bool p_can_rename, bool p_can_open_instance) {

	connect_to_script_mode = false;
	undo_redo = NULL;
	tree_dirty = true;
	selected = NULL;

	marked_selectable = false;
	marked_children_selectable = false;
	can_rename = p_can_rename;
	can_open_instance = p_can_open_instance;
	display_foreign = false;
	editor_selection = NULL;

	if (p_label) {
		Label *label = memnew(Label);
		label->set_position(Point2(10, 0));
		label->set_text(TTR("Scene Tree (Nodes):"));

		add_child(label);
	}

	tree = memnew(Tree);
	tree->set_anchor(MARGIN_RIGHT, ANCHOR_END);
	tree->set_anchor(MARGIN_BOTTOM, ANCHOR_END);
	tree->set_begin(Point2(0, p_label ? 18 : 0));
	tree->set_end(Point2(0, 0));
	tree->add_constant_override("button_margin", 0);

	add_child(tree);

	tree->set_drag_forwarding(this);
	if (p_can_rename) {
		tree->set_allow_rmb_select(true);
		tree->connect("item_rmb_selected", this, "_rmb_select");
		tree->connect("empty_tree_rmb_selected", this, "_rmb_select");
	}

	tree->connect("cell_selected", this, "_selected_changed");
	tree->connect("item_edited", this, "_renamed", varray(), CONNECT_DEFERRED);
	tree->connect("multi_selected", this, "_cell_multi_selected");
	tree->connect("button_pressed", this, "_cell_button_pressed");
	tree->connect("nothing_selected", this, "_deselect_items");
	//tree->connect("item_edited", this,"_renamed",Vector<Variant>(),true);

	error = memnew(AcceptDialog);
	add_child(error);

	warning = memnew(AcceptDialog);
	add_child(warning);
	warning->set_title(TTR("Node Configuration Warning!"));

	show_enabled_subscene = false;

	last_hash = 0;
	pending_test_update = false;
	updating_tree = false;
	blocked = 0;

	update_timer = memnew(Timer);
	update_timer->connect("timeout", this, "_update_tree");
	update_timer->set_one_shot(true);
	update_timer->set_wait_time(0.5);
	add_child(update_timer);

	script_types = memnew(List<StringName>);
	ClassDB::get_inheriters_from_class("Script", script_types);
}
Ejemplo n.º 24
0
SelectionRecipe::SelectionRecipe(Container * parent) :
    CustomControl(parent)
{
  Container *recipeContainer = Container::create().left(80).right(80);

  Container *checkBoxContainer = new Container();

  Label *typeLabel = new Label();
  typeLabel->setText("Olive Type");
  typeLabel->textStyle()->setBase(SystemDefaults::TextStyles::titleText());
  typeLabel->textStyle()->setFontWeight(FontWeight::Bold);
  typeLabel->setBottomMargin(0);

  checkBoxContainer->add(typeLabel);

  // Since we want the CheckBox Control to also have a colored box to represent the
  // selection of which olives should be in the mix, a CustomControl is used (see SelectionCheckBox.cpp).
  SelectionCheckBox *limonCello = new SelectionCheckBox();
  limonCello->setOliveColor(QVariant::fromValue<Color>(Color::fromARGB(0xff808000)));
  limonCello->setTitle("Limoncello");
  limonCello->setHorizontalAlignment(HorizontalAlignment::Fill);

  SelectionCheckBox *greek = new SelectionCheckBox();
  greek->setOliveColor(QVariant::fromValue<Color>(Color::fromARGB(0xff698B22)));
  greek->setTitle("Greek");

  SelectionCheckBox *kalamata = new SelectionCheckBox();
  kalamata->setOliveColor(QVariant::fromValue<Color>(Color::fromARGB(0xff733D1A)));
  kalamata->setTitle("Kalamata");

  checkBoxContainer->add(limonCello);
  checkBoxContainer->add(greek);
  checkBoxContainer->add(kalamata);

  // The two menu selections are separated by a Divider.
  Divider *divider = new Divider();
  divider->setBottomMargin(60);

  Label *fillingLabel = new Label();
  fillingLabel->setText("Filling");
  fillingLabel->textStyle()->setBase(SystemDefaults::TextStyles::titleText());
  fillingLabel->textStyle()->setFontWeight(FontWeight::Bold);
  fillingLabel->setBottomMargin(9);

  // The RadioGroup is a Control that you can use if only one option can
  // be selected at a time. RadioGroupOptions are added to the Control
  // and by listening for the onSelectedOptionChanged signal, its possible
  // to keep track of what the current selection is.
  RadioGroup *radioGroup = new RadioGroup();
  radioGroup->setDividersVisible(false);

  Option *stoneOption = new Option();
  stoneOption->setText("Stone");

  Option *pimentoOption = new Option();
  pimentoOption->setText("Pimento");

  radioGroup->add(stoneOption);
  radioGroup->add(pimentoOption);

  // We listen for changes in selected options on the RadioGroup.
  connect(radioGroup, SIGNAL(selectedIndexChanged(int)), this,
      SLOT(fillingSelectedOptionChanged(int)));

  // Add the controls
  recipeContainer->add(checkBoxContainer);
  recipeContainer->add(divider);
  recipeContainer->add(fillingLabel);
  recipeContainer->add(radioGroup);

  setRoot(recipeContainer);
}
Ejemplo n.º 25
0
// Creation
CTeamMenuPanel::CTeamMenuPanel(int iTrans, int iRemoveMe, int x,int y,int wide,int tall) : CMenuPanel(iTrans, iRemoveMe, x,y,wide,tall)
{
	// Get the scheme used for the Titles
	CSchemeManager *pSchemes = gViewPort->GetSchemeManager();

	// schemes
	SchemeHandle_t hTitleScheme = pSchemes->getSchemeHandle( "Title Font" );
	SchemeHandle_t hTeamWindowText = pSchemes->getSchemeHandle( "Briefing Text" );
	SchemeHandle_t hTeamInfoText = pSchemes->getSchemeHandle( "Team Info Text" );

	// get the Font used for the Titles
	Font *pTitleFont = pSchemes->getFont( hTitleScheme );
	int r, g, b, a;

	// Create the title
	Label *pLabel = new Label( "", TEAMMENU_TITLE_X, TEAMMENU_TITLE_Y );
	pLabel->setParent( this );
	pLabel->setFont( pTitleFont );
	pSchemes->getFgColor( hTitleScheme, r, g, b, a );
	pLabel->setFgColor( r, g, b, a );
	pSchemes->getBgColor( hTitleScheme, r, g, b, a );
	pLabel->setBgColor( r, g, b, a );
	pLabel->setContentAlignment( vgui::Label::a_west );
	pLabel->setText(gHUD.m_TextMessage.BufferedLocaliseTextString("#Title_SelectYourTeam"));

	// Create the Info Window
	m_pTeamWindow  = new CTransparentPanel( 255, TEAMMENU_WINDOW_X, TEAMMENU_WINDOW_Y, TEAMMENU_WINDOW_SIZE_X, TEAMMENU_WINDOW_SIZE_Y );
	m_pTeamWindow->setParent( this );
	m_pTeamWindow->setBorder( new LineBorder( Color(255*0.7,170*0.7,0,0 )) );

	// Create the Map Name Label
	m_pMapTitle = new Label( "", TEAMMENU_WINDOW_TITLE_X, TEAMMENU_WINDOW_TITLE_Y );
	m_pMapTitle->setFont( pTitleFont ); 
	m_pMapTitle->setParent( m_pTeamWindow );
	pSchemes->getFgColor( hTitleScheme, r, g, b, a );
	m_pMapTitle->setFgColor( r, g, b, a );
	pSchemes->getBgColor( hTitleScheme, r, g, b, a );
	m_pMapTitle->setBgColor( r, g, b, a );
	m_pMapTitle->setContentAlignment( vgui::Label::a_west );

	// Create the Scroll panel
	m_pScrollPanel = new CTFScrollPanel( TEAMMENU_WINDOW_TEXT_X, TEAMMENU_WINDOW_TEXT_Y, TEAMMENU_WINDOW_SIZE_X - (TEAMMENU_WINDOW_TEXT_X * 2), TEAMMENU_WINDOW_TEXT_SIZE_Y );
	m_pScrollPanel->setParent(m_pTeamWindow);
	m_pScrollPanel->setScrollBarVisible(false, false);

	// Create the Map Briefing panel
	m_pBriefing = new TextPanel("", 0,0, TEAMMENU_WINDOW_SIZE_X - TEAMMENU_WINDOW_TEXT_X, TEAMMENU_WINDOW_TEXT_SIZE_Y );
	m_pBriefing->setParent( m_pScrollPanel->getClient() );
	m_pBriefing->setFont( pSchemes->getFont(hTeamWindowText) );
	pSchemes->getFgColor( hTeamWindowText, r, g, b, a );
	m_pBriefing->setFgColor( r, g, b, a );
	pSchemes->getBgColor( hTeamWindowText, r, g, b, a );
	m_pBriefing->setBgColor( r, g, b, a );

	m_pBriefing->setText( gHUD.m_TextMessage.BufferedLocaliseTextString("#Map_Description_not_available") );
	
	// Team Menu buttons
	for (int i = 1; i <= 5; i++)
	{
		char sz[256]; 

		int iYPos = TEAMMENU_TOPLEFT_BUTTON_Y + ( (TEAMMENU_BUTTON_SIZE_Y + TEAMMENU_BUTTON_SPACER_Y) * i );

		// Team button
		m_pButtons[i] = new CommandButton( "", TEAMMENU_TOPLEFT_BUTTON_X, iYPos, TEAMMENU_BUTTON_SIZE_X, TEAMMENU_BUTTON_SIZE_Y, true);
		m_pButtons[i]->setParent( this );
		m_pButtons[i]->setContentAlignment( vgui::Label::a_west );
		m_pButtons[i]->setVisible( false );

		// AutoAssign button uses special case
		if (i == 5)
		{
			m_pButtons[5]->setBoundKey( '5' );
			m_pButtons[5]->setText( gHUD.m_TextMessage.BufferedLocaliseTextString("#Team_AutoAssign") );
			m_pButtons[5]->setVisible( true );
		}

		// Create the Signals
		sprintf(sz, "jointeam %d", i);
		m_pButtons[i]->addActionSignal( new CMenuHandler_StringCommandWatch( sz, true ) );
		m_pButtons[i]->addInputSignal( new CHandler_MenuButtonOver(this, i) );

		// Create the Team Info panel
		m_pTeamInfoPanel[i] = new TextPanel("", TEAMMENU_WINDOW_INFO_X, TEAMMENU_WINDOW_INFO_Y, TEAMMENU_WINDOW_SIZE_X - TEAMMENU_WINDOW_INFO_X, TEAMMENU_WINDOW_SIZE_X - TEAMMENU_WINDOW_INFO_Y );
		m_pTeamInfoPanel[i]->setParent( m_pTeamWindow );
		m_pTeamInfoPanel[i]->setFont( pSchemes->getFont(hTeamInfoText) );
		m_pTeamInfoPanel[i]->setFgColor(	iTeamColors[i % iNumberOfTeamColors][0],
											iTeamColors[i % iNumberOfTeamColors][1],
											iTeamColors[i % iNumberOfTeamColors][2],
											0 );
		m_pTeamInfoPanel[i]->setBgColor( 0,0,0, 255 );
	}

	// Create the Cancel button
	m_pCancelButton = new CommandButton( CHudTextMessage::BufferedLocaliseTextString( "#Menu_Cancel" ), TEAMMENU_TOPLEFT_BUTTON_X, 0, TEAMMENU_BUTTON_SIZE_X, TEAMMENU_BUTTON_SIZE_Y);
	m_pCancelButton->setParent( this );
	m_pCancelButton->addActionSignal( new CMenuHandler_TextWindow(HIDE_TEXTWINDOW) );

	// Create the Spectate button
	m_pSpectateButton = new SpectateButton( CHudTextMessage::BufferedLocaliseTextString( "#Menu_Spectate" ), TEAMMENU_TOPLEFT_BUTTON_X, 0, TEAMMENU_BUTTON_SIZE_X, TEAMMENU_BUTTON_SIZE_Y, true);
	m_pSpectateButton->setParent( this );
	m_pSpectateButton->addActionSignal( new CMenuHandler_StringCommand( "spectate", true ) );
	m_pSpectateButton->setBoundKey( '6' );
	m_pSpectateButton->addInputSignal( new CHandler_MenuButtonOver(this, 6) );

	Initialize();
}
BEGIN_JUCE_NAMESPACE

#include "juce_FileBrowserComponent.h"
#include "../lookandfeel/juce_LookAndFeel.h"
#include "../../graphics/drawables/juce_DrawablePath.h"
#include "../../../text/juce_LocalisedStrings.h"
#include "../../../core/juce_SystemStats.h"
#include "juce_FileListComponent.h"
#include "juce_FileTreeComponent.h"


//==============================================================================
FileBrowserComponent::FileBrowserComponent (int flags_,
                                            const File& initialFileOrDirectory,
                                            const FileFilter* fileFilter_,
                                            FilePreviewComponent* previewComp_)
   : FileFilter (String::empty),
     fileFilter (fileFilter_),
     flags (flags_),
     previewComp (previewComp_),
     thread ("Juce FileBrowser")
{
    // You need to specify one or other of the open/save flags..
    jassert ((flags & (saveMode | openMode)) != 0);
    jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));

    // You need to specify at least one of these flags..
    jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);

    String filename;

    if (initialFileOrDirectory == File::nonexistent)
    {
        currentRoot = File::getCurrentWorkingDirectory();
    }
    else if (initialFileOrDirectory.isDirectory())
    {
        currentRoot = initialFileOrDirectory;
    }
    else
    {
        chosenFiles.add (new File (initialFileOrDirectory));
        currentRoot = initialFileOrDirectory.getParentDirectory();
        filename = initialFileOrDirectory.getFileName();
    }

    fileList = new DirectoryContentsList (this, thread);

    if ((flags & useTreeView) != 0)
    {
        FileTreeComponent* const tree = new FileTreeComponent (*fileList);

        if ((flags & canSelectMultipleItems) != 0)
            tree->setMultiSelectEnabled (true);

        addAndMakeVisible (tree);
        fileListComponent = tree;
    }
    else
    {
        FileListComponent* const list = new FileListComponent (*fileList);
        list->setOutlineThickness (1);

        if ((flags & canSelectMultipleItems) != 0)
            list->setMultipleSelectionEnabled (true);

        addAndMakeVisible (list);
        fileListComponent = list;
    }

    fileListComponent->addListener (this);

    addAndMakeVisible (currentPathBox = new ComboBox ("path"));
    currentPathBox->setEditableText (true);

    StringArray rootNames, rootPaths;
    const BitArray separators (getRoots (rootNames, rootPaths));

    for (int i = 0; i < rootNames.size(); ++i)
    {
        if (separators [i])
            currentPathBox->addSeparator();

        currentPathBox->addItem (rootNames[i], i + 1);
    }

    currentPathBox->addSeparator();
    currentPathBox->addListener (this);

    addAndMakeVisible (filenameBox = new TextEditor());
    filenameBox->setMultiLine (false);
    filenameBox->setSelectAllWhenFocused (true);
    filenameBox->setText (filename, false);

    filenameBox->addListener (this);
    filenameBox->setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);

    Label* label = new Label ("f", TRANS("file:"));
    addAndMakeVisible (label);
    label->attachToComponent (filenameBox, true);

    addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());

    goUpButton->addButtonListener (this);
    goUpButton->setTooltip (TRANS ("go up to parent directory"));

    if (previewComp != 0)
        addAndMakeVisible (previewComp);

    setRoot (currentRoot);

    thread.startThread (4);
}
Ejemplo n.º 27
0
bool
CodeGeneratorX64::visitAsmJSStoreHeap(LAsmJSStoreHeap *ins)
{
    MAsmJSStoreHeap *mir = ins->mir();
    AsmJSHeapAccess::ViewType vt = mir->viewType();
    const LAllocation *ptr = ins->ptr();
    Operand dstAddr(HeapReg);

    if (ptr->isConstant()) {
        int32_t ptrImm = ptr->toConstant()->toInt32();
        MOZ_ASSERT(ptrImm >= 0);
        dstAddr = Operand(HeapReg, ptrImm);
    } else {
        dstAddr = Operand(HeapReg, ToRegister(ptr), TimesOne);
    }

    memoryBarrier(ins->mir()->barrierBefore());
    Label rejoin;
    uint32_t maybeCmpOffset = AsmJSHeapAccess::NoLengthCheck;
    if (mir->needsBoundsCheck()) {
        CodeOffsetLabel cmp = masm.cmplWithPatch(ToRegister(ptr), Imm32(0));
        masm.j(Assembler::AboveOrEqual, &rejoin);
        maybeCmpOffset = cmp.offset();
    }

    uint32_t before = masm.size();
    if (ins->value()->isConstant()) {
        switch (vt) {
          case AsmJSHeapAccess::Int8:
          case AsmJSHeapAccess::Uint8:        masm.movb(Imm32(ToInt32(ins->value())), dstAddr); break;
          case AsmJSHeapAccess::Int16:
          case AsmJSHeapAccess::Uint16:       masm.movw(Imm32(ToInt32(ins->value())), dstAddr); break;
          case AsmJSHeapAccess::Int32:
          case AsmJSHeapAccess::Uint32:       masm.movl(Imm32(ToInt32(ins->value())), dstAddr); break;
          case AsmJSHeapAccess::Float32:
          case AsmJSHeapAccess::Float64:
          case AsmJSHeapAccess::Float32x4:
          case AsmJSHeapAccess::Int32x4:
          case AsmJSHeapAccess::Uint8Clamped: MOZ_CRASH("unexpected array type");
        }
    } else {
        switch (vt) {
          case AsmJSHeapAccess::Int8:
          case AsmJSHeapAccess::Uint8:        masm.movb(ToRegister(ins->value()), dstAddr); break;
          case AsmJSHeapAccess::Int16:
          case AsmJSHeapAccess::Uint16:       masm.movw(ToRegister(ins->value()), dstAddr); break;
          case AsmJSHeapAccess::Int32:
          case AsmJSHeapAccess::Uint32:       masm.movl(ToRegister(ins->value()), dstAddr); break;
          case AsmJSHeapAccess::Float32:      masm.storeFloat32(ToFloatRegister(ins->value()), dstAddr); break;
          case AsmJSHeapAccess::Float64:      masm.storeDouble(ToFloatRegister(ins->value()), dstAddr); break;
          case AsmJSHeapAccess::Float32x4:    masm.storeUnalignedFloat32x4(ToFloatRegister(ins->value()), dstAddr); break;
          case AsmJSHeapAccess::Int32x4:      masm.storeUnalignedInt32x4(ToFloatRegister(ins->value()), dstAddr); break;
          case AsmJSHeapAccess::Uint8Clamped: MOZ_CRASH("unexpected array type");
        }
    }
    uint32_t after = masm.size();
    if (rejoin.used())
        masm.bind(&rejoin);
    memoryBarrier(ins->mir()->barrierAfter());
    masm.append(AsmJSHeapAccess(before, after, vt, maybeCmpOffset));
    return true;
}
Ejemplo n.º 28
0
void TextSample::controlEvent(Control* control, EventType evt)
{
    const char* id = control->getId();

    if (strcmp(id, "fontButton") == 0)
    {
        _fontIndex++;
        if (_fontIndex >= _fontsCount)
        {
            _fontIndex = 0;
        }
        _font = _fonts[_fontIndex];
        std::string s = "Font (" + _fontNames[_fontIndex] + ")";
        static_cast<Button*>(control)->setText(s.c_str());
    }
    else if (strcmp(id, "wrapButton") == 0)
    {
        _wrap = !_wrap;
        Button* wrapButton = static_cast<Button*>(control);
        if (_wrap)
            wrapButton->setText("Word Wrap (On)");
        else
            wrapButton->setText("Word Wrap (Off)");
    }
    else if (strcmp(id, "clipRectButton") == 0)
    {
        _ignoreClip = !_ignoreClip;
        Button* clipRectButton = static_cast<Button*>(control);
        if (_ignoreClip)
            clipRectButton->setText("Clipping (Off)");
        else
            clipRectButton->setText("Clipping (On)");
    }
    else if (strcmp(id, "reverseButton") == 0)
    {
        _rightToLeft = !_rightToLeft;
        Button* reverseButton = static_cast<Button*>(control);
        if (_rightToLeft)
            reverseButton->setText("Reverse Text (On)");
        else
            reverseButton->setText("Reverse Text (Off)");
    }
    else if (strcmp(id, "switchClipRegionButton") == 0)
    {
        _useViewport = !_useViewport;
        Button* switchClipButton = static_cast<Button*>(control);
        if (_useViewport)
            switchClipButton->setText("Clip Regions (Viewport)");
        else
            switchClipButton->setText("Clip Regions (Text Area)");
    }
    else if (strcmp(id, "simpleAdvancedButton") == 0)
    {
        _simple = !_simple;
        Button* simpleAdvancedButton = static_cast<Button*>(control);
        if (_simple)
            simpleAdvancedButton->setText("Font API (Simple)");
        else
            simpleAdvancedButton->setText("Font API (Advanced)");
    }
    else if (strcmp(id, "smallerButton") == 0)
    {
        if (_size > 8)
        {
            _size -= 2;
            Label* sizeLabel = static_cast<Label*>(_form->getControl("sizeLabel"));
            char s[20];
            sprintf(s, "Size (%u)", _size);
            sizeLabel->setText(s);
        }
    }
    else if (strcmp(id, "biggerButton") == 0)
    {
        _size += 2;
        Label* sizeLabel = static_cast<Label*>(_form->getControl("sizeLabel"));
        char s[20];
        sprintf(s, "Size (%u)", _size);
        sizeLabel->setText(s);
    }
    else if (strcmp(id, "topLeftButton") == 0)
    {
        _alignment = Font::ALIGN_TOP_LEFT;
        Label* alignmentLabel = static_cast<Label*>(_form->getControl("alignmentLabel"));
        alignmentLabel->setText("Align (Top-Left)");
    }
    else if (strcmp(id, "topCenterButton") == 0)
    {
        _alignment = Font::ALIGN_TOP_HCENTER;
        Label* alignmentLabel = static_cast<Label*>(_form->getControl("alignmentLabel"));
        alignmentLabel->setText("Align (Top-Center)");
    }
    else if (strcmp(id, "topRightButton") == 0)
    {
        _alignment = Font::ALIGN_TOP_RIGHT;
        Label* alignmentLabel = static_cast<Label*>(_form->getControl("alignmentLabel"));
        alignmentLabel->setText("Align (Top-Right)");
    }
    else if (strcmp(id, "centerLeftButton") == 0)
    {
        _alignment = Font::ALIGN_VCENTER_LEFT;
        Label* alignmentLabel = static_cast<Label*>(_form->getControl("alignmentLabel"));
        alignmentLabel->setText("Align (Center-Left)");
    }
    else if (strcmp(id, "centerButton") == 0)
    {
        _alignment = Font::ALIGN_VCENTER_HCENTER;
        Label* alignmentLabel = static_cast<Label*>(_form->getControl("alignmentLabel"));
        alignmentLabel->setText("Align (Center)");
    }
    else if (strcmp(id, "centerRightButton") == 0)
    {
        _alignment = Font::ALIGN_VCENTER_RIGHT;
        Label* alignmentLabel = static_cast<Label*>(_form->getControl("alignmentLabel"));
        alignmentLabel->setText("Align (Center-Right)");
    }
    else if (strcmp(id, "bottomLeftButton") == 0)
    {
        _alignment = Font::ALIGN_BOTTOM_LEFT;
        Label* alignmentLabel = static_cast<Label*>(_form->getControl("alignmentLabel"));
        alignmentLabel->setText("Align (Bottom-Left)");
    }
    else if (strcmp(id, "bottomCenterButton") == 0)
    {
        _alignment = Font::ALIGN_BOTTOM_HCENTER;
        Label* alignmentLabel = static_cast<Label*>(_form->getControl("alignmentLabel"));
        alignmentLabel->setText("Align (Bottom-Center)");
    }
    else if (strcmp(id, "bottomRightButton") == 0)
    {
        _alignment = Font::ALIGN_BOTTOM_RIGHT;
        Label* alignmentLabel = static_cast<Label*>(_form->getControl("alignmentLabel"));
        alignmentLabel->setText("Align (Bottom-Right)");
    }
}
TextueelScherm::TextueelScherm( WeerData* weerData )
{
	//bepaal grootte van het scherm
	MAExtent screenSize = maGetScrSize();
	int screenWidth = EXTENT_X( screenSize );
	int screenHeight = EXTENT_Y( screenSize );

	//sla de weerdata op in het attribuut
	this->weerData = weerData;

	//ken font en skin toe
	this->font = new MAUI::Font(RES_FONT);
	this->skin = new WidgetSkin( RES_SELECTED, RES_UNSELECTED, 16, 32, 16, 32, false, false );

	//maak een achtergrond label om alle andere widgets in op te slaan, en te tonen
	Label* achtergrond =  new Label(0,0,0,0,NULL);
	achtergrond->setBackgroundColor(0x000000);

	//maak een listbox waar update en visueelknop aan toegevoegd worden
//	this->listBox = new Label ( screenWidth/2-50, 250, 80, 30, achtergrond, "ListBox", 0, font );
//	this->listBox->setSkin( this->skin );
//	this->listBox->setPaddingLeft(5);
//	this->listBox->setPaddingTop(5);

	//knop om data te updaten
	this->updateKnop = new Label ( screenWidth/2-50, 350, 80, 30, achtergrond, "Update", 0, font );
	this->updateKnop->setSkin( this->skin );
	this->updateKnop->setPaddingLeft(5);
	this->updateKnop->setPaddingTop(5);

	//knop om naar visueel scherm te schakelen
	this->visueelKnop = new Label ( screenWidth/2-50, 385, 80, 30, achtergrond, "Visueel", 0, font );
	this->visueelKnop->setSkin( this->skin );
	this->visueelKnop->setPaddingLeft(5);
	this->visueelKnop->setPaddingTop(5);



	//label veld voor weer data, beslaat de rest van het scherm (zie onder)
	this->weerDataLabel = new Label (5, 5, screenWidth-10, screenHeight/2+60, achtergrond, "Weersvoorwachting komende dagen", 0, font);
	weerDataLabel->setBackgroundColor(0x666666);


	//info label
	this->weerInfo = new Label (10, 50, 220, 30, achtergrond, "Verwacht: vand., mrgn., overmrgn", 0, font);

	//zonneschijn label
	this->weerInfoZon = new Label (10, 90, 220, 30, achtergrond, "", 0, font);

	//neerslag label
	this->weerInfoNeerslag = new Label (10, 130, 220, 30, achtergrond, "", 0, font);

	//minimum temperatuur label
	this->weerInfoMintemp = new Label (10, 170, 220, 30, achtergrond, "", 0, font);

	//update labels met text, etc.
	this->update();

	//stel achtergrond label in als main widget, en maakt alles zichtbaar
	this->setMain(achtergrond);
}
Ejemplo n.º 30
0
void DialogNode::setLabTitleText(std::string text)
{
	Label *labTitle = (Label*)this->getChildByTag((int)ChildTag::LAB_TITLE);
	labTitle->setString(text);
}