Esempio n. 1
0
		public override View GetPropertyWindowLayout (Android.Content.Context context)
		{
			gridlayout = new GridLayout (context); 
			gridlayout.RowCount = 2;
			gridlayout.ColumnCount = 2;

			conditionTextView = new TextView (context);
			conditionTextView.Text = "Select the Condition to filter";
			columnTextView = new TextView (context);
			columnTextView.Text = "Select the Column to filter";
			columnDropdown = new Spinner(context);
			var columnAdapter = ArrayAdapter.CreateFromResource (context, Resource.Array.column_array, Android.Resource.Layout.SimpleSpinnerItem);
			columnAdapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem);
			columnDropdown.Adapter = columnAdapter;
			conditionDropdown = new Spinner (context);
			condtionAdapter = new ArrayAdapter (context, Android.Resource.Layout.SimpleSpinnerItem);
			condtionAdapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem);
			conditionDropdown.Adapter = condtionAdapter;
			columnDropdown.ItemSelected += new EventHandler<AdapterView.ItemSelectedEventArgs> (OnColumnSelected);
			conditionDropdown.ItemSelected += OnConditionSelected;
			gridlayout.LayoutParameters = new LinearLayout.LayoutParams (LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.WrapContent);
			gridlayout.AddView (columnTextView);
			gridlayout.AddView (columnDropdown);
			gridlayout.AddView (conditionTextView);
			gridlayout.AddView (conditionDropdown);
			return gridlayout;
		}
Esempio n. 2
0
 public PauseMenu(Background bg) : base(bg, "dialog_small")
 {
     var ui = new GridLayout(new Rectangle(Point.Zero, Size.ToPoint()), 4)
     {
         Scale = SkidiBirdGame.Scale,
         Rows =
         {
             new Row(32)
             {
                 new HColumn(1f)
                 {
                     VerticalAlign = VerticalAlign.Top,
                     Items = { Label.FromResource("Pause")}
                 }
             },
             new Row(-1)
             {
                 new HColumn(1f)
                 {
                     Spacing = 12,
                     Items =
                     {
                         new Buttons.SmallButton("ic_play", ReturnClick),
                         new Buttons.SmallButton("ic_restart", RestartClick),
                         new Buttons.SmallButton("ic_exit", ExitClick)
                     }
                 }
             }
         }
     };
     Add(ui);
 }
Esempio n. 3
0
		public MonoGameGuiManager CreateGui( )
		{
			
			var textureAtlas = new TextureAtlas("Atlas1");
            var upRegion = textureAtlas.AddRegion("cog", 48, 0, 47, 47);
            var cogRegion = textureAtlas.AddRegion("up", 0, 0, 47, 47);

			_gui = new MonoGameGuiManager(_game.GraphicsDevice, _game.Content);
            _gui.LoadContent(new GuiContent(textureAtlas, "ExampleFont.fnt", "ExampleFont_0"));
			
			var screen = new Screen(800, 480);
			var dockLayout = new DockLayout();
			var gridLayout = new GridLayout(1, 2);
			var leftStackLayout = new StackLayout() { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Bottom };
			var loadRubeFileBtn = CreateButton(cogRegion);
			var dumpRubeFileBtn = CreateButton(upRegion);
						
			dockLayout.Items.Add(new DockItem(gridLayout, DockStyle.Bottom));

            dumpRubeFileBtn.Tag = "dump";
			loadRubeFileBtn.Tag = "load";
			leftStackLayout.Items.Add(loadRubeFileBtn);
			leftStackLayout.Items.Add(dumpRubeFileBtn);
			
			gridLayout.Items.Add(new GridItem(leftStackLayout, 0, 0));
			
			
			screen.Items.Add(dockLayout);
			_gui.Screen = screen;

			return _gui;
		}
Esempio n. 4
0
 /// <summary>
 /// This override replaces the default <see cref="Diagram.Layout"/> with a <see cref="GridLayout"/>
 /// that executes under <see cref="DiagramLayout.Conditions"/> that include <see cref="LayoutChange.ViewportSizeChanged"/>.
 /// </summary>
 public override void OnApplyTemplate() {
   // use a different default Layout than what the Diagram constructor might set
   if (this.Layout == null || this.Layout.GetType() == typeof(Northwoods.GoXam.Layout.DiagramLayout)) {
     var layout = new GridLayout();
     layout.Conditions = LayoutChange.Standard | LayoutChange.ViewportSizeChanged;
     this.Layout = layout;
   } else {
     DiagramLayout layout = this.Layout as DiagramLayout;
     if (layout != null) {
       layout.Conditions |= LayoutChange.ViewportSizeChanged;
     }
   }
   base.OnApplyTemplate();
 }
Esempio n. 5
0
		protected override void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);

			SetContentView(Resource.Layout.Main);
			_grid = FindViewById<GridLayout>(Resource.Id.gridLayout);
			_currentScore = FindViewById<TextView>(Resource.Id.currentScore);
			_highScoreTv = FindViewById<TextView>(Resource.Id.highScore);
			_gameButton = FindViewById<Button>(Resource.Id.gameButton);
			_gameButton.Click += NewGameClick;
			_size = 8;

			NewGame(_size);
		}
Esempio n. 6
0
 public void AddGrassView(Grass grass, GridLayout gridLayout)
 {
     GameObject instance;
     if (grassPool.transform.childCount > 0)
         instance = grassPool.transform.GetChild(0).gameObject;
     else
         instance = Object.Instantiate(grassPrototype) as GameObject;
     Random.seed = (grass.row * 7457) ^ (grass.column * 89);
     var grassTransform = instance.transform.GetChild(0).transform;
     grassTransform.localRotation =
         Quaternion.Euler(0f, 180f, Random.Range(0f, 360f) + grass.row * 97);
     var grassSize = Mathf.Clamp(grass.age * 0.2f, 0, 1);
     grassTransform.localScale = new Vector3(grassSize, grassSize, grassSize);
     gridLayout.AddItem(grass.row, grass.column, 0, instance, grassPool);
 }
		Control createControl(Composite parent) {
			PixelConverter converter = new PixelConverter(parent);
			
			var composite = new Composite(parent, SWT.NONE);
			composite.setFont(parent.getFont());
			
			var layout = new GridLayout();
			layout.numColumns = 2;
			composite.setLayout(layout);

			//
			// Label
			//
			var label = new Label(composite, SWT.LEFT | SWT.WRAP);
			label.setFont(composite.getFont());
			label.setText(Messages.librariesPreferencesLabelText);
	
			var gd = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
			gd.horizontalSpan = 2;
			gd.verticalAlignment = GridData.BEGINNING;
			label.setLayoutData(gd);

			//
			// Table
			//
			var tableComposite = new Composite(composite, SWT.NONE);
			tableComposite.setFont(composite.getFont());
			var tableColumnLayout = new TableColumnLayout();
			tableComposite.setLayout(tableColumnLayout);
			
			var table = new Table(tableComposite, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CHECK);
			table.setFont(composite.getFont());
			table.setHeaderVisible(false);
			table.setLinesVisible(false);
			var column = new TableColumn(table, SWT.NONE);
			tableColumnLayout.setColumnData(column, new ColumnWeightData(100, false));
	
			// Table viewer
			tableViewer = new CheckboxTableViewer(table);
			tableViewer.setContentProvider(tableContentProvider);
			tableViewer.setCheckStateProvider(tableCheckStateProvider);
			tableViewer.setLabelProvider(tableLabelProvider);
			tableViewer.addCheckStateListener(tableCheckStateListener);
			tableViewer.addSelectionChangedListener(event => {
Esempio n. 8
0
		protected override void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);

			// Create your application here
			GridLayout layout = new GridLayout(this);
			layout.ColumnCount = 1;
			layout.RowCount = 5;

			createButton = new Button(this);
			createButton.Text = "Create Bucket";
			createButton.Click += createButton_Click;
			layout.AddView(createButton);

			uploadButton = new Button(this);
			uploadButton.Text = "Upload Image";
			uploadButton.Click += uploadButton_Click;
			uploadButton.Enabled = false;
			layout.AddView(uploadButton);

			deleteButton = new Button(this);
			deleteButton.Text = "Delete Bucket";
			deleteButton.Click += deleteButton_Click;
			deleteButton.Enabled = false;
			layout.AddView(deleteButton);

			statusText = new TextView(this);
			layout.AddView(statusText);

			progressBar = new ProgressBar(this);
			progressBar.Visibility = ViewStates.Invisible;

			layout.AddView(progressBar);

			SetContentView(layout);
		}
Esempio n. 9
0
		protected override void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);

			// Create your application here
			GridLayout layout = new GridLayout(this);
			layout.ColumnCount = 1;
			layout.RowCount = 5;

			createTopic = new Button(this);
			createTopic.Text = "Create Topic";
			createTopic.Click += createTopic_Click;
			layout.AddView(createTopic);

			emailText = new EditText(this);
			emailText.Text = "";
			layout.AddView(emailText);

			subscribe = new Button(this);
			subscribe.Enabled = false;
			subscribe.Text = "Subscribe to Topic";
			subscribe.Click += subscribe_Click;
			layout.AddView(subscribe);

			deleteTopic = new Button(this);
			deleteTopic.Click += deleteTopic_Click;
			deleteTopic.Enabled = false;
			deleteTopic.Text = "Delete Topic";
			layout.AddView(deleteTopic);

			statusText = new TextView(this);
			layout.AddView(statusText);


			SetContentView(layout);
		}
Esempio n. 10
0
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            _spriteBatch = new SpriteBatch(GraphicsDevice);

            var textureAtlas = new TextureAtlas("ExampleAtlas2.png");
            var playRegion = textureAtlas.AddRegion("play", 0, 0, 128, 128);
            var upRegion = textureAtlas.AddRegion("up", 128, 0, 64, 64);
            var cogRegion = textureAtlas.AddRegion("cog", 128, 64, 64, 64);
            var twitterRegion = textureAtlas.AddRegion("twitter", 417, 1, 62, 62);
            var facebookRegion = textureAtlas.AddRegion("facebook", 353, 1, 62, 62);
            var titleRegion = textureAtlas.AddRegion("title", 0, 435, 448, 77);

            //var tickRegion = textureAtlas.AddRegion("tick", 192, 0, 64, 64);
            //var crossRegion = textureAtlas.AddRegion("cross", 192, 64, 64, 64);
            //var pauseRegion = textureAtlas.AddRegion("pause", 256, 0, 64, 64);
            //var resetRegion = textureAtlas.AddRegion("reset", 256, 64, 64, 64);
            //var boxRegion = textureAtlas.AddRegion("box", 496, 0, 16, 16);
            //var redRegion = textureAtlas.AddRegion("red", 0, 164, 128, 111);
            //var blueRegion = textureAtlas.AddRegion("blue", 0, 276, 128, 111);
            //var squareRegion = textureAtlas.AddRegion("square", 128, 164, 128, 128);
            //var greenSquareRegion = textureAtlas.AddRegion("greenSquare", 256, 164, 128, 128);

            _gui = new MonoGameGuiManager(GraphicsDevice, Content);
            _gui.LoadContent(new GuiContent(textureAtlas, "ExampleFont.fnt", "ExampleFont_0.png"));
            var backgroundRegion = _gui.LoadTexture("Background.png");

            var screen = new Screen(800, 480);
            var dockLayout = new DockLayout();
            var gridLayout = new GridLayout(1, 2);
            var leftStackLayout = new StackLayout() { Orientation = Orientation.Horizontal, VerticalAlignment = VerticalAlignment.Bottom };
            var rightStackLaout = new StackLayout() { Orientation = Orientation.Vertical, HorizontalAlignment = HorizontalAlignment.Right };
            var playButton = CreateButton(playRegion);
            var cogButton = CreateButton(cogRegion);
            var upButton = CreateButton(upRegion);
            var facebookButton = new Button(new VisualStyle(twitterRegion)) { HoverStyle = new VisualStyle(twitterRegion) { Rotation = 0.05f } };
            var twitterButton = new Button(new VisualStyle(facebookRegion)) { HoverStyle = new VisualStyle(facebookRegion) { Rotation = 0.05f } };
            var titleImage = new Image(new VisualStyle(titleRegion)) { Margin = new Margin(0, 50, 0, 0) };

            _timeLabel = new Label() { Height = 32 };

            screen.Background = new VisualStyle(backgroundRegion);

            dockLayout.Items.Add(new DockItem(playButton, DockStyle.Fill));
            dockLayout.Items.Add(new DockItem(gridLayout, DockStyle.Bottom));
            dockLayout.Items.Add(new DockItem(_timeLabel, DockStyle.Top));
            dockLayout.Items.Add(new DockItem(titleImage, DockStyle.Top));

            leftStackLayout.Items.Add(cogButton);
            leftStackLayout.Items.Add(upButton);

            rightStackLaout.Items.Add(facebookButton);
            rightStackLaout.Items.Add(twitterButton);

            gridLayout.Items.Add(new GridItem(leftStackLayout, 0, 0));
            gridLayout.Items.Add(new GridItem(rightStackLaout, 0, 1));

            screen.Items.Add(dockLayout);

            _gui.Screen = screen;

            facebookButton.Clicked += (object sender, EventArgs e) => Process.Start("https://www.facebook.com/CraftworkGames");
            twitterButton.Clicked += (object sender, EventArgs e) => Process.Start("https://twitter.com/craftworkgames");
        }
Esempio n. 11
0
        public ActivityNameEntryBox(string title, ActivityDatabase activityDatabase, LayoutStack layoutStack, bool createNewActivity = false, bool placeTitleAbove = true)
        {
            // some settings
            this.layoutStack               = layoutStack;
            this.AutoAcceptAutocomplete    = true;
            this.createNewActivity         = createNewActivity;
            this.activityDatabase          = activityDatabase;
            this.numAutocompleteRowsToShow = 1;

            // the box the user is typing in
            this.nameBox              = new Editor();
            this.nameBox.TextChanged += NameBox_TextChanged;
            this.nameBox_layout       = new TextboxLayout(this.nameBox);

            // "X"/"?" button for clearing text or getting help
            // We use one button for both purposes so that the layout doesn't relayout (and shift focus) when this button switches from one to the other
            this.sideButton          = new Button();
            this.sideButton.Clicked += SideButton_Clicked;
            this.sideButtonLayout    = new ButtonLayout(this.sideButton);

            // layouts controlling the alignment of the main text box and the side button
            this.sideLayout           = new ContainerLayout();
            this.sideLayout.SubLayout = this.sideButtonLayout;

            GridView   gridView = new GridView();
            GridLayout evenBox  = GridLayout.New(new BoundProperty_List(1), BoundProperty_List.WithRatios(new List <double>()
            {
                7, 1
            }), LayoutScore.Zero, 1, gridView);
            GridLayout unevenBox = GridLayout.New(new BoundProperty_List(1), new BoundProperty_List(2), LayoutScore.Get_UnCentered_LayoutScore(1), 1, gridView);

            evenBox.AddLayout(this.nameBox_layout);
            evenBox.AddLayout(this.sideLayout);
            unevenBox.AddLayout(this.nameBox_layout);
            unevenBox.AddLayout(this.sideLayout);
            this.nameBoxWithSideLayout = new LayoutUnion(evenBox, unevenBox);

            // the autocomplete above the text box
            this.autocompleteLayout = new TextblockLayout();
            this.autocompleteLayout.ScoreIfEmpty = false;

            // button that gives help with autocomplete
            this.helpWindow = new HelpWindowBuilder()
                              .AddMessage("This screen explains how to enter " + title + " in the previous screen. " +
                                          "If you haven't already created the activity that you want to enter here, you will have to go back and create it first in the Activities screen.")
                              .AddMessage("")
                              .AddMessage("To input an activity name, you may type it in using the letters on the keyboard.")
                              .AddMessage("While you do this, ActivityRecommender will try to guess which activity you mean, and " +
                                          "that autocomplete guess will appear above. If this autocomplete suggestion is what you want, then you can press " +
                                          "[enter] to use the autocomplete suggestion.")
                              .AddMessage("Autocomplete does not require you to type full words but it does require spaces between words.")
                              .AddMessage("Autocomplete does not require that you type letters using the correct case but it is more effective if you do.")
                              .AddMessage("Consider the following example:")
                              .AddMessage("If you have already entered an activity named \"Taking out the Garbage\", " +
                                          "here are some things you can type that might cause it to become the autocomplete suggestion:")
                              .AddMessage("Taking out the")
                              .AddMessage("Taking")
                              .AddMessage("out")
                              .AddMessage("Garbage")
                              .AddMessage("garbage")
                              .AddMessage("Taking o t G")
                              .AddMessage("T o t G")
                              .AddMessage("T")
                              .AddMessage("G")
                              .AddMessage("t")
                              .AddMessage("")
                              .AddMessage("Note, of course, that the longer and more unique your text, the more likely that it will be matched with the activity that you intend, rather than " +
                                          "with another activity, like for example, 'Talking on the Phone'")
                              .AddLayout(new CreditsButtonBuilder(layoutStack)
                                         .AddContribution(ActRecContributor.ANNI_ZHANG, new DateTime(2020, 6, 7), "Pointed out that completed ToDos should have a very low autocomplete priority")
                                         .Build()
                                         )
                              .Build();

            // help buttons that appear when the user types something invalid
            Button help_createNew_button = new Button();

            help_createNew_button.Clicked   += help_createNew_button_Clicked;
            this.autocomplete_longHelpLayout = new Horizontal_GridLayout_Builder().Uniform()
                                               .AddLayout(new ButtonLayout(help_createNew_button, "Create"))
                                               .AddLayout(new HelpButtonLayout(this.helpWindow, layoutStack))
                                               .Build();

            // the main layout that contains everything
            LayoutChoice_Set content;

            if (createNewActivity)
            {
                content = unevenBox;
            }
            else
            {
                GridLayout contentWithFeedback = GridLayout.New(new BoundProperty_List(2), new BoundProperty_List(1), LayoutScore.Get_UnCentered_LayoutScore(1));
                contentWithFeedback.AddLayout(this.responseLayout);
                contentWithFeedback.AddLayout(this.nameBoxWithSideLayout);

                content = contentWithFeedback;

                this.UpdateFeedback();
            }

            this.updateSideButton();

            TextblockLayout titleLayout = new TextblockLayout(title);

            titleLayout.AlignHorizontally(TextAlignment.Center);
            if (placeTitleAbove)
            {
                this.SubLayout = new Vertical_GridLayout_Builder()
                                 .AddLayout(titleLayout)
                                 .AddLayout(content)
                                 .Build();
            }
            else
            {
                GridLayout evenGrid   = GridLayout.New(new BoundProperty_List(1), BoundProperty_List.Uniform(2), LayoutScore.Zero);
                GridLayout unevenGrid = GridLayout.New(new BoundProperty_List(1), new BoundProperty_List(2), LayoutScore.Get_UnCentered_LayoutScore(1));
                evenGrid.AddLayout(titleLayout);
                unevenGrid.AddLayout(titleLayout);
                evenGrid.AddLayout(content);
                unevenGrid.AddLayout(content);
                this.SubLayout = new LayoutUnion(evenGrid, unevenGrid);
            }
        }
Esempio n. 12
0
 public void ShowIslandOnGrid(Island island, GridLayout gridLayout, MeshFilter meshFilter)
 {
     gridLayout.size = islandsSize;
     gridLayout.Clear();
     meshFilter.transform.localScale = Vector3.one;
     meshFilter.mesh = IslandBuilder.Build(island);
     foreach (var animal in island.animals) {
         var pool = animal.type == AnimalType.Sheep ? sheepPool : humanPool;
         GameObject instance;
         if (pool.transform.childCount > 0) {
             instance = pool.transform.GetChild(0).gameObject;
         } else {
             var prototype = animal.type == AnimalType.Sheep ? sheepPrototype : humanPrototype;
             instance = Object.Instantiate(prototype) as GameObject;
         }
         var animalView = instance.GetComponent<AnimalView>();
         animalView.gridLayout = gridLayout;
         animalView.animal = animal;
         gridLayout.AddItem(animal.row, animal.column, 0, instance, pool);
     }
     foreach (var harbor in island.harbors) {
         GameObject instance;
         if (harborPool.transform.childCount > 0)
             instance = harborPool.transform.GetChild(0).gameObject;
         else
             instance = Object.Instantiate(harborPrototype) as GameObject;
         gridLayout.AddItem(harbor.row, harbor.column, 0, instance, harborPool);
     }
     foreach (var grass in island.grasses)
         AddGrassView(grass, gridLayout);
 }
        public static Mesh GenerateCachedGridMesh(GridLayout gridLayout, Color color, float screenPixelSize, RectInt bounds, MeshTopology topology)
        {
            Mesh mesh = new Mesh();

            mesh.hideFlags = HideFlags.HideAndDontSave;

            int vertex = 0;

            int totalVertices = topology == MeshTopology.Quads ?
                                8 * (bounds.size.x + bounds.size.y) :
                                4 * (bounds.size.x + bounds.size.y);

            Vector3 horizontalPixelOffset = new Vector3(screenPixelSize, 0f, 0f);
            Vector3 verticalPixelOffset   = new Vector3(0f, screenPixelSize, 0f);

            Vector3[] vertices = new Vector3[totalVertices];
            Vector2[] uvs2     = new Vector2[totalVertices];

            Vector3    cellStride  = gridLayout.cellSize + gridLayout.cellGap;
            Vector3Int minPosition = new Vector3Int(0, bounds.min.y, 0);
            Vector3Int maxPosition = new Vector3Int(0, bounds.max.y, 0);

            Vector3 cellGap = Vector3.zero;

            if (!Mathf.Approximately(cellStride.x, 0f))
            {
                cellGap.x = gridLayout.cellSize.x / cellStride.x;
            }

            for (int x = bounds.min.x; x < bounds.max.x; x++)
            {
                minPosition.x = x;
                maxPosition.x = x;

                vertices[vertex + 0] = gridLayout.CellToLocal(minPosition);
                vertices[vertex + 1] = gridLayout.CellToLocal(maxPosition);
                uvs2[vertex + 0]     = Vector2.zero;
                uvs2[vertex + 1]     = new Vector2(0f, cellStride.y * bounds.size.y);
                if (topology == MeshTopology.Quads)
                {
                    vertices[vertex + 2] = gridLayout.CellToLocal(maxPosition) + horizontalPixelOffset;
                    vertices[vertex + 3] = gridLayout.CellToLocal(minPosition) + horizontalPixelOffset;
                    uvs2[vertex + 2]     = new Vector2(0f, cellStride.y * bounds.size.y);
                    uvs2[vertex + 3]     = Vector2.zero;
                }
                vertex += topology == MeshTopology.Quads ? 4 : 2;

                vertices[vertex + 0] = gridLayout.CellToLocalInterpolated(minPosition + cellGap);
                vertices[vertex + 1] = gridLayout.CellToLocalInterpolated(maxPosition + cellGap);
                uvs2[vertex + 0]     = Vector2.zero;
                uvs2[vertex + 1]     = new Vector2(0f, cellStride.y * bounds.size.y);
                if (topology == MeshTopology.Quads)
                {
                    vertices[vertex + 2] = gridLayout.CellToLocalInterpolated(maxPosition + cellGap) + horizontalPixelOffset;
                    vertices[vertex + 3] = gridLayout.CellToLocalInterpolated(minPosition + cellGap) + horizontalPixelOffset;
                    uvs2[vertex + 2]     = new Vector2(0f, cellStride.y * bounds.size.y);
                    uvs2[vertex + 3]     = Vector2.zero;
                }
                vertex += topology == MeshTopology.Quads ? 4 : 2;
            }

            minPosition = new Vector3Int(bounds.min.x, 0, 0);
            maxPosition = new Vector3Int(bounds.max.x, 0, 0);
            cellGap     = Vector3.zero;
            if (!Mathf.Approximately(cellStride.y, 0f))
            {
                cellGap.y = gridLayout.cellSize.y / cellStride.y;
            }

            for (int y = bounds.min.y; y < bounds.max.y; y++)
            {
                minPosition.y = y;
                maxPosition.y = y;

                vertices[vertex + 0] = gridLayout.CellToLocal(minPosition);
                vertices[vertex + 1] = gridLayout.CellToLocal(maxPosition);
                uvs2[vertex + 0]     = Vector2.zero;
                uvs2[vertex + 1]     = new Vector2(cellStride.x * bounds.size.x, 0f);
                if (topology == MeshTopology.Quads)
                {
                    vertices[vertex + 2] = gridLayout.CellToLocal(maxPosition) + verticalPixelOffset;
                    vertices[vertex + 3] = gridLayout.CellToLocal(minPosition) + verticalPixelOffset;
                    uvs2[vertex + 2]     = new Vector2(cellStride.x * bounds.size.x, 0f);
                    uvs2[vertex + 3]     = Vector2.zero;
                }
                vertex += topology == MeshTopology.Quads ? 4 : 2;

                vertices[vertex + 0] = gridLayout.CellToLocalInterpolated(minPosition + cellGap);
                vertices[vertex + 1] = gridLayout.CellToLocalInterpolated(maxPosition + cellGap);
                uvs2[vertex + 0]     = Vector2.zero;
                uvs2[vertex + 1]     = new Vector2(cellStride.x * bounds.size.x, 0f);
                if (topology == MeshTopology.Quads)
                {
                    vertices[vertex + 2] = gridLayout.CellToLocalInterpolated(maxPosition + cellGap) + verticalPixelOffset;
                    vertices[vertex + 3] = gridLayout.CellToLocalInterpolated(minPosition + cellGap) + verticalPixelOffset;
                    uvs2[vertex + 2]     = new Vector2(cellStride.x * bounds.size.x, 0f);
                    uvs2[vertex + 3]     = Vector2.zero;
                }
                vertex += topology == MeshTopology.Quads ? 4 : 2;
            }

            var uv0     = new Vector2(k_GridGizmoDistanceFalloff, 0f);
            var uvs     = new Vector2[vertex];
            var indices = new int[vertex];
            var colors  = new Color[vertex];

            for (int i = 0; i < vertex; i++)
            {
                uvs[i]     = uv0;
                indices[i] = i;
                colors[i]  = color;
            }

            mesh.vertices = vertices;
            mesh.uv       = uvs;
            mesh.uv2      = uvs2;
            mesh.colors   = colors;
            mesh.SetIndices(indices, topology, 0);

            return(mesh);
        }
Esempio n. 14
0
		public static View Create (Context context)
		{
			GridLayout p = new GridLayout(context);
			p.UseDefaultMargins = true;
			p.AlignmentMode = GridAlign.Bounds;
			Configuration configuration = context.Resources.Configuration;
			if ((configuration.Orientation == Android.Content.Res.Orientation.Portrait)) {
				p.ColumnOrderPreserved = false;
			} else {
				p.RowOrderPreserved = false;
			}

			//FIXME https://bugzilla.xamarin.com/show_bug.cgi?id=14210
			GridLayout.Spec titleRow              = GridLayout.InvokeSpec (0);
			GridLayout.Spec introRow              = GridLayout.InvokeSpec (1);
			GridLayout.Spec emailRow              = GridLayout.InvokeSpec (2, GridLayout.Baseline);
			GridLayout.Spec passwordRow           = GridLayout.InvokeSpec (3, GridLayout.Baseline);
			GridLayout.Spec button1Row            = GridLayout.InvokeSpec (5);
			GridLayout.Spec button2Row            = GridLayout.InvokeSpec (6);

			GridLayout.Spec centerInAllColumns    = GridLayout.InvokeSpec (0, 4, GridLayout.Center);
			GridLayout.Spec leftAlignInAllColumns = GridLayout.InvokeSpec (0, 4, GridLayout.Left);
			GridLayout.Spec labelColumn           = GridLayout.InvokeSpec (0, GridLayout.Right);
			GridLayout.Spec fieldColumn           = GridLayout.InvokeSpec (1, GridLayout.Left);
			GridLayout.Spec defineLastColumn      = GridLayout.InvokeSpec (3);
			GridLayout.Spec fillLastColumn        = GridLayout.InvokeSpec (3, GridLayout.Fill);

			{
				TextView c = new TextView (context);
				c.TextSize = 32;
				c.Text = "Email setup";
				p.AddView (c, new GridLayout.LayoutParams (titleRow, centerInAllColumns));
			}
			{
				TextView c = new TextView (context);
				c.TextSize = 16;
				c.Text = "You can configure email in a few simple steps:";
				p.AddView (c, new GridLayout.LayoutParams (introRow, leftAlignInAllColumns));
			}
			{
				TextView c = new TextView (context);
				c.Text = "Email address:";
				p.AddView (c, new GridLayout.LayoutParams (emailRow, labelColumn));
			}
			{
				EditText c = new EditText (context);
				c.SetEms (10);
				c.InputType = Android.Text.InputTypes.ClassText | Android.Text.InputTypes.TextVariationEmailAddress;
				p.AddView (c, new GridLayout.LayoutParams (emailRow, fieldColumn));
			}
			{
				TextView c = new TextView (context);
				c.Text = "Password:"******"Manual setup";
				p.AddView (c, new GridLayout.LayoutParams (button1Row, defineLastColumn));
			}
			{
				Button c = new Button (context);
				c.Text ="Next";
				p.AddView (c, new GridLayout.LayoutParams (button2Row, fillLastColumn));
			}

			return p;
		}
Esempio n. 15
0
        private static string EditGrid(UrlHelper urlHelper, string pageId, string gridId, string url, GridLayout gridLayout, string submitBtn, string primaryKey, bool hasToolbar, bool needAddEvent, int gridHeight, int gridWidth, bool isMultiSelect, string editFlag, bool hasClickEvent, string clickFlag, bool fixHeight = false, bool isLimit = false)
        {
            string actGridId = gridId + pageId;

            //submitBtn = submitBtn + pageId;
            submitBtn = ProcessSubmitBtn(submitBtn, pageId);
            string        pagerId   = actGridId + "pager";
            string        inputId   = actGridId + AppMember.HideString;
            string        inputName = gridId + AppMember.HideString;
            StringBuilder sbGrid    = new StringBuilder();

            sbGrid.AppendLine("<script type=\"text/javascript\">");
            sbGrid.AppendLine("var onCellEdit" + editFlag + ";");
            sbGrid.AppendLine("var loadGridComplete" + editFlag + ";");
            sbGrid.AppendLine("var lastsel;");
            //sbGrid.AppendLine("var onClickRow = function(id){return id+'qq';}; ");
            sbGrid.AppendLine("$(function(){");
            #region grid设置
            sbGrid.AppendLine("$('#%%GRIDID%%').jqGrid({".Replace("%%GRIDID%%", actGridId));
            sbGrid.AppendFormat("url:'{0}',", url);
            sbGrid.AppendLine("mtype:'post',");
            sbGrid.AppendLine(@"datatype: ""json"",");

            sbGrid.AppendFormat("colNames:[{0}],", GetColNames(gridLayout.GridLayouts));
            sbGrid.AppendFormat("colModel:[{0}],", GetColModel(urlHelper, gridLayout.GridLayouts));

            SetGridProperty(actGridId, gridLayout.GridTitle, pagerId, sbGrid, gridHeight, hasToolbar, true, gridWidth, isMultiSelect, fixHeight, isLimit);
            SetEditGridEvent(pageId, actGridId, sbGrid, isMultiSelect, editFlag, hasClickEvent, clickFlag);

            sbGrid.Length--;
            sbGrid.AppendLine("});");
            SetGridPage(actGridId, pagerId, sbGrid);

            sbGrid.AppendLine("});");
            sbGrid.AppendLine("</script>");
            #endregion
            GenerateGridHtml(actGridId, pagerId, inputName, sbGrid, true);
            SetEditGridMethod(actGridId, sbGrid, gridLayout, primaryKey, inputId, submitBtn, hasToolbar, needAddEvent, isMultiSelect);
            return(sbGrid.ToString());
        }
Esempio n. 16
0
        public async Task <JsonValue> FetchDataHeader(string url)
        {
            LinearLayout linearLayout = FindViewById <LinearLayout>(Resource.Id.ListLinearLayout);
            GridLayout   gridLayout   = FindViewById <GridLayout>(Resource.Id.viewLayout);
            ImageView    imageViewas  = (ImageView)FindViewById(Resource.Id.Imageview);

            navigationView = (NavigationView)FindViewById(Resource.Id.nav_view);
            string dbPath                   = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "mintdata.db3");
            var    db                       = new SQLiteAsyncConnection(dbPath);
            var    HomeButtonTalbe          = db.Table <HomeButton>();
            var    InfoContentTable         = db.Table <InfoContent>();
            var    IntroPageTable           = db.Table <Intropage>();
            var    BackgroundNADBUttonTABLE = db.Table <BackgGroundAndButton>();

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));

            request.ContentType = "application/json";
            request.Method      = "GET";

            try
            {
                // Send the request to the server and wait for the response:
                using (WebResponse response = await request.GetResponseAsync())
                {
                    // Get a stream representation of the HTTP web response:
                    using (System.IO.Stream stream = response.GetResponseStream())
                    {
                        JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

                        JSONArray ja = new JSONArray(jsonDoc.ToString());

                        for (int i = 0; i < ja.Length(); i++)
                        {
                            JSONObject jo = ja.GetJSONObject(i);

                            BackgGroundAndButton BaB = new BackgGroundAndButton
                            {
                                image         = jo.GetString("BackgroundImg"),
                                IsTrueORfalse = jo.GetBoolean("ButtonInterface"),
                            };

                            BaBLisr.Add(BaB);
                            await db.InsertOrReplaceAsync(BaB);

                            InfoContent infoContent = new InfoContent
                            {
                                Content = jo.GetString("ContentText"),
                            };

                            infocontentlist.Add(infoContent);
                            await db.InsertOrReplaceAsync(infoContent);

                            Intropage intropage = new Intropage
                            {
                                LastChanged = jo.GetString("LastChanged"),
                            };

                            IntroPageList.Add(intropage);
                            await db.InsertOrReplaceAsync(intropage);


                            //Convert the Base64 from the api to and image and sets the image to the imageview
                            GetImage = BaB.image;
                            byte[] imgdata     = Convert.FromBase64String(GetImage);
                            var    imageBitmap = Android.Graphics.BitmapFactory.DecodeByteArray(imgdata, 0, imgdata.Length);
                            imageViewas.SetImageBitmap(imageBitmap);

                            //Check if buttoninterfece is false or true
                            if (BaB.IsTrueORfalse == false)
                            {
                                //Create listview

                                string    urlListView = Intent.GetStringExtra("APIListView");
                                JsonValue CreateList  = await FetchListView(urlListView);
                            }

                            else

                            {
                                //Creates imagebuttons
                                JSONArray jsonArray = ja.GetJSONObject(0).GetJSONArray("Buttons");
                                //Hides the linearlayout with the Listview
                                linearLayout.Visibility = ViewStates.Gone;


                                for (int init = 0; init < jsonArray.Length(); init++)
                                {
                                    JSONObject jsonObject = jsonArray.GetJSONObject(init);

                                    HomeButton homeButton = new HomeButton
                                    {
                                        Column        = jsonObject.GetInt("Column"),
                                        Image         = jsonObject.GetString("Image"),
                                        InfoContentId = jsonObject.GetString("InfoContentID"),
                                        ModuleId      = jsonObject.GetInt("ModuleID"),
                                        Row           = jsonObject.GetInt("Row"),
                                    };

                                    HomeButtonList.Add(homeButton);
                                    await db.InsertOrReplaceAsync(homeButton);

                                    GridLayout.LayoutParams paramms = new GridLayout.LayoutParams();
                                    paramms.RowSpec    = GridLayout.InvokeSpec(GridLayout.Undefined, 1f);
                                    paramms.ColumnSpec = GridLayout.InvokeSpec(GridLayout.Undefined, 1f);

                                    var buttons = new ImageButton(this);
                                    buttons.LayoutParameters = paramms;
                                    buttons.SetScaleType(ImageButton.ScaleType.FitXy);
                                    byte[] buttonimg      = Convert.FromBase64String(homeButton.Image);
                                    var    buttonimagemap = Android.Graphics.BitmapFactory.DecodeByteArray(buttonimg, 0, buttonimg.Length);
                                    buttons.SetImageBitmap(buttonimagemap);
                                    gridLayout.AddView(buttons);

                                    //Displays the ModuleID when a imagebutton is pressed.
                                    buttons.Click += delegate
                                    {
                                        Toast.MakeText(this, "ModuleId: " + homeButton.ModuleId.ToString(), ToastLength.Long).Show();
                                    };
                                }
                            }
                        }

                        // Return the JSON document:
                        Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
                        return(url);
                    }
                }
            }

            catch (Exception)
            {
                return(null);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// entry画面grid
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="urlHelper"></param>
        /// <param name="pageId"></param>
        /// <param name="gridId"></param>
        /// <param name="url"></param>
        /// <param name="gridLayout"></param>
        /// <param name="gridHeight"></param>
        /// <param name="gridWidth"></param>
        /// <param name="submitBtn">用户点击提交按钮时,获取表格的json值,如果有多个按钮,以逗号分割</param>
        /// <param name="editFlag"></param>
        /// <param name="pageSizeLimit"></param>
        /// <returns></returns>
        public static MvcHtmlString AppEntryGridFor(this HtmlHelper htmlHelper, UrlHelper urlHelper, string pageId, string gridId, string url, GridLayout gridLayout, int gridHeight, int gridWidth, string submitBtn, string editFlag, bool pageSizeLimit = false)
        {
            string str = EditGrid(urlHelper, pageId, gridId, url, gridLayout, submitBtn, "", false, false, gridHeight, gridWidth, false, editFlag, false, "", false, pageSizeLimit);

            return(MvcHtmlString.Create(str));
        }
Esempio n. 18
0
        private static void SetEditGridMethod(string gridID, StringBuilder sbGrid, GridLayout gridLayout, string primaryKey, string inputId, string submitBtn, bool hasToolbar, bool needAddEvent, bool isMultiSelect)
        {
            sbGrid.AppendLine();
            sbGrid.AppendLine("<script type=\"text/javascript\">");
            sbGrid.AppendLine("$(document).ready(function () {");
            if (!isMultiSelect && hasToolbar)
            {
                if (needAddEvent)
                {
                    sbGrid.AppendLine("$('#btnAdd" + gridID + "', '#t_" + gridID + "').click(function () {");
                    sbGrid.AppendLine("var dataRow = {");
                    foreach (KeyValuePair <string, GridInfo> dic in gridLayout.GridLayouts)
                    {
                        sbGrid.AppendLine(dic.Value.Name + ":'',");
                    }
                    sbGrid.Remove(sbGrid.Length - 3, 3);
                    sbGrid.AppendLine(" };");
                    sbGrid.AppendLine(" var d =new Date();  ");
                    sbGrid.AppendLine("var s= '';");
                    sbGrid.AppendLine(" s += d.getHours().toString();  ");
                    sbGrid.AppendLine(" s += d.getMinutes().toString();  ");
                    sbGrid.AppendLine(" s += d.getSeconds().toString();  ");
                    sbGrid.AppendLine(" s += d.getMilliseconds().toString(); ");
                    sbGrid.AppendLine(" s += Math.floor(Math.random()*100).toString();");
                    sbGrid.AppendLine("$('#" + gridID + "').jqGrid('addRowData', s, dataRow);");
                    sbGrid.AppendLine("$('#" + gridID + "').jqGrid('editRow', s,true);");
                    sbGrid.AppendLine("  });");
                }

                sbGrid.AppendLine("$('#btnDelete" + gridID + "', '#t_" + gridID + "').click(function () {");
                sbGrid.AppendLine("var id = jQuery('#" + gridID + "').jqGrid('getGridParam','selrow');");
                sbGrid.AppendFormat(" var pk=jQuery(\"#{0}\").getCell(id,'{1}');", gridID, primaryKey);
                sbGrid.AppendLine("  var oldval=$('#" + gridID + AppMember.DeletePK + "').val();");
                sbGrid.AppendLine("$('#" + gridID + AppMember.DeletePK + "').attr('value',oldval+','+pk);");
                sbGrid.AppendLine("$('#" + gridID + "').jqGrid('delRowData', id);");
                sbGrid.AppendLine("  });");
            }
            string ss = sbGrid.ToString();

            //sbGrid.AppendLine(" $('#" + btnSubmit + "').click(function () {");
            //sbGrid.AppendLine("$('#" + submitBtn + "').mouseup(function() {");
            sbGrid.AppendLine("$('" + submitBtn + "').mouseup(function() {");  //修改后可支持多个按钮的提交,多个以逗号分割
            sbGrid.AppendFormat(@"var data = $('#{0}').getDataIDs();
                                                    for(i=0;i<data.length;i++){{
                                                        $('#{0}').jqGrid('saveRow',data[i]); 
                                                    }}
                                ", gridID);
            //sbGrid.AppendLine("});");
            sbGrid.AppendLine(" var griddata = '';");
            if (!isMultiSelect)
            {
                sbGrid.AppendLine(" griddata = jQuery('#" + gridID + "').jqGrid('getRowData');");
            }
            else
            {
                sbGrid.AppendLine(" var  arrRow = jQuery('#" + gridID + "').jqGrid('getGridParam','selarrrow');");
                sbGrid.AppendFormat(@"if(arrRow.length > 0)
                                        {{
                                            griddata = new Array();
                                            var rowdata
                                            var j=0;
                                            for(var i=0;i<arrRow.length;i++)
                                            {{
                                                if(arrRow[i]!=undefined){{
                                                    rowdata=jQuery('#{0}').getRowData(arrRow[i]);
                                                    griddata[j] = rowdata;
                                                    j++;             
                                                }}
                                            }}
                                        }}", gridID);
            }
            sbGrid.AppendFormat("$(\"#{0}\").attr(\"value\",JSON.stringify(griddata));", inputId);
            //sbGrid.AppendLine(" var griddata1 =JSON.stringify(griddata);");
            //sbGrid.AppendLine(" alert(griddata1);");
            sbGrid.AppendLine(" });");
            sbGrid.AppendLine("   });");
            sbGrid.AppendLine("</script>");
        }
        public static void ColorGrid()
        {
            // Draws a grid rectangles and then formats the shapes
            // with different colors

            // Demonstrates:
            // How use the GridLayout object to quickly drop a grid
            // How to use ShapeFormatCells to apply formatting to shapes
            // How UpdateBase can be used to modfiy multiple shapes at once

            int[] colors =
            {
                0x0A3B76, 0x4395D1, 0x99D9EA, 0x0D686B, 0x00A99D, 0x7ACCC8, 0x82CA9C,
                0x74A402,
                0xC4DF9B, 0xD9D56F, 0xFFF468, 0xFFF799, 0xFFC20E, 0xEB6119, 0xFBAF5D,
                0xE57300, 0xC14000, 0xB82832, 0xD85171, 0xFEDFEC, 0x563F7F, 0xA186BE,
                0xD9CFE5
            };

            const int num_cols = 5;
            const int num_rows = 5;

            var page = SampleEnvironment.Application.ActiveDocument.Pages.Add();

            var page_size = new VA.Geometry.Size(10, 10);

            SampleEnvironment.SetPageSize(page, page_size);

            var stencil = SampleEnvironment.Application.Documents.OpenStencil("basic_u.vss");
            var master  = stencil.Masters["Rectangle"];

            var layout = new GridLayout(num_cols, num_rows, new VA.Geometry.Size(1, 1), master);

            layout.Origin       = new VA.Geometry.Point(0, 0);
            layout.CellSpacing  = new VA.Geometry.Size(0, 0);
            layout.RowDirection = RowDirection.BottomToTop;

            layout.PerformLayout();
            layout.Render(page);

            var fmtcells = new VA.Shapes.ShapeFormatCells();
            int i        = 0;
            var writer   = new SidSrcWriter();

            foreach (var node in layout.Nodes)
            {
                var shapeid     = node.ShapeID;
                int color_index = i % colors.Length;
                var color       = colors[color_index];
                fmtcells.FillForeground = new VisioAutomation.Models.Color.ColorRgb(color).ToFormula();
                fmtcells.LinePattern    = 0;
                fmtcells.LineWeight     = 0;

                writer.SetValues(shapeid, fmtcells);
                i++;
            }

            writer.Commit(page, VA.ShapeSheet.CellValueType.Formula);

            var bordersize = new VA.Geometry.Size(1, 1);

            page.ResizeToFitContents(bordersize);
        }
Esempio n. 20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="urlHelper"></param>
        /// <param name="pageId"></param>
        /// <param name="formId"></param>
        /// <param name="gridId"></param>
        /// <param name="gridTitle"></param>
        /// <param name="url"></param>
        /// <param name="gridLayout"></param>
        /// <param name="primaryKey"></param>
        /// <param name="viewUrlStr"></param>
        /// <param name="viewTitle"></param>
        /// <param name="gridHeight">页面中去除grid部分的高度</param>
        /// <returns></returns>
        public static MvcHtmlString AppGridFor(this HtmlHelper htmlHelper, UrlHelper urlHelper, string pageId, string formId, string gridId, string url, GridLayout gridLayout, string primaryKey, string viewUrlStr, string viewTitle, int gridHeight)
        {
            string inputName = gridId + AppMember.HideString;

            gridId = gridId + pageId;
            formId = formId + pageId;
            string        pagerId = gridId + "pager";
            StringBuilder sbGrid  = new StringBuilder();

            sbGrid.AppendLine("<script type=\"text/javascript\">");
            sbGrid.AppendLine("$(function(){");
            #region grid设置
            sbGrid.AppendLine("$('#%%GRIDID%%').jqGrid({".Replace("%%GRIDID%%", gridId));
            sbGrid.AppendFormat("url:'{0}',", url);
            sbGrid.AppendFormat("mtype:'{0}',", "post");
            sbGrid.AppendLine(@"datatype: ""json"",");
            //sbGrid.AppendLine("postData: $('form').serialize(),");

            sbGrid.AppendFormat("colNames:[{0}],", GetColNames(gridLayout.GridLayouts));
            sbGrid.AppendFormat("colModel:[{0}],", GetColModel(urlHelper, gridLayout.GridLayouts));

            SetGridProperty(gridId, gridLayout.GridTitle, pagerId, sbGrid, gridHeight, true);
            SetGridEvent(pageId, formId, gridId, sbGrid, primaryKey, viewUrlStr, viewTitle);

            sbGrid.Length--;
            sbGrid.AppendLine("});");
            SetGridPage(gridId, pagerId, sbGrid);
            //sbGrid.AppendLine("  $('#" + gridId + "').setGridHeight($(window).height() - " + gridHeight.ToString()+ ");  ");//调整表格高度

            sbGrid.AppendLine("});");

            #region 窗体改变大小时,重新设定grid的宽度和高度
            //gridResize(gridId, sbGrid);
            #endregion

            sbGrid.AppendLine("</script>");
            #endregion
            GenerateGridHtml(gridId, pagerId, inputName, sbGrid);
            return(MvcHtmlString.Create(sbGrid.ToString()));
        }
Esempio n. 21
0
        public static MvcHtmlString AppMultiSelectGridFor(this HtmlHelper htmlHelper, UrlHelper urlHelper, string pageId, string gridId, string url, GridLayout gridLayout, int gridHeight, bool fixHeight, int gridWidth, bool isMultiSelect)
        {
            string str = EditGrid(urlHelper, pageId, gridId, url, gridLayout, "", "", false, false, gridHeight, gridWidth, isMultiSelect, "", false, "", fixHeight, true);

            return(MvcHtmlString.Create(str));
        }
Esempio n. 22
0
        public static MvcHtmlString AppEntryGridFor(this HtmlHelper htmlHelper, UrlHelper urlHelper, string pageId, string gridId, string url, GridLayout gridLayout, int gridHeight, bool fixHeight, int gridWidth, bool hasToolbar, bool needAddEvent, string submitBtn, string editFlag)
        {
            string str = EditGrid(urlHelper, pageId, gridId, url, gridLayout, submitBtn, "", hasToolbar, needAddEvent, gridHeight, gridWidth, false, editFlag, false, "", fixHeight, false);

            return(MvcHtmlString.Create(str));
        }
Esempio n. 23
0
 public DirectionEnergyDiff(GridLayout.Direction dir, float ene)
 {
     this.m_direction = dir;
     this.m_energyDiff = ene;
 }
Esempio n. 24
0
        public async Task <JsonValue> FetchListView(string url)
        {
            GridLayout   gridLayout   = FindViewById <GridLayout>(Resource.Id.viewLayout);
            LinearLayout linearLayout = FindViewById <LinearLayout>(Resource.Id.ListLinearLayout);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));

            request.ContentType = "application/json";
            request.Method      = "GET";

            try
            {
                // Send the request to the server and wait for the response:
                using (WebResponse response = await request.GetResponseAsync())
                {
                    // Get a stream representation of the HTTP web response:
                    using (System.IO.Stream stream = response.GetResponseStream())
                    {
                        JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

                        JSONArray ja = new JSONArray(jsonDoc.ToString());

                        for (int y = 0; y < ja.Length(); y++)
                        {
                            JSONArray jarray = ja.OptJSONArray(y);

                            for (int i = 0; i < jarray.Length(); i++)
                            {
                                JSONObject jo = jarray.GetJSONObject(i);

                                Agenda agenda = new Agenda
                                {
                                    ShortName    = jo.GetString("ShortName"),
                                    StartTime    = jo.GetString("StartTime"),
                                    EndTime      = jo.GetString("EndTime"),
                                    Location     = jo.GetString("Location"),
                                    EventId      = jo.GetString("EventID"),
                                    Description  = jo.GetString("Description"),
                                    Speakers     = jo.GetString("Speakers"),
                                    SpeakerNames = jo.GetString("SpeakerNames"),
                                };

                                AgendaList.Add(agenda);
                            }
                        }

                        LV         = new ListView(this);
                        LV.Adapter = new ListViewEvents(this, AgendaList);
                        linearLayout.AddView(LV);

                        LV.ItemClick += itemclick;

                        Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
                        // Return the JSON document:
                        return(url);
                    }
                }
            }

            catch (Exception)
            {
                Toast.MakeText(this, "Couldnt find a list", ToastLength.Long).Show();
                return(null);
            }
        }
Esempio n. 25
0
 public override void init()
 {
   Scheduler scheduler = this;
   CardLayout cardLayout1 = new CardLayout();
   CardLayout cardLayout2 = cardLayout1;
   this.cardLayout = cardLayout1;
   ((Container) this).setLayout((LayoutManager) cardLayout2);
   this.labels = (List) new ArrayList();
   this.buttons = (List) new ArrayList();
   this.commandPanel = new JPanel();
   ((Container) this.commandPanel).setLayout((LayoutManager) new GridLayout(0, 2));
   this.commandLabels = new JPanel();
   this.cancelButtons = new JPanel();
   ((Container) this.commandPanel).add((Component) this.commandLabels, (object) "West");
   ((Container) this.commandPanel).add((Component) this.cancelButtons, (object) "Center");
   this.commandLayout = new GridLayout(0, 1);
   this.cancelLayout = new GridLayout(0, 1);
   ((Container) this.commandLabels).setLayout((LayoutManager) this.commandLayout);
   ((Container) this.cancelButtons).setLayout((LayoutManager) this.cancelLayout);
   ((Container) this).add((Component) this.commandPanel, (object) "Commands");
   this.noCommands = new JLabel("No commands running.");
   this.noCommands.setHorizontalAlignment(0);
   ((Container) this).add((Component) this.noCommands, (object) "No Command");
   this.cardLayout.show((Container) this, "No Command");
   ((Component) this).repaint();
 }
        public static void DrawSelectedHexGridArea(GridLayout gridLayout, BoundsInt area, Color color)
        {
            int requiredVertices = 4 * (area.size.x + area.size.y) - 2;

            if (requiredVertices < 0)
            {
                return;
            }
            Vector3[] cellLocals      = new Vector3[requiredVertices];
            int       horizontalCount = area.size.x * 2;
            int       verticalCount   = area.size.y * 2 - 1;
            int       bottom          = 0;
            int       top             = horizontalCount + verticalCount + horizontalCount - 1;
            int       left            = requiredVertices - 1;
            int       right           = horizontalCount;

            Vector3[] cellOffset =
            {
                Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(0,                          gridLayout.cellSize.y / 2,  0)),
                Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(gridLayout.cellSize.x / 2,  gridLayout.cellSize.y / 4,  0)),
                Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(gridLayout.cellSize.x / 2,  -gridLayout.cellSize.y / 4, 0)),
                Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(0,                          -gridLayout.cellSize.y / 2, 0)),
                Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(-gridLayout.cellSize.x / 2, -gridLayout.cellSize.y / 4, 0)),
                Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(-gridLayout.cellSize.x / 2, gridLayout.cellSize.y / 4, 0))
            };
            // Fill Top and Bottom Vertices
            for (int x = area.min.x; x < area.max.x; x++)
            {
                cellLocals[bottom++] = gridLayout.CellToLocal(new Vector3Int(x, area.min.y, 0)) + cellOffset[4];
                cellLocals[bottom++] = gridLayout.CellToLocal(new Vector3Int(x, area.min.y, 0)) + cellOffset[3];
                cellLocals[top--]    = gridLayout.CellToLocal(new Vector3Int(x, area.max.y - 1, 0)) + cellOffset[0];
                cellLocals[top--]    = gridLayout.CellToLocal(new Vector3Int(x, area.max.y - 1, 0)) + cellOffset[1];
            }
            // Fill first Left and Right Vertices
            cellLocals[left--] = gridLayout.CellToLocal(new Vector3Int(area.min.x, area.min.y, 0)) + cellOffset[5];
            cellLocals[top--]  = gridLayout.CellToLocal(new Vector3Int(area.max.x - 1, area.max.y - 1, 0)) + cellOffset[2];
            // Fill Left and Right Vertices
            for (int y = area.min.y + 1; y < area.max.y; y++)
            {
                cellLocals[left--] = gridLayout.CellToLocal(new Vector3Int(area.min.x, y, 0)) + cellOffset[4];
                cellLocals[left--] = gridLayout.CellToLocal(new Vector3Int(area.min.x, y, 0)) + cellOffset[5];
            }
            for (int y = area.min.y; y < (area.max.y - 1); y++)
            {
                cellLocals[right++] = gridLayout.CellToLocal(new Vector3Int(area.max.x - 1, y, 0)) + cellOffset[2];
                cellLocals[right++] = gridLayout.CellToLocal(new Vector3Int(area.max.x - 1, y, 0)) + cellOffset[1];
            }
            HandleUtility.ApplyWireMaterial();
            GL.PushMatrix();
            GL.MultMatrix(gridLayout.transform.localToWorldMatrix);
            GL.Begin(GL.LINES);
            GL.Color(color);
            int i = 0;

            for (int j = cellLocals.Length - 1; i < cellLocals.Length; j = i++)
            {
                DrawBatchedLine(cellLocals[j], cellLocals[i]);
            }
            GL.End();
            GL.PopMatrix();
        }
Esempio n. 27
0
        public override void OnEnter()
        {
            DefaultFont = Game.Content.Load<SpriteFont>(ContentPaths.Fonts.Default);
            GUI = new DwarfGUI(Game, DefaultFont, Game.Content.Load<SpriteFont>(ContentPaths.Fonts.Title), Game.Content.Load<SpriteFont>(ContentPaths.Fonts.Small), Input);
            IsInitialized = true;
            Drawer = new Drawer2D(Game.Content, Game.GraphicsDevice);
            MainWindow = new Panel(GUI, GUI.RootComponent)
            {
                LocalBounds = new Rectangle(EdgePadding, EdgePadding, Game.GraphicsDevice.Viewport.Width - EdgePadding * 2, Game.GraphicsDevice.Viewport.Height - EdgePadding * 2)
            };
            Layout = new GridLayout(GUI, MainWindow, 10, 6);

            Label label = new Label(GUI, Layout, "Options", GUI.TitleFont);
            Layout.SetComponentPosition(label, 0, 0, 1, 1);

            TabSelector = new TabSelector(GUI, Layout, 6);
            Layout.SetComponentPosition(TabSelector, 0, 1, 6, 8);

            TabSelector.Tab graphicsTab = TabSelector.AddTab("Graphics");

            GroupBox graphicsBox = new GroupBox(GUI, graphicsTab, "Graphics")
            {
                WidthSizeMode = GUIComponent.SizeMode.Fit,
                HeightSizeMode = GUIComponent.SizeMode.Fit
            };

            Categories["Graphics"] = graphicsBox;
            CurrentBox = graphicsBox;

            GridLayout graphicsLayout = new GridLayout(GUI, graphicsBox, 6, 5);

            Label resolutionLabel = new Label(GUI, graphicsLayout, "Resolution", GUI.DefaultFont)
            {
                Alignment = Drawer2D.Alignment.Right
            };

            ComboBox resolutionBox = new ComboBox(GUI, graphicsLayout)
            {
                ToolTip = "Sets the size of the screen.\nSmaller for higher framerates."
            };

            foreach(DisplayMode mode in GraphicsAdapter.DefaultAdapter.SupportedDisplayModes)
            {
                if(mode.Format != SurfaceFormat.Color)
                {
                    continue;
                }

                if (mode.Width <= 640) continue;

                string s = mode.Width + " x " + mode.Height;
                DisplayModes[s] = mode;
                if(mode.Width == GameSettings.Default.ResolutionX && mode.Height == GameSettings.Default.ResolutionY)
                {
                    resolutionBox.AddValue(s);
                    resolutionBox.CurrentValue = s;
                }
                else
                {
                    resolutionBox.AddValue(s);
                }
            }

            graphicsLayout.SetComponentPosition(resolutionLabel, 0, 0, 1, 1);
            graphicsLayout.SetComponentPosition(resolutionBox, 1, 0, 1, 1);

            resolutionBox.OnSelectionModified += resolutionBox_OnSelectionModified;

            Checkbox fullscreenCheck = new Checkbox(GUI, graphicsLayout, "Fullscreen", GUI.DefaultFont, GameSettings.Default.Fullscreen)
            {
                ToolTip = "If this is checked, the game takes up the whole screen."
            };

            graphicsLayout.SetComponentPosition(fullscreenCheck, 0, 1, 1, 1);

            fullscreenCheck.OnCheckModified += fullscreenCheck_OnClicked;

            Label drawDistance = new Label(GUI, graphicsLayout, "Draw Distance", GUI.DefaultFont);
            Slider chunkDrawSlider = new Slider(GUI, graphicsLayout, "", GameSettings.Default.ChunkDrawDistance, 1, 1000, Slider.SliderMode.Integer)
            {
                ToolTip = "Maximum distance at which terrain will be drawn\nSmaller for faster."
            };

            graphicsLayout.SetComponentPosition(drawDistance, 0, 2, 1, 1);
            graphicsLayout.SetComponentPosition(chunkDrawSlider, 1, 2, 1, 1);
            chunkDrawSlider.OnValueModified += ChunkDrawSlider_OnValueModified;

            Label cullDistance = new Label(GUI, graphicsLayout, "Cull Distance", GUI.DefaultFont);
            Slider cullSlider = new Slider(GUI, graphicsLayout, "", GameSettings.Default.VertexCullDistance, 0.1f, 1000, Slider.SliderMode.Integer)
            {
                ToolTip = "Maximum distance at which anything will be drawn\n Smaller for faster."
            };

            cullSlider.OnValueModified += CullSlider_OnValueModified;

            graphicsLayout.SetComponentPosition(cullDistance, 0, 3, 1, 1);
            graphicsLayout.SetComponentPosition(cullSlider, 1, 3, 1, 1);

            Label generateDistance = new Label(GUI, graphicsLayout, "Generate Distance", GUI.DefaultFont);
            Slider generateSlider = new Slider(GUI, graphicsLayout, "", GameSettings.Default.ChunkGenerateDistance, 1, 1000, Slider.SliderMode.Integer)
            {
                ToolTip = "Maximum distance at which terrain will be generated."
            };

            generateSlider.OnValueModified += GenerateSlider_OnValueModified;

            graphicsLayout.SetComponentPosition(generateDistance, 0, 4, 1, 1);
            graphicsLayout.SetComponentPosition(generateSlider, 1, 4, 1, 1);

            Checkbox glowBox = new Checkbox(GUI, graphicsLayout, "Enable Glow", GUI.DefaultFont, GameSettings.Default.EnableGlow)
            {
                ToolTip = "When checked, there will be a fullscreen glow effect."
            };

            graphicsLayout.SetComponentPosition(glowBox, 1, 1, 1, 1);
            glowBox.OnCheckModified += glowBox_OnCheckModified;

            Label aaLabel = new Label(GUI, graphicsLayout, "Antialiasing", GUI.DefaultFont)
            {
                Alignment = Drawer2D.Alignment.Right
            };

            ComboBox aaBox = new ComboBox(GUI, graphicsLayout)
            {
                ToolTip = "Determines how much antialiasing (smoothing) there is.\nHigher means more smooth, but is slower."
            };
            aaBox.AddValue("None");
            aaBox.AddValue("FXAA");
            aaBox.AddValue("2x MSAA");
            aaBox.AddValue("4x MSAA");
            aaBox.AddValue("16x MSAA");

            foreach(string s in AAModes.Keys.Where(s => AAModes[s] == GameSettings.Default.AntiAliasing))
            {
                aaBox.CurrentValue = s;
            }

            aaBox.OnSelectionModified += AABox_OnSelectionModified;

            graphicsLayout.SetComponentPosition(aaLabel, 2, 0, 1, 1);
            graphicsLayout.SetComponentPosition(aaBox, 3, 0, 1, 1);

            Checkbox reflectTerrainBox = new Checkbox(GUI, graphicsLayout, "Reflect Chunks", GUI.DefaultFont, GameSettings.Default.DrawChunksReflected)
            {
                ToolTip = "When checked, water will reflect terrain."
            };
            reflectTerrainBox.OnCheckModified += reflectTerrainBox_OnCheckModified;
            graphicsLayout.SetComponentPosition(reflectTerrainBox, 2, 1, 1, 1);

            Checkbox refractTerrainBox = new Checkbox(GUI, graphicsLayout, "Refract Chunks", GUI.DefaultFont, GameSettings.Default.DrawChunksRefracted)
            {
                ToolTip = "When checked, water will refract terrain."
            };
            refractTerrainBox.OnCheckModified += refractTerrainBox_OnCheckModified;
            graphicsLayout.SetComponentPosition(refractTerrainBox, 2, 2, 1, 1);

            Checkbox reflectEntities = new Checkbox(GUI, graphicsLayout, "Reflect Entities", GUI.DefaultFont, GameSettings.Default.DrawEntityReflected)
            {
                ToolTip = "When checked, water will reflect trees, dwarves, etc."
            };
            reflectEntities.OnCheckModified += reflectEntities_OnCheckModified;
            graphicsLayout.SetComponentPosition(reflectEntities, 3, 1, 1, 1);

            Checkbox refractEntities = new Checkbox(GUI, graphicsLayout, "Refract Entities", GUI.DefaultFont, GameSettings.Default.DrawEntityReflected)
            {
                ToolTip = "When checked, water will reflect trees, dwarves, etc."
            };
            refractEntities.OnCheckModified += refractEntities_OnCheckModified;
            graphicsLayout.SetComponentPosition(refractEntities, 3, 2, 1, 1);

            Checkbox sunlight = new Checkbox(GUI, graphicsLayout, "Sunlight", GUI.DefaultFont, GameSettings.Default.CalculateSunlight)
            {
                ToolTip = "When checked, terrain will be lit/shadowed by the sun."
            };
            sunlight.OnCheckModified += sunlight_OnCheckModified;
            graphicsLayout.SetComponentPosition(sunlight, 2, 3, 1, 1);

            Checkbox ao = new Checkbox(GUI, graphicsLayout, "Ambient Occlusion", GUI.DefaultFont, GameSettings.Default.AmbientOcclusion)
            {
                ToolTip = "When checked, terrain will smooth shading effects."
            };
            ao.OnCheckModified += AO_OnCheckModified;
            graphicsLayout.SetComponentPosition(ao, 3, 3, 1, 1);

            Checkbox ramps = new Checkbox(GUI, graphicsLayout, "Ramps", GUI.DefaultFont, GameSettings.Default.CalculateRamps)
            {
                ToolTip = "When checked, some terrain will have smooth ramps."
            };

            ramps.OnCheckModified += ramps_OnCheckModified;
            graphicsLayout.SetComponentPosition(ramps, 2, 4, 1, 1);

            Checkbox cursorLight = new Checkbox(GUI, graphicsLayout, "Cursor Light", GUI.DefaultFont, GameSettings.Default.CursorLightEnabled)
            {
                ToolTip = "When checked, a light will follow the player cursor."
            };

            cursorLight.OnCheckModified += cursorLight_OnCheckModified;
            graphicsLayout.SetComponentPosition(cursorLight, 2, 5, 1, 1);

            Checkbox entityLight = new Checkbox(GUI, graphicsLayout, "Entity Lighting", GUI.DefaultFont, GameSettings.Default.EntityLighting)
            {
                ToolTip = "When checked, dwarves, objects, etc. will be lit\nby the sun, lamps, etc."
            };

            entityLight.OnCheckModified += entityLight_OnCheckModified;
            graphicsLayout.SetComponentPosition(entityLight, 3, 4, 1, 1);

            Checkbox selfIllum = new Checkbox(GUI, graphicsLayout, "Ore Glow", GUI.DefaultFont, GameSettings.Default.SelfIlluminationEnabled)
            {
                ToolTip = "When checked, some terrain elements will glow."
            };

            selfIllum.OnCheckModified += selfIllum_OnCheckModified;
            graphicsLayout.SetComponentPosition(selfIllum, 3, 5, 1, 1);

            Checkbox particlePhysics = new Checkbox(GUI, graphicsLayout, "Particle Body", GUI.DefaultFont, GameSettings.Default.ParticlePhysics)
            {
                ToolTip = "When checked, some particles will bounce off terrain."
            };

            particlePhysics.OnCheckModified += particlePhysics_OnCheckModified;
            graphicsLayout.SetComponentPosition(particlePhysics, 0, 5, 1, 1);

            TabSelector.Tab graphics2Tab = TabSelector.AddTab("Graphics II");
            GroupBox graphicsBox2 = new GroupBox(GUI, graphics2Tab, "Graphics II")
            {
                HeightSizeMode = GUIComponent.SizeMode.Fit,
                WidthSizeMode = GUIComponent.SizeMode.Fit
            };
            Categories["Graphics II"] = graphicsBox2;
            GridLayout graphicsLayout2 = new GridLayout(GUI, graphicsBox2, 6, 5);

            Checkbox moteBox = new Checkbox(GUI, graphicsLayout2, "Generate Motes", GUI.DefaultFont, GameSettings.Default.GrassMotes)
            {
                ToolTip = "When checked, trees, grass, etc. will be visible."
            };

            moteBox.OnCheckModified += MoteBox_OnCheckModified;
            graphicsLayout2.SetComponentPosition(moteBox, 1, 2, 1, 1);

            Label numMotes = new Label(GUI, graphicsLayout2, "Num Motes", GUI.DefaultFont);
            Slider motesSlider = new Slider(GUI, graphicsLayout2, "", (int) (GameSettings.Default.NumMotes * 100), 0, 1000, Slider.SliderMode.Integer)
            {
                ToolTip = "Determines the maximum amount of trees/grass that will be visible."
            };

            graphicsLayout2.SetComponentPosition(numMotes, 0, 1, 1, 1);
            graphicsLayout2.SetComponentPosition(motesSlider, 1, 1, 1, 1);
            motesSlider.OnValueModified += MotesSlider_OnValueModified;
            TabSelector.Tab gameplayTab = TabSelector.AddTab("Gameplay");
            GroupBox gameplayBox = new GroupBox(GUI, gameplayTab, "Gameplay")
            {
                WidthSizeMode = GUIComponent.SizeMode.Fit,
                HeightSizeMode = GUIComponent.SizeMode.Fit
            };
            Categories["Gameplay"] = gameplayBox;

            GridLayout gameplayLayout = new GridLayout(GUI, gameplayBox, 6, 5);

            Label moveSpeedLabel = new Label(GUI, gameplayLayout, "Camera Move Speed", GUI.DefaultFont);
            Slider moveSlider = new Slider(GUI, gameplayLayout, "", GameSettings.Default.CameraScrollSpeed, 0.0f, 20.0f, Slider.SliderMode.Float)
            {
                ToolTip = "Determines how fast the camera will move when keys are pressed."
            };

            gameplayLayout.SetComponentPosition(moveSpeedLabel, 0, 0, 1, 1);
            gameplayLayout.SetComponentPosition(moveSlider, 1, 0, 1, 1);
            moveSlider.OnValueModified += MoveSlider_OnValueModified;

            Label zoomSpeedLabel = new Label(GUI, gameplayLayout, "Zoom Speed", GUI.DefaultFont);
            Slider zoomSlider = new Slider(GUI, gameplayLayout, "", GameSettings.Default.CameraZoomSpeed, 0.0f, 2.0f, Slider.SliderMode.Float)
            {
                ToolTip = "Determines how fast the camera will go\nup and down with the scroll wheel."
            };

            gameplayLayout.SetComponentPosition(zoomSpeedLabel, 0, 1, 1, 1);
            gameplayLayout.SetComponentPosition(zoomSlider, 1, 1, 1, 1);
            zoomSlider.OnValueModified += ZoomSlider_OnValueModified;

            Checkbox invertZoomBox = new Checkbox(GUI, gameplayLayout, "Invert Zoom", GUI.DefaultFont, GameSettings.Default.InvertZoom)
            {
                ToolTip = "When checked, the scroll wheel is reversed\nfor zooming."
            };

            gameplayLayout.SetComponentPosition(invertZoomBox, 2, 1, 1, 1);
            invertZoomBox.OnCheckModified += InvertZoomBox_OnCheckModified;

            Checkbox edgeScrollBox = new Checkbox(GUI, gameplayLayout, "Edge Scrolling", GUI.DefaultFont, GameSettings.Default.EnableEdgeScroll)
            {
                ToolTip = "When checked, the camera will scroll\nwhen the cursor is at the edge of the screen."
            };

            gameplayLayout.SetComponentPosition(edgeScrollBox, 0, 2, 1, 1);
            edgeScrollBox.OnCheckModified += EdgeScrollBox_OnCheckModified;

            Checkbox introBox = new Checkbox(GUI, gameplayLayout, "Play Intro", GUI.DefaultFont, GameSettings.Default.DisplayIntro)
            {
                ToolTip = "When checked, the intro will be played when the game starts"
            };

            gameplayLayout.SetComponentPosition(introBox, 1, 2, 1, 1);
            introBox.OnCheckModified += IntroBox_OnCheckModified;

            Checkbox fogOfWarBox = new Checkbox(GUI, gameplayLayout, "Fog of War", GUI.DefaultFont, GameSettings.Default.FogofWar)
            {
                ToolTip = "When checked, unexplored blocks will be blacked out"
            };

            gameplayLayout.SetComponentPosition(fogOfWarBox, 2, 2, 1, 1);

            fogOfWarBox.OnCheckModified += fogOfWarBox_OnCheckModified;

            /*
            Label chunkWidthLabel = new Label(GUI, gameplayLayout, "Chunk Width", GUI.DefaultFont);
            Slider chunkWidthSlider = new Slider(GUI, gameplayLayout, "", GameSettings.Default.ChunkWidth, 4, 256, Slider.SliderMode.Integer)
            {
                ToolTip = "Determines the number of blocks in a chunk of terrain."
            };

            gameplayLayout.SetComponentPosition(chunkWidthLabel, 0, 3, 1, 1);
            gameplayLayout.SetComponentPosition(chunkWidthSlider, 1, 3, 1, 1);
            chunkWidthSlider.OnValueModified += ChunkWidthSlider_OnValueModified;

            Label chunkHeightLabel = new Label(GUI, gameplayLayout, "Chunk Height", GUI.DefaultFont);
            Slider chunkHeightSlider = new Slider(GUI, gameplayLayout, "", GameSettings.Default.ChunkHeight, 4, 256, Slider.SliderMode.Integer)
            {
                ToolTip = "Determines the maximum depth,\nin blocks, of a chunk of terrain."
            };

            gameplayLayout.SetComponentPosition(chunkHeightLabel, 2, 3, 1, 1);
            gameplayLayout.SetComponentPosition(chunkHeightSlider, 3, 3, 1, 1);

            chunkHeightSlider.OnValueModified += ChunkHeightSlider_OnValueModified;

            Label worldWidthLabel = new Label(GUI, gameplayLayout, "World Width", GUI.DefaultFont);
            Slider worldWidthSlider = new Slider(GUI, gameplayLayout, "", GameSettings.Default.WorldWidth, 4, 2048, Slider.SliderMode.Integer)
            {
                ToolTip = "Determines the size of the overworld."
            };

            gameplayLayout.SetComponentPosition(worldWidthLabel, 0, 4, 1, 1);
            gameplayLayout.SetComponentPosition(worldWidthSlider, 1, 4, 1, 1);
            worldWidthSlider.OnValueModified += WorldWidthSlider_OnValueModified;

            Label worldHeightLabel = new Label(GUI, gameplayLayout, "World Height", GUI.DefaultFont);
            Slider worldHeightSlider = new Slider(GUI, gameplayLayout, "", GameSettings.Default.WorldHeight, 4, 2048, Slider.SliderMode.Integer)
            {
                ToolTip = "Determines the size of the overworld."
            };

            gameplayLayout.SetComponentPosition(worldHeightLabel, 2, 4, 1, 1);
            gameplayLayout.SetComponentPosition(worldHeightSlider, 3, 4, 1, 1);
            worldHeightSlider.OnValueModified += WorldHeightSlider_OnValueModified;

            Label worldScaleLabel = new Label(GUI, gameplayLayout, "World Scale", GUI.DefaultFont);
            Slider worldScaleSlider = new Slider(GUI, gameplayLayout, "", GameSettings.Default.WorldScale, 2, 128, Slider.SliderMode.Integer)
            {
                ToolTip = "Determines the number of voxel\nper pixel of the overworld"
            };

            gameplayLayout.SetComponentPosition(worldScaleLabel, 0, 5, 1, 1);
            gameplayLayout.SetComponentPosition(worldScaleSlider, 1, 5, 1, 1);
            worldScaleSlider.OnValueModified += WorldScaleSlider_OnValueModified;
            */

            TabSelector.Tab audioTab = TabSelector.AddTab("Audio");

            GroupBox audioBox = new GroupBox(GUI, audioTab, "Audio")
            {
              WidthSizeMode = GUIComponent.SizeMode.Fit,
              HeightSizeMode = GUIComponent.SizeMode.Fit
            };
            Categories["Audio"] = audioBox;

            GridLayout audioLayout = new GridLayout(GUI, audioBox, 6, 5);

            Label masterLabel = new Label(GUI, audioLayout, "Master Volume", GUI.DefaultFont);
            Slider masterSlider = new Slider(GUI, audioLayout, "", GameSettings.Default.MasterVolume, 0.0f, 1.0f, Slider.SliderMode.Float);
            audioLayout.SetComponentPosition(masterLabel, 0, 0, 1, 1);
            audioLayout.SetComponentPosition(masterSlider, 1, 0, 1, 1);
            masterSlider.OnValueModified += MasterSlider_OnValueModified;

            Label sfxLabel = new Label(GUI, audioLayout, "SFX Volume", GUI.DefaultFont);
            Slider sfxSlider = new Slider(GUI, audioLayout, "", GameSettings.Default.SoundEffectVolume, 0.0f, 1.0f, Slider.SliderMode.Float);
            audioLayout.SetComponentPosition(sfxLabel, 0, 1, 1, 1);
            audioLayout.SetComponentPosition(sfxSlider, 1, 1, 1, 1);
            sfxSlider.OnValueModified += SFXSlider_OnValueModified;

            Label musicLabel = new Label(GUI, audioLayout, "Music Volume", GUI.DefaultFont);
            Slider musicSlider = new Slider(GUI, audioLayout, "", GameSettings.Default.MusicVolume, 0.0f, 1.0f, Slider.SliderMode.Float);
            audioLayout.SetComponentPosition(musicLabel, 0, 2, 1, 1);
            audioLayout.SetComponentPosition(musicSlider, 1, 2, 1, 1);
            musicSlider.OnValueModified += MusicSlider_OnValueModified;

            TabSelector.Tab keysTab = TabSelector.AddTab("Keys");
            GroupBox keysBox = new GroupBox(GUI, keysTab, "Keys")
            {
                WidthSizeMode = GUIComponent.SizeMode.Fit,
                HeightSizeMode = GUIComponent.SizeMode.Fit
            };
            Categories["Keys"] = keysBox;

            KeyEditor keyeditor = new KeyEditor(GUI, keysBox, new KeyManager(), 8, 4);
            GridLayout keyLayout = new GridLayout(GUI, keysBox, 1, 1);
            keyLayout.SetComponentPosition(keyeditor, 0, 0, 1, 1);
            keyLayout.UpdateSizes();
            keyeditor.UpdateLayout();

            /*
            GroupBox customBox = new GroupBox(GUI, Layout, "Customization")
            {
                IsVisible = false
            };
            Categories["Customization"] = customBox;
            TabSelector.AddItem("Customization");

            GridLayout customBoxLayout = new GridLayout(GUI, customBox, 6, 5);

            List<string> assets = TextureManager.DefaultContent.Keys.ToList();

            AssetManager assetManager = new AssetManager(GUI, customBoxLayout, assets);
            customBoxLayout.SetComponentPosition(assetManager, 0, 0, 5, 6);
            */

            Button apply = new Button(GUI, Layout, "Apply", GUI.DefaultFont, Button.ButtonMode.ToolButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.Check));
            Layout.SetComponentPosition(apply, 5, 9, 1, 1);
            apply.OnClicked += apply_OnClicked;

            Button back = new Button(GUI, Layout, "Back", GUI.DefaultFont, Button.ButtonMode.ToolButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.LeftArrow));
            Layout.SetComponentPosition(back, 4, 9, 1, 1);
            back.OnClicked += back_OnClicked;

            Layout.UpdateSizes();
            TabSelector.UpdateSize();
            TabSelector.SetTab("Graphics");
            base.OnEnter();
        }
        private static Mesh GenerateCachedHexagonalGridMesh(GridLayout gridLayout, Color color)
        {
            Mesh mesh = new Mesh();

            mesh.hideFlags = HideFlags.HideAndDontSave;
            int vertex = 0;
            int max    = k_GridGizmoVertexCount / (2 * (6 * 2));

            max = (max / 4) * 4;
            int   min = -max;
            float numVerticalCells = 6 * (max / 4);
            int   totalVertices    = max * 2 * 6 * 2;
            var   cellStrideY      = gridLayout.cellGap.y + gridLayout.cellSize.y;
            var   cellOffsetY      = gridLayout.cellSize.y / 2;
            var   hexOffset        = (1.0f / 3.0f);
            var   drawTotal        = numVerticalCells * 2.0f * hexOffset;
            var   drawDiagTotal    = 2 * drawTotal;

            Vector3[] vertices = new Vector3[totalVertices];
            Vector2[] uvs2     = new Vector2[totalVertices];
            // Draw Vertical Lines
            for (int x = min; x < max; x++)
            {
                vertices[vertex]     = gridLayout.CellToLocal(new Vector3Int(x, min, 0));
                vertices[vertex + 1] = gridLayout.CellToLocal(new Vector3Int(x, max, 0));
                uvs2[vertex]         = new Vector2(0f, 2 * hexOffset);
                uvs2[vertex + 1]     = new Vector2(0f, 2 * hexOffset + drawTotal);
                vertex += 2;
                // Alternate Row Offset
                vertices[vertex]     = gridLayout.CellToLocal(new Vector3Int(x, min - 1, 0));
                vertices[vertex + 1] = gridLayout.CellToLocal(new Vector3Int(x, max - 1, 0));
                uvs2[vertex]         = new Vector2(0f, 2 * hexOffset);
                uvs2[vertex + 1]     = new Vector2(0f, 2 * hexOffset + drawTotal);
                vertex += 2;
            }
            // Draw Diagonals
            for (int y = min; y < max; y++)
            {
                float drawDiagOffset = ((y + 1) % 3) * hexOffset;
                var   cellOffSet     = Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(0f, y * cellStrideY + cellOffsetY, 0.0f));
                // Slope Up
                vertices[vertex]     = gridLayout.CellToLocal(new Vector3Int(Mathf.RoundToInt(1.5f * min), min, 0)) + cellOffSet;
                vertices[vertex + 1] = gridLayout.CellToLocal(new Vector3Int(Mathf.RoundToInt(1.5f * max), max, 0)) + cellOffSet;
                uvs2[vertex]         = new Vector2(0f, drawDiagOffset);
                uvs2[vertex + 1]     = new Vector2(0f, drawDiagOffset + drawDiagTotal);
                vertex += 2;
                // Slope Down
                vertices[vertex]     = gridLayout.CellToLocal(new Vector3Int(Mathf.RoundToInt(1.5f * max), min, 0)) + cellOffSet;
                vertices[vertex + 1] = gridLayout.CellToLocal(new Vector3Int(Mathf.RoundToInt(1.5f * min), max, 0)) + cellOffSet;
                uvs2[vertex]         = new Vector2(0f, drawDiagOffset);
                uvs2[vertex + 1]     = new Vector2(0f, drawDiagOffset + drawDiagTotal);
                vertex += 2;
                // Alternate Row Offset
                vertices[vertex]     = gridLayout.CellToLocal(new Vector3Int(Mathf.RoundToInt(1.5f * min) + 1, min, 0)) + cellOffSet;
                vertices[vertex + 1] = gridLayout.CellToLocal(new Vector3Int(Mathf.RoundToInt(1.5f * max) + 1, max, 0)) + cellOffSet;
                uvs2[vertex]         = new Vector2(0f, drawDiagOffset);
                uvs2[vertex + 1]     = new Vector2(0f, drawDiagOffset + drawDiagTotal);
                vertex              += 2;
                vertices[vertex]     = gridLayout.CellToLocal(new Vector3Int(Mathf.RoundToInt(1.5f * max) + 1, min, 0)) + cellOffSet;
                vertices[vertex + 1] = gridLayout.CellToLocal(new Vector3Int(Mathf.RoundToInt(1.5f * min) + 1, max, 0)) + cellOffSet;
                uvs2[vertex]         = new Vector2(0f, drawDiagOffset);
                uvs2[vertex + 1]     = new Vector2(0f, drawDiagOffset + drawDiagTotal);
                vertex              += 2;
            }
            var uv0     = new Vector2(k_GridGizmoDistanceFalloff, 0f);
            var indices = new int[totalVertices];
            var uvs     = new Vector2[totalVertices];
            var colors  = new Color[totalVertices];

            for (int i = 0; i < totalVertices; i++)
            {
                uvs[i]     = uv0;
                indices[i] = i;
                colors[i]  = color;
            }
            mesh.vertices = vertices;
            mesh.uv       = uvs;
            mesh.uv2      = uvs2;
            mesh.colors   = colors;
            mesh.SetIndices(indices, MeshTopology.Lines, 0);
            return(mesh);
        }
Esempio n. 29
0
        public override void OnEnter()
        {
            IsInitialized = true;
            DefaultFont = Game.Content.Load<SpriteFont>(ContentPaths.Fonts.Default);
            GUI = new DwarfGUI(Game, DefaultFont, Game.Content.Load<SpriteFont>(ContentPaths.Fonts.Title), Game.Content.Load<SpriteFont>(ContentPaths.Fonts.Small), Input);
            MainWindow = new Panel(GUI, GUI.RootComponent)
            {
                LocalBounds = new Rectangle(EdgePadding, EdgePadding, Game.GraphicsDevice.Viewport.Width - EdgePadding * 2, Game.GraphicsDevice.Viewport.Height - EdgePadding * 2)
            };
            Layout = new GridLayout(GUI, MainWindow, 10, 3);

            Label title = new Label(GUI, Layout, "Create a Company", GUI.TitleFont);
            Layout.SetComponentPosition(title, 0, 0, 1, 1);

            Label companyNameLabel = new Label(GUI, Layout, "Name", GUI.DefaultFont);
            Layout.SetComponentPosition(companyNameLabel, 0, 1, 1, 1);

            CompanyNameEdit = new LineEdit(GUI, Layout, CompanyName);
            Layout.SetComponentPosition(CompanyNameEdit, 1, 1, 1, 1);

            Button randomButton = new Button(GUI, Layout, "Random", GUI.DefaultFont, Button.ButtonMode.PushButton, null)
            {
                ToolTip = "Randomly generate a name"
            };
            Layout.SetComponentPosition(randomButton, 2, 1, 1, 1);
            randomButton.OnClicked += randomButton_OnClicked;

            Label companyMottoLabel = new Label(GUI, Layout, "Motto", GUI.DefaultFont);
            Layout.SetComponentPosition(companyMottoLabel, 0, 2, 1, 1);

            CompanyMottoEdit = new LineEdit(GUI, Layout, CompanyMotto);
            Layout.SetComponentPosition(CompanyMottoEdit, 1, 2, 1, 1);
            CompanyMottoEdit.OnTextModified += companyMottoEdit_OnTextModified;

            CompanyNameEdit.OnTextModified += companyNameEdit_OnTextModified;

            Button randomButton2 = new Button(GUI, Layout, "Random", GUI.DefaultFont, Button.ButtonMode.PushButton, null)
            {
                ToolTip = "Randomly generate a motto"
            };
            Layout.SetComponentPosition(randomButton2, 2, 2, 1, 1);
            randomButton2.OnClicked += randomButton2_OnClicked;

            Label companyLogoLabel = new Label(GUI, Layout, "Logo", GUI.DefaultFont);
            Layout.SetComponentPosition(companyLogoLabel, 0, 3, 1, 1);

            CompanyLogoPanel = new ImagePanel(GUI, Layout, CompanyLogo)
            {
                KeepAspectRatio = true,
                AssetName = CompanyLogo.AssetName
            };
            Layout.SetComponentPosition(CompanyLogoPanel, 1, 3, 1, 1);

            Button selectorButton = new Button(GUI, Layout, "Select", GUI.DefaultFont, Button.ButtonMode.PushButton, null)
            {
                ToolTip = "Load a custom company logo"
            };
            Layout.SetComponentPosition(selectorButton, 2, 3, 1, 1);
            selectorButton.OnClicked += selectorButton_OnClicked;

            Label companyColorLabel = new Label(GUI, Layout, "Color", GUI.DefaultFont);
            Layout.SetComponentPosition(companyColorLabel, 0, 4, 1, 1);

            CompanyColorPanel = new ColorPanel(GUI, Layout) {CurrentColor = DefaultColor};
            Layout.SetComponentPosition(CompanyColorPanel, 1, 4, 1, 1);
            CompanyColorPanel.OnClicked += CompanyColorPanel_OnClicked;

            Button apply = new Button(GUI, Layout, "Continue", GUI.DefaultFont, Button.ButtonMode.ToolButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.Check));
            Layout.SetComponentPosition(apply, 2, 9, 1, 1);

            apply.OnClicked += apply_OnClicked;

            Button back = new Button(GUI, Layout, "Back", GUI.DefaultFont, Button.ButtonMode.ToolButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.LeftArrow));
            Layout.SetComponentPosition(back, 1, 9, 1, 1);

            back.OnClicked += back_onClicked;

            base.OnEnter();
        }
 public static void DrawQuad(GridLayout grid, Vector3Int position, Color color)
 {
     BeginQuads(color);
     DrawQuadBatched(grid, position);
     EndQuads();
 }
Esempio n. 31
0
        public override void Pick(GridLayout gridLayout, GameObject brushTarget, BoundsInt position, Vector3Int pickStart)
        {
            // Do standard pick if user has selected a custom bounds
            if (position.size.x > 1 || position.size.y > 1 || position.size.z > 1)
            {
                base.Pick(gridLayout, brushTarget, position, pickStart);
                return;
            }

            Tilemap tilemap = brushTarget.GetComponent <Tilemap>();

            if (tilemap == null)
            {
                return;
            }

            Reset();

            // Determine size of picked locations based on gap and limit
            Vector3Int limitOrigin = position.position - limit;
            Vector3Int limitSize   = Vector3Int.one + limit * 2;
            BoundsInt  limitBounds = new BoundsInt(limitOrigin, limitSize);
            BoundsInt  pickBounds  = new BoundsInt(position.position, Vector3Int.one);

            m_VisitedLocations.SetAll(false);
            m_VisitedLocations.Set(GetIndex(position.position, limitOrigin, limitSize), true);
            m_NextPosition.Clear();
            m_NextPosition.Push(position.position);

            while (m_NextPosition.Count > 0)
            {
                Vector3Int next = m_NextPosition.Pop();
                if (tilemap.GetTile(next) != null)
                {
                    Encapsulate(ref pickBounds, next);
                    BoundsInt gapBounds = new BoundsInt(next - gap, Vector3Int.one + gap * 2);
                    foreach (var gapPosition in gapBounds.allPositionsWithin)
                    {
                        if (!limitBounds.Contains(gapPosition))
                        {
                            continue;
                        }
                        int index = GetIndex(gapPosition, limitOrigin, limitSize);
                        if (!m_VisitedLocations.Get(index))
                        {
                            m_NextPosition.Push(gapPosition);
                            m_VisitedLocations.Set(index, true);
                        }
                    }
                }
            }

            UpdateSizeAndPivot(pickBounds.size, position.position - pickBounds.position);

            foreach (Vector3Int pos in pickBounds.allPositionsWithin)
            {
                Vector3Int brushPosition = new Vector3Int(pos.x - pickBounds.x, pos.y - pickBounds.y, pos.z - pickBounds.z);
                if (m_VisitedLocations.Get(GetIndex(pos, limitOrigin, limitSize)))
                {
                    PickCell(pos, brushPosition, tilemap);
                }
            }
        }
 public static void DrawMarquee(GridLayout grid, Vector3Int position, Color color)
 {
     BeginMarquee(color);
     DrawMarqueeBatched(grid, position);
     EndMarquee();
 }
Esempio n. 33
0
        public override Android.Views.View GetSampleContent(Android.Content.Context context)
        {
            LayoutInflater layoutInflater = LayoutInflater.From(context);

            view       = layoutInflater.Inflate(Resource.Layout.TicketBooking, null);
            gridlayout = (GridLayout)view;

            maps = new SfMaps(context);
            ShapeFileLayer layer = new ShapeFileLayer();

            layer.ShowItems       = true;
            layer.EnableSelection = true;
            layer.Uri             = "Custom.shp";
            layer.DataSource      = GetDataSource();
            layer.SelectionMode   = SelectionMode.Multiple;
            layer.ShapeSettings.SelectedShapeColor = Color.Rgb(98, 170, 95);
            layer.GeometryType = GeometryType.Points;

            layer.ShapeSelected += (object sender, ShapeFileLayer.ShapeSelectedEventArgs e) =>
            {
                JSONObject data = (JSONObject)e.P0;



                if (data != null)
                {
                    UpdateSelection();
                }
            };

            layer.SelectedItems.CollectionChanged += SelectedItems_CollectionChanged;

            layer.ShapeSettings.ShapeStrokeThickess = 2;
            SetColorMapping(layer.ShapeSettings);
            layer.ShapeSettings.ShapeColorValuePath = "SeatNumber";
            layer.ShapeIdTableField = "seatno";
            layer.ShapeIdPath       = "SeatNumber";


            maps.Layers.Add(layer);
            maps.SetPadding(10, 0, 0, 0);

            linearLayoutChild = (LinearLayout)view.FindViewById(Resource.Id.linear);
            ClearSelection    = (Button)view.FindViewById(Resource.Id.ClearSelection);

            ClearSelection.Click += (object sender, EventArgs e) =>
            {
                if ((maps.Layers[0] as ShapeFileLayer).SelectedItems.Count != 0)
                {
                    (maps.Layers[0] as ShapeFileLayer).SelectedItems.Clear();
                    SelectedLabel.Text      = "";
                    SelectedLabelCount.Text = "" + (maps.Layers[0] as ShapeFileLayer).SelectedItems.Count;
                    //ClearSelection.Visibility = ViewStates.Invisible;
                    ClearSelection.Alpha   = 0.5f;
                    ClearSelection.Enabled = false;
                }
            };



            SelectedLabel      = (TextView)view.FindViewById(Resource.Id.SelectedLabel);
            SelectedLabelCount = (TextView)view.FindViewById(Resource.Id.SelectedLabelCount);

            linearLayoutChild.AddView(maps);


            return(gridlayout);
        }
 public static void DrawLine(GridLayout grid, Vector3Int from, Vector3Int to, Color color)
 {
     BeginLines(color);
     DrawLineBatched(grid, from, to);
     EndLines();
 }
Esempio n. 35
0
 public override void Erase(GridLayout grid, GameObject layer, Vector3Int position)
 {
     BoxErase(grid, layer, new BoundsInt(position, Vector3Int.one));
 }
 public static void DrawLineBatched(GridLayout grid, Vector3Int from, Vector3Int to)
 {
     GL.Vertex(grid.GetComponent <Grid>().GetCellCenterWorld(from));
     GL.Vertex(grid.GetComponent <Grid>().GetCellCenterWorld(to));
 }
Esempio n. 37
0
		public override void Destroy ()
		{
			sfGrid.AutoGeneratingColumn -= GridAutoGenerateColumn;
			sfGrid.Dispose ();
			conditionDropdown = null;
			columnDropdown = null;
			filterText = null;
			columnTextView = null;
			conditionTextView = null;
			sfGrid = null;
			viewModel = null;
			condtionAdapter = null; 
			gridlayout.RemoveAllViews();
			gridlayout = null;
		}
Esempio n. 38
0
 public TabButton()
 {
     GridLayout.SetHorizontalStretch(this, GridLayout.StretchFlags.ExpandAndFill);
 }
Esempio n. 39
0
 /// <summary>
 /// Move the position of a node to the direction.
 /// </summary>
 /// <param name="node">a node, to be moved.</param>
 /// <param name="direction">direction, to be moved to.</param>
 /// <param name="posMatrix">a matrix of position in grid coordinate system</param>
 private void MoveNode(EcellObject node, GridLayout.Direction direction, bool[,] posMatrix)
 {
     if (posMatrix != null)
         posMatrix[(int)node.X, (int)node.Y] = false;
     switch (direction)
     {
         case Direction.LeftUpper:
             node.X = node.X - 1;
             node.Y = node.Y - 1;
             break;
         case Direction.Upper:
             node.Y = node.Y - 1;
             break;
         case Direction.RightUpper:
             node.X = node.X + 1;
             node.Y = node.Y - 1;
             break;
         case Direction.Right:
             node.X = node.X + 1;
             break;
         case Direction.RightLower:
             node.X = node.X + 1;
             node.Y = node.Y + 1;
             break;
         case Direction.Lower:
             node.Y = node.Y + 1;
             break;
         case Direction.LeftLower:
             node.X = node.X - 1;
             node.Y = node.Y + 1;
             break;
         case Direction.Left:
             node.X = node.X - 1;
             break;
     }
     if (posMatrix != null)
         posMatrix[(int)node.X, (int)node.Y] = true;
 }
Esempio n. 40
0
 private void initGUI()
 {
     try
     {
         setPreferredSize(new Dimension(400, 300));
         {
             generalPanel = new JPanel();
             FlowLayout generalPanelLayout = new FlowLayout();
             generalPanelLayout.setAlignment(FlowLayout.LEFT);
             generalPanel.setLayout(generalPanelLayout);
             this.addTab("General", null, generalPanel, null);
             {
                 resolutionPanel = new JPanel();
                 generalPanel.add(resolutionPanel);
                 FlowLayout resolutionPanelLayout = new FlowLayout();
                 resolutionPanel.setLayout(resolutionPanelLayout);
                 resolutionPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED), "Resolution", TitledBorder.LEADING, TitledBorder.TOP));
                 {
                     resolutionCheckBox = new JCheckBox();
                     resolutionPanel.add(resolutionCheckBox);
                     resolutionCheckBox.setText("Override");
                 }
                 {
                     jLabel1 = new JLabel();
                     resolutionPanel.add(jLabel1);
                     jLabel1.setText("Image Width:");
                 }
                 {
                     resolutionXTextField = new JTextField();
                     resolutionPanel.add(resolutionXTextField);
                     resolutionXTextField.setText("640");
                     resolutionXTextField.setPreferredSize(new java.awt.Dimension(50, 20));
                 }
                 {
                     jLabel2 = new JLabel();
                     resolutionPanel.add(jLabel2);
                     jLabel2.setText("Image Height:");
                 }
                 {
                     resolutionYTextField = new JTextField();
                     resolutionPanel.add(resolutionYTextField);
                     resolutionYTextField.setText("480");
                     resolutionYTextField.setPreferredSize(new java.awt.Dimension(50, 20));
                 }
             }
             {
                 threadsPanel = new JPanel();
                 generalPanel.add(threadsPanel);
                 threadsPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED), "Threads", TitledBorder.LEADING, TitledBorder.TOP));
                 {
                     threadCheckBox = new JCheckBox();
                     threadsPanel.add(threadCheckBox);
                     threadCheckBox.setText("Use All Processors");
                 }
                 {
                     jLabel3 = new JLabel();
                     threadsPanel.add(jLabel3);
                     jLabel3.setText("Threads:");
                 }
                 {
                     threadTextField = new JTextField();
                     threadsPanel.add(threadTextField);
                     threadTextField.setText("1");
                     threadTextField.setPreferredSize(new java.awt.Dimension(50, 20));
                 }
             }
         }
         {
             rendererPanel = new JPanel();
             FlowLayout rendererPanelLayout = new FlowLayout();
             rendererPanelLayout.setAlignment(FlowLayout.LEFT);
             rendererPanel.setLayout(rendererPanelLayout);
             this.addTab("Renderer", null, rendererPanel, null);
             {
                 defaultRendererRadioButton = new JRadioButton();
                 rendererPanel.add(defaultRendererRadioButton);
                 defaultRendererRadioButton.setText("Default Renderer");
             }
             {
                 bucketRendererPanel = new JPanel();
                 BoxLayout bucketRendererPanelLayout = new BoxLayout(bucketRendererPanel, javax.swing.BoxLayout.Y_AXIS);
                 bucketRendererPanel.setLayout(bucketRendererPanelLayout);
                 rendererPanel.add(bucketRendererPanel);
                 bucketRendererPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(BevelBorder.LOWERED), "Bucket Renderer", TitledBorder.LEADING, TitledBorder.TOP));
                 {
                     bucketRendererRadioButton = new JRadioButton();
                     bucketRendererPanel.add(bucketRendererRadioButton);
                     bucketRendererRadioButton.setText("Enable");
                 }
                 {
                     samplingPanel = new JPanel();
                     GridLayout samplingPanelLayout = new GridLayout(2, 2);
                     samplingPanelLayout.setColumns(2);
                     samplingPanelLayout.setHgap(5);
                     samplingPanelLayout.setVgap(5);
                     samplingPanelLayout.setRows(2);
                     samplingPanel.setLayout(samplingPanelLayout);
                     bucketRendererPanel.add(samplingPanel);
                     {
                         jLabel5 = new JLabel();
                         samplingPanel.add(jLabel5);
                         jLabel5.setText("Min:");
                     }
                     {
                         ComboBoxModel minSamplingComboBoxModel = new DefaultComboBoxModel(new string[] {
                             "Item One", "Item Two" });
                         minSamplingComboBox = new JComboBox();
                         samplingPanel.add(minSamplingComboBox);
                         minSamplingComboBox.setModel(minSamplingComboBoxModel);
                     }
                     {
                         jLabel6 = new JLabel();
                         samplingPanel.add(jLabel6);
                         jLabel6.setText("Max:");
                     }
                     {
                         ComboBoxModel maxSamplingComboxBoxModel = new DefaultComboBoxModel(new string[] {
                             "Item One", "Item Two" });
                         maxSamplingComboxBox = new JComboBox();
                         samplingPanel.add(maxSamplingComboxBox);
                         maxSamplingComboxBox.setModel(maxSamplingComboxBoxModel);
                     }
                 }
             }
         }
     }
     catch (Exception e)
     {
         e.printStackTrace();
     }
 }
Esempio n. 41
0
		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			// Set our view from the "main" layout resource
			SetContentView (Resource.Layout.Main);
			StartService (new Intent(Application.Context, typeof(NotificationService)));


			//Our App starts here
			ImageButton setButton = FindViewById<ImageButton> (Resource.Id.set_button);
			lvlIndicator = FindViewById<TextView> (Resource.Id.lvlVal);
			state = FindViewById<TextView> (Resource.Id.stateTxt);
			region = FindViewById<TextView> (Resource.Id.regionTxt);
			mainLayout = FindViewById<GridLayout> (Resource.Id.gridLayout1);
			loadingText = FindViewById<TextView> (Resource.Id.loadText);

			string stateString = string.Format ("State: ");
			state.Text = stateString;

			//TODO: Might Eliminate settings button
			setButton.Click += delegate {
				var intent = new Intent(this, typeof(SettingsActivity));
				StartActivityForResult(intent, 0); //Request result from settings page to set main page
			};

			//Location Service
			//InitLocationManager will initialize the service (set criteria fine or coarse, getproviders based on criteria)
			//Then the location will always be updated onlocationchange
			InitLocationManager ();
//			_locationManager.RequestLocationUpdates (_locationProvider, 60*60*1000, 0, this);
		}
Esempio n. 42
0
        public GameOverMenu(Background bg) : base(bg, "dialog")
        {
            var ui = new GridLayout(new Rectangle(Point.Zero, Size.ToPoint()), 12)
            {
                Scale = SkidiBirdGame.Scale,
                Rows =
                {
                    new Row(40)
                    {
                        new HColumn(1f)
                        {
                            VerticalAlign = VerticalAlign.Top,
                            Items = {Label.FromResource("GameOver")}
                        }
                    },
                    new Row(50)
                    {
                        new HColumn(.5f)
                        {
                            HorizontalAlign = HorizontalAlign.Right,
                            Items = {Label.FromResource("Score")}
                        },
                        new HColumn(-1f)
                        {
                            (_scoresLb = new Label("0"))
                        }
                    },
                    new Row(50)
                    {
                        new HColumn(.5f)
                        {
                            HorizontalAlign = HorizontalAlign.Right,
                            Items = {Label.FromResource("HighScore")}
                        },
                        new HColumn(-1f)
                        {
                            (_highScoresLb = new Label("0"))
                        }
                    },
                    new Row(-1)
                    {
                        new HColumn(1f)
                        {
                            Spacing = 24,
                            Items = {
                                new Buttons.SmallButton("ic_restart", RestartClick),
                                new Buttons.SmallButton("ic_exit", ExitClick)
                            }
                        }
                    }
                }
            };

            Add(ui);
        }
Esempio n. 43
0
 public override void FloodFill(GridLayout gridLayout, GameObject brushTarget, Vector3Int position)
 {
     Debug.LogWarning("FloodFill not supported");
 }
Esempio n. 44
0
        public static MvcHtmlString AppNormalGridFor(this HtmlHelper htmlHelper, UrlHelper urlHelper, string pageId, string gridId, string url, GridLayout gridLayout, int gridHeight, int gridWidth)
        {
            string str = EditGrid(urlHelper, pageId, gridId, url, gridLayout, "", "", false, false, gridHeight, gridWidth, false, "", false, "", true, false);

            return(MvcHtmlString.Create(str));
        }
Esempio n. 45
0
        public static void DrawAllGradients()
        {
            var app     = SampleEnvironment.Application;
            var docs    = app.Documents;
            var stencil = docs.OpenStencil("basic_u.vss");
            var master  = stencil.Masters["Rectangle"];
            var page    = SampleEnvironment.Application.ActiveDocument.Pages.Add();

            int num_cols = 7;
            int num_rows = 7;

            var page_size = new VA.Drawing.Size(5, 5);

            SampleEnvironment.SetPageSize(page, page_size);

            var lowerleft        = new VA.Drawing.Point(0, 0);
            var actual_page_size = SampleEnvironment.GetPageSize(page);
            var page_rect        = new VA.Drawing.Rectangle(lowerleft, actual_page_size);

            var layout = new GridLayout(num_cols, num_rows, new VA.Drawing.Size(1, 1), master);

            layout.RowDirection = RowDirection.TopToBottom;
            layout.Origin       = page_rect.UpperLeft;
            layout.CellSpacing  = new VA.Drawing.Size(0, 0);
            layout.PerformLayout();

            int max_grad_id = 40;
            int n           = 0;

            foreach (var node in layout.Nodes)
            {
                int grad_id = n % max_grad_id;
                node.Text = grad_id.ToString();
                n++;
            }

            layout.Render(page);

            var color1 = new VA.Drawing.ColorRGB(0xffdddd);
            var color2 = new VA.Drawing.ColorRGB(0x00ffff);

            var format = new VA.Shapes.ShapeFormatCells();

            var writer = new SidSrcWriter();

            string color1_formula = color1.ToFormula();
            string color2_formula = color2.ToFormula();

            n = 0;

            foreach (var node in layout.Nodes)
            {
                short shapeid = node.ShapeID;
                int   grad_id = n % max_grad_id;

                format.FillPattern    = grad_id;
                format.FillForeground = color1_formula;
                format.FillBackground = color2_formula;
                format.LinePattern    = 0;
                format.LineWeight     = 0;
                format.SetFormulas(shapeid, writer);

                n++;
            }

            writer.Commit(page);

            var bordersize = new VA.Drawing.Size(1, 1);

            page.ResizeToFitContents(bordersize);
        }
Esempio n. 46
0
 private void EraseCell(GridLayout grid, Vector3Int position, Transform parent)
 {
     ClearSceneCell(grid, parent, position);
 }
		protected override async void OnCreate (Bundle bundle)
		{
			//RequestWindowFeature(WindowFeatures.NoTitle);
			base.OnCreate (bundle);

			//CREAMOS EL OBJETO QUE VA A LEER/ESCRIBIR LAS PREFERENCIAS DEL USUARIO
			var prefs = this.GetSharedPreferences("RunningAssistant.preferences", FileCreationMode.Private);

			//ASIGNAMOS EL DICCIONARIO

			valores = new ContentValues ();
			source = 1;

			negocioid = Intent.GetStringExtra ("id");

			//CREAMOS EL OBJETO DEL OBJETO (lel) que va a editar las preferencias
			var editor = prefs.Edit ();
			userid = prefs.GetString("id", null);

			//SETEAMOS LA VISTA A CONTROLAR
			SetContentView(Resource.Layout.perfil_premium);

			imgnegocioprev = FindViewById<GridLayout> (Resource.Id.imgnegocioprev);
			masimagenesnegocio = FindViewById<TextView> (Resource.Id.masimagenesnegocio);
			imagennegocio = FindViewById <Button> (Resource.Id.imagennegocio);
			imagencamaranegocio = FindViewById<Button> (Resource.Id.imagencamaranegocio);
			enviarimgneg = FindViewById<Button> (Resource.Id.enviarimgneg);
			LinearLayout containernegocio = FindViewById<LinearLayout> (Resource.Id.containernegocio);
			LinearLayout waitlayout = FindViewById <LinearLayout> (Resource.Id.waitlayout);

			ubicacionbtn = FindViewById<Button> (Resource.Id.ubicacionbtn);
			descripcionbtn = FindViewById<Button> (Resource.Id.descripcionbtn);
			contactobtn = FindViewById<Button> (Resource.Id.contactobtn);

			ubicacionlayout = FindViewById<LinearLayout> (Resource.Id.ubicacionlayout);
			descripcionlayout = FindViewById<LinearLayout> (Resource.Id.descripcionlayout);
			contactolayout = FindViewById<LinearLayout> (Resource.Id.contactolayout);

			callnow = FindViewById<Button> (Resource.Id.callnow);

		



			mToolbar = FindViewById<SupportToolBar> (Resource.Id.toolbar);
			mScrollView = FindViewById<ScrollView> (Resource.Id.scrollView);

			SetSupportActionBar (mToolbar);
			//ESTA ES LA FLECHA PARA ATRÁS
			SupportActionBar.SetHomeAsUpIndicator (Resource.Drawable.ic_arrow_back);
			SupportActionBar.SetDisplayHomeAsUpEnabled (true);
			//SupportActionBar.SetHomeButtonEnabled (true);

			layoutdejaimagenes = FindViewById<LinearLayout> (Resource.Id.layoutdejaimagenes);

			Point size = new Point ();
			Display display = WindowManager.DefaultDisplay;
			display.GetSize (size);
			mScreenHeight = size.Y;

			mScrollView.ViewTreeObserver.AddOnScrollChangedListener (this);

			//despues del show del action var, vamos a obtener el negocio

			SupportActionBar.Title = Intent.GetStringExtra("nombre");

			portada = FindViewById<ImageView> (Resource.Id.coverneg);

			TextView abiertocerrado = FindViewById<TextView>(Resource.Id.abiertocerrado);

			bounce = AnimationUtils.LoadAnimation (Application.Context, Resource.Animation.bounce);
			flip = AnimationUtils.LoadAnimation (Application.Context, Resource.Animation.flip);
			floatbounce = AnimationUtils.LoadAnimation (Application.Context, Resource.Animation.floatbounce);

			idres=Intent.GetStringExtra ("id");
			titulores = Intent.GetStringExtra ("nombre");

			//BOTONES DE RESEÑA
			Button enviarrev = FindViewById<Button> (Resource.Id.enviarrev);
			Button imagenrev = FindViewById<Button> (Resource.Id.imagenrev);
			Button imagenrev2 = FindViewById<Button> (Resource.Id.imagenrev2);
			Button imagencamara = FindViewById<Button> (Resource.Id.imagencamara);


			masimagenes = FindViewById<TextView> (Resource.Id.masimagenes);

			imgUri = null;
			apath = "";


			revItems = new List<Review>();

			//fuente
			Typeface font = Typeface.CreateFromAsset(Assets, "Fonts/fa.ttf");


			//COORDINATOR LAYOUT:
			var fab = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition);

			Button addimg = FindViewById<Button> (Resource.Id.addimg);
			Button addcomment = FindViewById<Button> (Resource.Id.addcomment);
			Button addtip = FindViewById<Button> (Resource.Id.addtip);
			Button enviarmensaje = FindViewById<Button> (Resource.Id.enviarmensaje);
			Button addlike = FindViewById<Button> (Resource.Id.addlike);
			fossbytes = new List<byte[]>();

			deleteimgnegocio = FindViewById<Button> (Resource.Id.deleteimgnegocio);

			addimg.SetTypeface(font, TypefaceStyle.Normal);
			addcomment.SetTypeface(font, TypefaceStyle.Normal);
			addtip.SetTypeface(font, TypefaceStyle.Normal);
			enviarmensaje.SetTypeface(font, TypefaceStyle.Normal);
			addlike.SetTypeface(font, TypefaceStyle.Normal);

			TextView corazonlikes = FindViewById<TextView> (Resource.Id.corazonlikes);

			TextView alikes = FindViewById<TextView> (Resource.Id.alikes);
			TextView likes = FindViewById<TextView> (Resource.Id.likes);
			TextView gustalikes = FindViewById<TextView> (Resource.Id.gustalikes);


			corazonlikes.SetTypeface(font, TypefaceStyle.Normal);
			alikes.SetTypeface(font, TypefaceStyle.Normal);
			likes.SetTypeface(font, TypefaceStyle.Normal);
			gustalikes.SetTypeface(font, TypefaceStyle.Normal);
			callnow.SetTypeface(font, TypefaceStyle.Normal);


			LinearLayout layoutdiascontainer = FindViewById<LinearLayout> (Resource.Id.layoutdiascontainer);
			//layoutdiascontainer.Animate().TranslationY(0);

			ScrollView scrollview = FindViewById<ScrollView> (Resource.Id.scrollView);

			ProgressBar waitpb = FindViewById<ProgressBar> (Resource.Id.waitpb);

			deleteimgrev = FindViewById<Button> (Resource.Id.deleteimgrev);


			try{
				negocio = await plifserver.FetchWeatherAsync ("http://plif.mx/mobile/get_negocio?id="+Intent.GetStringExtra("id")+"&uid="+userid);
				objeto = negocio["respuesta"][0]["Data"];

				Log.Debug (tag, "La ruta es: "+objeto["ruta"]);



				if(negocio["respuesta"][0]["0"]["has_like"]=="1"){
					haslike=true;
				}else{
					haslike=false;
				}

				if (haslike) {
					addlike.Text = GetString (Resource.String.heart);
				} else {
					addlike.Text = GetString (Resource.String.heartempty);
				}

				numlikes=objeto["likes"];


				if (objeto["ruta"] == null || objeto["ruta"] == "" || objeto["ruta"] == "null") {
					//pon la imagen por defecto
					portada.SetImageResource (Resource.Drawable.dcover);
					Log.Debug (tag, "No hay ruta!");
				} else {
					//TENEMOS QUE VERIFICAR SI LA IMAGEN ES DE GOOGLE O DE NOSOTROS!!!
					string ruta=objeto["ruta"];
					string first=ruta[0].ToString();

					if(first=="u" || first=="U"){
						//Toast.MakeText (Application.Context, "EMPIEZA CON U!!!", ToastLength.Long).Show ();
						ruta=extra+ruta;
					}else{
						//no hagas nada, la imagen es de google
					}

					Koush.UrlImageViewHelper.SetUrlDrawable (portada, ruta, Resource.Drawable.dcover);

				}//TERMINA SI LA IMAGEN NO ES NULL

				//Ponemos el titulo
				TextView titulo = FindViewById<TextView> (Resource.Id.titulo);
				titulo.Text=Intent.GetStringExtra("nombre");
				TextView numestrellas = FindViewById<TextView> (Resource.Id.numestrellas);

				//Ponemos las estrellas
				ImageView estrellas = FindViewById<ImageView> (Resource.Id.estrellas);

				switch (Intent.GetStringExtra("calificacion")) {

				case "0":
				case "":
				case "null":
				case null:
					numestrellas.Text="0.0";
					break;

				case "1":
					numestrellas.Text="1.0";
					break;

				case "2":
					numestrellas.Text="2.0";
					break;
				case "3":
					numestrellas.Text="3.0";
					break;
				
				case "4":
					numestrellas.Text="4.0";
					break;

				case "5":
					numestrellas.Text="5.0";
					break;


				default:
					numestrellas.Text="0.0";
					break;
				}

				//categoria y subcategoria
				TextView categoria = FindViewById<TextView> (Resource.Id.categoria);
				TextView subcategoria = FindViewById<TextView> (Resource.Id.subcategoria);
				TextView guioncat = FindViewById<TextView> (Resource.Id.guioncat);

				categoria.Text=objeto["categoria"];

				if(objeto["propietario"]==null || objeto["propietario"]=="null"){
					propietario="0";
				}else{
					propietario=objeto["propietario"];
				}

				if(objeto["subcategoria"]=="" || objeto["subcategoria"]==null || objeto["subcategoria"]=="null"){
					subcategoria.Text="";
					guioncat.Text="";
				}else{
					subcategoria.Text=objeto["subcategoria"];
				}

				//likes
				likes.Text=objeto["likes"]+" Personas";

				//mapa?
				try{
					mapFrag = (MapFragment)FragmentManager.FindFragmentById(Resource.Id.map);
					map = mapFrag.Map;

					LatLng location = new LatLng(objeto["geo_lat"], objeto["geo_long"]);
					CameraPosition.Builder builder = CameraPosition.InvokeBuilder();
					builder.Target(location);
					builder.Zoom(16);
					//builder.Bearing(155);
					//builder.Tilt(65);
					CameraPosition cameraPosition = builder.Build();
					CameraUpdate cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition);



					if (map != null)
					{
						map.MapType = GoogleMap.MapTypeNormal;

						MarkerOptions markerOpt1 = new MarkerOptions();
						markerOpt1.SetPosition(new LatLng(objeto["geo_lat"], objeto["geo_long"]));
						markerOpt1.SetTitle(objeto["titulo"]);
						markerOpt1.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pliflocation3));
						markerOpt1.Draggable(true);
						map.AddMarker(markerOpt1);
						map.MoveCamera(cameraUpdate);




					}
				}catch(Exception ex){
					Log.Debug (tag, "GMAPS ERROR:"+ex);
				}


				//direccion
				TextView callenum = FindViewById<TextView> (Resource.Id.callenum);
				callenum.Text=objeto["geo_calle"]+" "+objeto["geo_numero"];
				TextView colonia = FindViewById<TextView> (Resource.Id.colonia);
				colonia.Text=objeto["geo_colonia"];
				TextView regpais = FindViewById<TextView> (Resource.Id.regpais);
				regpais.Text=objeto["geo_estado"]+", "+objeto["geo_pais"];

				//acerca de este negocio
				TextView mapmarker1 = FindViewById<TextView> (Resource.Id.sobreeste);
				mapmarker1.SetTypeface(font, TypefaceStyle.Normal);

				TextView descripcion = FindViewById<TextView> (Resource.Id.descripcion);
				string desc=objeto["descripcion"];

				descripcion.Text=System.Net.WebUtility.HtmlDecode(desc);
				descripcion.Visibility=ViewStates.Gone;

				WebView descweb = FindViewById<WebView> (Resource.Id.descweb);
				descweb.Settings.JavaScriptEnabled=true;
				string div1="<div style=\"color: #FFFFFF\">";
				string div2="</div>";
				descweb.LoadDataWithBaseURL("", div1+desc+div2, "text/html", "UTF-8", "");
				descweb.SetBackgroundColor(Color.ParseColor("#343A41"));

				//telefono
				TextView webico =FindViewById<TextView> (Resource.Id.webico);
				TextView telico =FindViewById<TextView> (Resource.Id.telico);

				telefono= FindViewById<TextView> (Resource.Id.telefono);
				telico.SetTypeface(font, TypefaceStyle.Normal);
				telefono.Text= objeto["telefono"]+" ";


				//webpage
				TextView web = FindViewById<TextView> (Resource.Id.pagweb);
				webico.SetTypeface(font, TypefaceStyle.Normal);
				web.Text=objeto["website"]+" ";

				//Horarios
				TextView horarios=FindViewById<TextView> (Resource.Id.horarios);
				horarios.SetTypeface(font, TypefaceStyle.Normal);

				abiertocerrado = FindViewById<TextView>(Resource.Id.abiertocerrado);

				LinearLayout lunescontainer = FindViewById<LinearLayout> (Resource.Id.lunescontainer);
				TextView lunes = FindViewById<TextView>(Resource.Id.lunes);
				TextView luneshora = FindViewById<TextView>(Resource.Id.luneshora);

				LinearLayout martescontainer = FindViewById<LinearLayout> (Resource.Id.martescontainer);
				TextView martes = FindViewById<TextView>(Resource.Id.martes);
				TextView marteshora = FindViewById<TextView>(Resource.Id.marteshora);

				LinearLayout miercolescontainer = FindViewById<LinearLayout> (Resource.Id.miercolescontainer);
				TextView miercoles = FindViewById<TextView>(Resource.Id.miercoles);
				TextView miercoleshora = FindViewById<TextView>(Resource.Id.miercoleshora);

				LinearLayout juevescontainer = FindViewById<LinearLayout> (Resource.Id.juevescontainer);
				TextView jueves = FindViewById<TextView>(Resource.Id.jueves);
				TextView jueveshora = FindViewById<TextView>(Resource.Id.jueveshora);

				LinearLayout viernescontainer = FindViewById<LinearLayout> (Resource.Id.viernescontainer);
				TextView viernes = FindViewById<TextView>(Resource.Id.viernes);
				TextView vierneshora = FindViewById<TextView>(Resource.Id.vierneshora);

				LinearLayout sabadocontainer = FindViewById<LinearLayout> (Resource.Id.sabadocontainer);
				TextView sabado = FindViewById<TextView>(Resource.Id.sabado);
				TextView sabadohora = FindViewById<TextView>(Resource.Id.sabadohora);

				LinearLayout domingocontainer = FindViewById<LinearLayout> (Resource.Id.domingocontainer);
				TextView domingo = FindViewById<TextView>(Resource.Id.domingo);
				TextView domingohora = FindViewById<TextView>(Resource.Id.domingohora);

				//poner los horarios donde corresponde
				if(objeto["lunes_a"]=="" || objeto["lunes_c"]==""){
					lunescontainer.Visibility=ViewStates.Gone;
				}else{
					if(objeto["lunes_a"]=="Cerrado" || objeto["lunes_c"]=="Cerrado"){
						luneshora.Text="Cerrado";
					}else{
						luneshora.Text=objeto["lunes_a"]+" - "+objeto["lunes_c"];
					}

				}


				if(objeto["martes_a"]=="" || objeto["martes_c"]==""){
					martescontainer.Visibility=ViewStates.Gone;
				}else{
					if(objeto["martes_a"]=="Cerrado" || objeto["martes_c"]=="Cerrado"){
						marteshora.Text="Cerrado";
					}else{
						marteshora.Text=objeto["martes_a"]+" - "+objeto["martes_c"];
					}

				}

				if(objeto["miercoles_a"]=="" || objeto["miercoles_c"]==""){
					miercolescontainer.Visibility=ViewStates.Gone;
				}else{
					if(objeto["miercoles_a"]=="Cerrado" || objeto["miercoles_c"]=="Cerrado"){
						miercoleshora.Text="Cerrado";
					}else{
						miercoleshora.Text=objeto["miercoles_a"]+" - "+objeto["miercoles_c"];
					}

				}

				if(objeto["jueves_a"]=="" || objeto["jueves_c"]==""){
					juevescontainer.Visibility=ViewStates.Gone;
				}else{
					if(objeto["jueves_a"]=="Cerrado" || objeto["jueves_c"]=="Cerrado"){
						jueveshora.Text="Cerrado";
					}else{
						jueveshora.Text=objeto["jueves_a"]+" - "+objeto["jueves_c"];
					}

				}

				if(objeto["viernes_a"]=="" || objeto["viernes_c"]==""){
					viernescontainer.Visibility=ViewStates.Gone;
				}else{
					if(objeto["viernes_a"]=="Cerrado" || objeto["viernes_c"]=="Cerrado"){
						vierneshora.Text="Cerrado";
					}else{
						vierneshora.Text=objeto["viernes_a"]+" - "+objeto["viernes_c"];
					}

				}

				if(objeto["sabado_a"]=="" || objeto["sabado_c"]==""){
					sabadocontainer.Visibility=ViewStates.Gone;
				}else{
					if(objeto["sabado_a"]=="Cerrado" || objeto["sabado_c"]=="Cerrado"){
						sabadohora.Text="Cerrado";
					}else{
						sabadohora.Text=objeto["sabado_a"]+" - "+objeto["sabado_c"];
					}

				}

				if(objeto["domingo_a"]=="" || objeto["domingo_c"]==""){
					domingocontainer.Visibility=ViewStates.Gone;
				}else{
					if(objeto["domingo_a"]=="Cerrado" || objeto["domingo_c"]=="Cerrado"){
						domingohora.Text="Cerrado";
					}else{
						domingohora.Text=objeto["domingo_a"]+" - "+objeto["domingo_c"];
					}

				}







				//vemos que dia es hoy y lo ponemos en verde
				DateTime localDate = DateTime.Now;
				int dia=(int)localDate.DayOfWeek; 
				//1 es lunes, 7 es domingo y así

				string hoy_abre="";
				string hoy_cierra="";

				switch(dia){
				case 1:
					lunes.SetTextColor(Android.Graphics.Color.ParseColor("#FFFFFF"));
					luneshora.SetTextColor(Android.Graphics.Color.ParseColor("#FFFFFF"));
					hoy_abre = objeto ["lunes_a"];
					hoy_cierra = objeto ["lunes_c"];
					break;

				case 2:
					martes.SetTextColor(Android.Graphics.Color.ParseColor("#FFFFFF"));
					marteshora.SetTextColor(Android.Graphics.Color.ParseColor("#FFFFFF"));
					hoy_abre = objeto ["martes_a"];
					hoy_cierra = objeto ["martes_c"];
					break;

				case 3:
					miercoles.SetTextColor(Android.Graphics.Color.ParseColor("#FFFFFF"));
					miercoleshora.SetTextColor(Android.Graphics.Color.ParseColor("#FFFFFF"));
					hoy_abre = objeto ["miercoles_a"];
					hoy_cierra = objeto ["miercoles_c"];
					break;

				case 4:
					jueves.SetTextColor(Android.Graphics.Color.ParseColor("#FFFFFF"));
					jueveshora.SetTextColor(Android.Graphics.Color.ParseColor("#FFFFFF"));
					hoy_abre = objeto ["jueves_a"];
					hoy_cierra = objeto ["jueves_c"];
					break;

				case 5:
					viernes.SetTextColor(Android.Graphics.Color.ParseColor("#FFFFFF"));
					vierneshora.SetTextColor(Android.Graphics.Color.ParseColor("#FFFFFF"));
					hoy_abre = objeto ["viernes_a"];
					hoy_cierra = objeto ["viernes_c"];
					break;

				case 6:
					sabado.SetTextColor(Android.Graphics.Color.ParseColor("#FFFFFF"));
					sabadohora.SetTextColor(Android.Graphics.Color.ParseColor("#FFFFFF"));
					hoy_abre = objeto ["sabado_a"];
					hoy_cierra = objeto ["sabado_c"];
					break;

				case 7:
					domingo.SetTextColor(Android.Graphics.Color.ParseColor("#FFFFFF"));
					domingohora.SetTextColor(Android.Graphics.Color.ParseColor("#FFFFFF"));
					hoy_abre = objeto ["domingo_a"];
					hoy_cierra = objeto ["domingo_c"];
					break;

				default:
					hoy_abre = "cerrado";
					hoy_cierra = "cerrado";
					break;

				}

				if(hoy_abre == "Cerrado" || hoy_cierra=="Cerrado"){
					abiertocerrado.Text="Cerrado por el dia de hoy.";
					abiertocerrado.SetTextColor(Android.Graphics.Color.ParseColor("#C41200"));
				}else{

					if(hoy_abre == "" || hoy_cierra==""){
						abiertocerrado.Text="No disponemos de los horarios para el dia de hoy.";
						abiertocerrado.SetTextColor(Android.Graphics.Color.ParseColor("#C41200"));
					}else{
						//TODO AQUI
						//AQUI HAY QUE VER SI ESTÁ ABIERTO O CERRADO
						DateTime ahora = DateTime.Now;
						DateTime abre = Convert.ToDateTime(hoy_abre);
						DateTime cierra = Convert.ToDateTime(hoy_cierra);
						DateTime cierra2 = DateTime.Now;



						int diasig=DateTime.Compare(abre,cierra);
						//Toast.MakeText (Application.Context, "Cierra primero: "+cierra.ToString(), ToastLength.Long).Show ();

						if(diasig>0){
							//sumale un dia a la hora de cierre
							//Toast.MakeText (Application.Context, "si es mayor!: "+diasig, ToastLength.Long).Show ();
							cierra2=cierra.AddDays(1);
						}else{
							cierra2=cierra;
							//no hagas nada
						}

						int f1=DateTime.Compare(abre, ahora);
						int f2=DateTime.Compare(ahora,cierra2);

						if(f1<0 && f2<0){
							//abierto
							abiertocerrado.Text="Abierto justo ahora!";
							abiertocerrado.SetTextColor(Android.Graphics.Color.ParseColor("#FFFFFF"));
						}else{
							//cerrado
							abiertocerrado.Text="Cerrado ahora";
							abiertocerrado.SetTextColor(Android.Graphics.Color.ParseColor("#C41200"));
						}

					}

				}

				TextView revs_tit= FindViewById<TextView> (Resource.Id.revs_tit);
				revs_tit.SetTypeface(font, TypefaceStyle.Normal);
				containernegocio.Visibility=ViewStates.Visible;
				waitlayout.Visibility=ViewStates.Gone;

				ImageView imgface = FindViewById<ImageView> (Resource.Id.imageface);
				ImageView imgtwitter = FindViewById<ImageView> (Resource.Id.imagetwitter);
				ImageView imggoogle = FindViewById<ImageView> (Resource.Id.imagegoogle);
				ImageView imgplif = FindViewById<ImageView> (Resource.Id.imageplif);

				if (objeto ["facebook"] == "") {
					imgface.Visibility = ViewStates.Gone;
				}

				if (objeto ["twitter"] == "") {
					imgtwitter.Visibility = ViewStates.Gone;
				}

				if (objeto ["google"] == "") {
					imggoogle.Visibility = ViewStates.Gone;
				}


				imgface.Click += (object sender, EventArgs e) => {

					Intent intent = new Intent(Intent.ActionView, Android.Net.Uri.Parse(objeto["facebook"]));
					StartActivity(intent);

				};

				imgtwitter.Click += (object sender, EventArgs e) => {
					Intent intent = new Intent(Intent.ActionView, Android.Net.Uri.Parse(objeto["twitter"]));
					StartActivity(intent);

				};

				imggoogle.Click += (object sender, EventArgs e) => {
					Intent intent = new Intent(Intent.ActionView, Android.Net.Uri.Parse(objeto["google"]));
					StartActivity(intent);

				};

				imgplif.Click += (object sender, EventArgs e) => {
					Intent intent = new Intent(Intent.ActionView, Android.Net.Uri.Parse("http://www.plif.mx/negocio/"+objeto["id"]));
					StartActivity(intent);

				};






			}
			catch(Exception ex){
				Log.Debug (tag, "ERROR FETCHING DATA: "+ex);
				Toast.MakeText (Application.Context, "Ocurrió un error al recuperar la información del negocio", ToastLength.Long).Show ();
				Finish ();
			}

			//aqui en un nuevo try catch, cargamos los comentarios

			ProgressBar waitrv = FindViewById<ProgressBar> (Resource.Id.waitrv);
			try{

				ReviewsObj=await plifserver.FetchWeatherAsync("http://plif.mx/mobile/get_neg_reviews?nid="+Intent.GetStringExtra("id")+"&uid="+userid);
				//Aqui vamos a cargar los reviews con ayuda del adapter

				LinearLayout reviewscont = FindViewById<LinearLayout> (Resource.Id.reviewscont);
				LayoutInflater inflater = LayoutInflater.From(this);

				/*
				for(int i=0; i<=5; i++){
					View view = inflater.Inflate(Resource.Layout.listview_comentarios, reviewscont, false);
					TextView revlikes = view.FindViewById<TextView> (Resource.Id.user_corazonlikes);
					revlikes.SetTypeface(font, TypefaceStyle.Normal);
					reviewscont.AddView(view);
				
				
				}*/

				foreach(JsonObject data in ReviewsObj){
					View row = inflater.Inflate(Resource.Layout.listview_comentarios, reviewscont, false);
					ReviewDetalles holder=null;
					LinearDetalles preholder=null;
					/*TextView revlikes = view.FindViewById<TextView> (Resource.Id.user_corazonlikes);
					revlikes.SetTypeface(font, TypefaceStyle.Normal);*/

					LinearLayout fondo_coment = row.FindViewById<LinearLayout> (Resource.Id.fondo_coment);
					fondo_coment.SetBackgroundResource(Resource.Drawable.fondoinfopremium);


					//EMPIEZA
					//ESTE SETEA LA IMAGEN
					ImageView imagen = row.FindViewById<ImageView> (Resource.Id.user_imagen);

					if (data["i"]["ruta"] == null || data["i"]["ruta"] == "" || data["i"]["ruta"] == "null") {
						//pon la imagen por defecto
						imagen.SetImageResource (Resource.Drawable.noprof);
					} else {
						//TENEMOS QUE VERIFICAR SI LA IMAGEN ES DE GOOGLE O DE NOSOTROS!!!
						string extra="http://plif.mx/";
						string ruta=data["i"]["ruta"];
						string first=ruta[0].ToString();

						if(first=="u" || first=="U"){
							ruta=extra+ruta;
						}else{
							//no hagas nada, la imagen es de google
						}

						Koush.UrlImageViewHelper.SetUrlDrawable (imagen, ruta, Resource.Drawable.bolaplace);

					}//TERMINA SI LA IMAGEN NO ES NULA

					//Ponemos el nombre
					TextView nombre = row.FindViewById<TextView> (Resource.Id.user_nombre);
					nombre.Text = data["u"]["nombre"]+" "+data["u"]["apellidos"];

					nombre.SetTextColor(Color.ParseColor("#FFFFFF"));

					//ESTE SETEA LAS ESTRELLAS DE LA CALIFICACION
					ImageView cali = row.FindViewById<ImageView> (Resource.Id.user_calificacion);

					string cal = data["cm"]["calificacion"];

					switch (cal) {

					case "0":
						cali.SetImageResource (Resource.Drawable.e0);
						break;

					case "":
						cali.SetImageResource (Resource.Drawable.e0);
						break;

					case "null":
						cali.SetImageResource (Resource.Drawable.e0);
						break;

					case null:
						cali.SetImageResource (Resource.Drawable.e0);
						break;

					case "1":
						cali.SetImageResource (Resource.Drawable.e1);
						break;

					case "2":
						cali.SetImageResource (Resource.Drawable.e2);
						break;

					case "3":
						cali.SetImageResource (Resource.Drawable.e3);
						break;

					case "4":
						cali.SetImageResource (Resource.Drawable.e4);
						break;

					case "5":
						cali.SetImageResource (Resource.Drawable.e5);
						break;



					default:
						cali.SetImageResource (Resource.Drawable.e0);
						break;
					}

					//Ponemos el comentario
					TextView comentario = row.FindViewById<TextView> (Resource.Id.user_comentario);
					comentario.Text = data["cm"]["comentario"];

					comentario.SetTextColor(Color.ParseColor("#FFFFFF"));

					//Ponemos la fecha y la hora
					TextView fechahora = row.FindViewById<TextView> (Resource.Id.user_fechahora);
					string fc=data["cm"]["fecha"];
					DateTime dt = System.Convert.ToDateTime(fc);   
					fechahora.Text = dt.ToString ("dd/MM/yyyy H:mm");

					fechahora.SetTextColor(Color.ParseColor("#FFFFFF"));

					//ponemos los likes que tiene
					TextView likescom = row.FindViewById<TextView> (Resource.Id.user_numlikes);
					likescom.Text = " "+data["cm"]["num_likes"];
					likescom.SetTextColor(Color.ParseColor("#FFFFFF"));
					bool haslike = false;
					//averiguamos si el usuario le ha dado like

					try{
						string ulk=" ";
						if(data["user_likes"]["user_likes"]!= null & data["user_likes"]["user_likes"]!= "null"){
							ulk=data["user_likes"]["user_likes"];
							string[] words;
							words = ulk.Split(' ');

							foreach (string word in words)
							{
								if (word == userid) {
									haslike = true;
								}
							}
						}else{
							//no hagas nada!
							Log.Debug("Split","Los likes son nulos");
						}
					}catch(Exception ex){
						Log.Debug("Split","Fue null: "+ex);
					}

					corazonlike = row.FindViewById<TextView> (Resource.Id.user_corazonlikes);
					string hl="";

					if (haslike) {
						corazonlike.Text = GetString(Resource.String.heart);
						hl="si";

					} else {
						corazonlike.Text = GetString (Resource.String.heartempty);
						hl="no";
					}

					//Typeface font = Typeface.CreateFromAsset(mContext.Assets, "Fonts/fa.ttf");
					corazonlike.SetTypeface(font, TypefaceStyle.Normal);





					holder = new ReviewDetalles(data["cm"]["id"],hl,likescom);

					corazonlike.SetTag(Resource.String.lel,holder);



					LinearLayout layoutlike = row.FindViewById<LinearLayout> (Resource.Id.layoutlike);
					preholder=new LinearDetalles(corazonlike);
					layoutlike.SetTag(Resource.String.lel,preholder);



					//TERMINA
					reviewscont.AddView(row);
				};



				/*
				 * 
				foreach(JsonObject data in ReviewsObj){
					revItems.Add(
						new Review(){
							ReviewId=data["cm"]["id"],
							ReviewnegId=data["cm"]["negocio_id"],
							ReviewNombre=data["u"]["nombre"]+" "+data["u"]["apellidos"],
							ReviewEmail=data["u"]["autor_email"],
							ReviewComentario=data["cm"]["comentario"],
							ReviewCalificacion=data["cm"]["calificacion"],
							ReviewFecha=data["cm"]["fecha"],
							ReviewLikes=data["cm"]["num_likes"],
							ReviewautorId=data["u"]["id"],
							ReviewRuta=data["i"]["ruta"],		
					        ReviewLikesUsers=data["user_likes"]["user_likes"]	
						}
					);

					Log.Debug("AñadirReviews","Añadida!");


				}
*/
				//MyReviewsAdapter rev_adapter = new MyReviewsAdapter(Application.Context, revItems);
				//ListView revslista = FindViewById<ListView> (Resource.Id.revslista);
				//revslista.Adapter=rev_adapter;
				waitrv.Visibility=ViewStates.Gone;
				//revslista.Visibility=ViewStates.Visible;



			}catch(Exception ex){
				Log.Debug("ErrorTodo", ex.ToString());
				waitrv.Visibility=ViewStates.Gone;
				//var fab = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition);
				Snackbar
					.Make (fab, "Ooops! Ocurrió un error al recuperar las reseñas. Inténtalo nuevamente!", Snackbar.LengthLong)
					.SetAction ("Ok", (view) => {  })
					.Show ();				
			}

			try{

				//Traemos la galeria de imagenes
				TextView fotos_tit = FindViewById<TextView> (Resource.Id.fotos_tit);
				fotos_tit.SetTypeface(font, TypefaceStyle.Normal);

				Utils utils = new Utils(this);
				JsonValue contenedorimg = await utils.getFilePaths("http://plif.mx/mobile/get_img_neg?id="+Intent.GetStringExtra("id")+"&prev");

				LinearLayout fotosprevcontain = FindViewById<LinearLayout> (Resource.Id.fotosprevcontain);
				LayoutInflater inflater2 = LayoutInflater.From(this);

				string extra="http://plif.mx/admin/";
				string rutaa="";
				string first="";
				View rowimg = inflater2.Inflate(Resource.Layout.img_layout, fotosprevcontain, false);

				int numfotos=0;

				try{
					rutaa=contenedorimg[0]["imagenes"]["ruta"];
					first=rutaa[0].ToString();

					if(first=="u" || first=="U"){
						//Toast.MakeText (Application.Context, "EMPIEZA CON U!!!", ToastLength.Long).Show ();
						rutaa=extra+rutaa;
					}else{
						//no hagas nada, la imagen es de google
					}

					Log.Debug ("GaleriaAdapter", "Procesando: "+rutaa);

					ImageView cont = rowimg.FindViewById<ImageView> (Resource.Id.img_galeria1);
					Koush.UrlImageViewHelper.SetUrlDrawable (cont, rutaa, Resource.Drawable.bola);
					numfotos++;
				}
				catch(Exception ex){
					ImageView cont = rowimg.FindViewById<ImageView> (Resource.Id.img_galeria1);
					cont.Visibility=ViewStates.Gone;
					Log.Debug("imgscont","no hay imagen uno");


				}

				////LA QUE SIGUE!!!
				try{
					rutaa=contenedorimg[1]["imagenes"]["ruta"];
					first=rutaa[0].ToString();
					if(first=="u" || first=="U"){
						//Toast.MakeText (Application.Context, "EMPIEZA CON U!!!", ToastLength.Long).Show ();
						rutaa=extra+rutaa;
					}else{
						//no hagas nada, la imagen es de google
					}

					Log.Debug ("GaleriaAdapter", "Procesando: "+rutaa);

					ImageView cont2 = rowimg.FindViewById<ImageView> (Resource.Id.img_galeria2);
					Koush.UrlImageViewHelper.SetUrlDrawable (cont2, rutaa, Resource.Drawable.bola);
					numfotos++;
				}
				catch(Exception ex){
					ImageView cont = rowimg.FindViewById<ImageView> (Resource.Id.img_galeria2);
					cont.Visibility=ViewStates.Gone;
					Log.Debug("imgscont","no hay imagen dos");

				}

				////LA ULTIMA!!!
				try{
					rutaa=contenedorimg[2]["imagenes"]["ruta"];
					first=rutaa[0].ToString();
					if(first=="u" || first=="U"){
						//Toast.MakeText (Application.Context, "EMPIEZA CON U!!!", ToastLength.Long).Show ();
						rutaa=extra+rutaa;
					}else{
						//no hagas nada, la imagen es de google
					}

					Log.Debug ("GaleriaAdapter", "Procesando: "+rutaa);

					ImageView cont3 = rowimg.FindViewById<ImageView> (Resource.Id.img_galeria3);
					Koush.UrlImageViewHelper.SetUrlDrawable (cont3, rutaa, Resource.Drawable.bola);
					numfotos++;
				}
				catch(Exception ex){
					ImageView cont = rowimg.FindViewById<ImageView> (Resource.Id.img_galeria3);
					cont.Visibility=ViewStates.Gone;
					Log.Debug("imgscont","no hay imagen tres");

				}



				fotosprevcontain.AddView(rowimg);

				fullfotos= FindViewById<TextView> (Resource.Id.fullfotos);

				if(numfotos>0){
					fullfotos.Visibility=ViewStates.Visible;
				}





			}catch(Exception ex){
				Log.Debug("ErrorLista", ex.ToString());
				var fabee = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition);
				Snackbar
					.Make (fabee, "Ooops! Ocurrió un error al recuperar las imágenes. Inténtalo nuevamente!", Snackbar.LengthLong)
					.SetAction ("Ok", (view) => {  })
					.Show ();	

			}

			EditText nombrerev = FindViewById<EditText> (Resource.Id.nombrerev);
			EditText emailrev = FindViewById<EditText> (Resource.Id.emailrev);
			commentrev = FindViewById<EditText> (Resource.Id.commentrev);

			nombrerev.Text=prefs.GetString("nombre", null);
			emailrev.Text=prefs.GetString("email", null);

			//nombrerev.EditableText = false;
			//emailrev.EditableText = false;
			nombrerev.Enabled = false;
			emailrev.Enabled = false;

			ImageButton e1 = FindViewById<ImageButton> (Resource.Id.estrella1);
			ImageButton e2 = FindViewById<ImageButton> (Resource.Id.estrella2);
			ImageButton e3 = FindViewById<ImageButton> (Resource.Id.estrella3);
			ImageButton e4 = FindViewById<ImageButton> (Resource.Id.estrella4);
			ImageButton e5 = FindViewById<ImageButton> (Resource.Id.estrella5);

			TextView califspan = FindViewById<TextView> (Resource.Id.califspan);

			callnow.Click += (object sender, EventArgs e) => {
				Intent intent = new Intent(Intent.ActionCall, Android.Net.Uri.Parse("tel:" + telefono.Text));
				StartActivity(intent);
			};

			ubicacionbtn.Click += (object sender, EventArgs e) => {
				ubicacionlayout.Visibility=ViewStates.Visible;
				descripcionlayout.Visibility=ViewStates.Gone;
				contactolayout.Visibility=ViewStates.Gone;

				ubicacionbtn.SetBackgroundResource(Resource.Drawable.ubicacionbtnpressprem);
				descripcionbtn.SetBackgroundResource(Resource.Drawable.ubicacionbtnprem);
				contactobtn.SetBackgroundResource(Resource.Drawable.ubicacionbtnprem);
			};

			descripcionbtn.Click += (object sender, EventArgs e) => {
				ubicacionlayout.Visibility=ViewStates.Gone;
				descripcionlayout.Visibility=ViewStates.Visible;
				contactolayout.Visibility=ViewStates.Gone;

				ubicacionbtn.SetBackgroundResource(Resource.Drawable.ubicacionbtnprem);
				descripcionbtn.SetBackgroundResource(Resource.Drawable.ubicacionbtnpressprem);
				contactobtn.SetBackgroundResource(Resource.Drawable.ubicacionbtnprem);
				
			};

			contactobtn.Click += (object sender, EventArgs e) => {
				ubicacionlayout.Visibility=ViewStates.Gone;
				descripcionlayout.Visibility=ViewStates.Gone;
				contactolayout.Visibility=ViewStates.Visible;

				ubicacionbtn.SetBackgroundResource(Resource.Drawable.ubicacionbtnprem);
				descripcionbtn.SetBackgroundResource(Resource.Drawable.ubicacionbtnprem);
				contactobtn.SetBackgroundResource(Resource.Drawable.ubicacionbtnpressprem);

				
			};

			addcomentbtn = FindViewById<Button> (Resource.Id.addcomment);

			enviarmensaje.Click += (object sender, EventArgs e) => {
				var enviarmsj = new Intent (this, typeof(EnviarMensaje));
				enviarmsj.PutExtra("negocioid",idres);
				enviarmsj.PutExtra("titulo", titulores);
				enviarmsj.PutExtra("propietario",propietario);
				StartActivity (enviarmsj);
			};


			addcomentbtn.Click += (sender, e) => {
				enviarrev.Focusable=true;
				enviarrev.FocusableInTouchMode=true;
				if(enviarrev.RequestFocus()){
					Log.Debug("BotonArribaReseña", "It dit it!");
					enviarrev.ClearFocus();
					enviarrev.FocusableInTouchMode=false;
				}

			};

			e1.Click += delegate(object sender, EventArgs e) {

				califspan.StartAnimation(flip);
				califspan.Text="1.0";
				calificacion=1;
				e1.SetImageResource(Resource.Drawable.estrellafull);
				e2.SetImageResource(Resource.Drawable.estrellaempty);
				e3.SetImageResource(Resource.Drawable.estrellaempty);
				e4.SetImageResource(Resource.Drawable.estrellaempty);
				e5.SetImageResource(Resource.Drawable.estrellaempty);
			};

			e2.Click += delegate(object sender, EventArgs e) {

				califspan.StartAnimation(flip);
				califspan.Text="2.0";
				calificacion=2;
				e1.SetImageResource(Resource.Drawable.estrellafull);
				e2.SetImageResource(Resource.Drawable.estrellafull);
				e3.SetImageResource(Resource.Drawable.estrellaempty);
				e4.SetImageResource(Resource.Drawable.estrellaempty);
				e5.SetImageResource(Resource.Drawable.estrellaempty);
			};

			e3.Click += delegate(object sender, EventArgs e) {

				califspan.StartAnimation(flip);
				califspan.Text="3.0";
				calificacion=3;
				e1.SetImageResource(Resource.Drawable.estrellafull);
				e2.SetImageResource(Resource.Drawable.estrellafull);
				e3.SetImageResource(Resource.Drawable.estrellafull);
				e4.SetImageResource(Resource.Drawable.estrellaempty);
				e5.SetImageResource(Resource.Drawable.estrellaempty);
			};

			e4.Click += delegate(object sender, EventArgs e) {

				califspan.StartAnimation(flip);
				califspan.Text="4.0";
				calificacion=4;
				e1.SetImageResource(Resource.Drawable.estrellafull);
				e2.SetImageResource(Resource.Drawable.estrellafull);
				e3.SetImageResource(Resource.Drawable.estrellafull);
				e4.SetImageResource(Resource.Drawable.estrellafull);
				e5.SetImageResource(Resource.Drawable.estrellaempty);
			};

			e5.Click += delegate(object sender, EventArgs e) {

				califspan.StartAnimation(flip);
				califspan.Text="5.0";
				calificacion=5;
				e1.SetImageResource(Resource.Drawable.estrellafull);
				e2.SetImageResource(Resource.Drawable.estrellafull);
				e3.SetImageResource(Resource.Drawable.estrellafull);
				e4.SetImageResource(Resource.Drawable.estrellafull);
				e5.SetImageResource(Resource.Drawable.estrellafull);
			};

			e5.PerformClick ();


			//nenenenenenene
			addimg.Click += async (object sender, EventArgs e) => {
				layoutdejaimagenes.Visibility=ViewStates.Visible;
			};

			deleteimgrev.Click += async (sender, e) => {
				GridLayout imgcomprev = FindViewById<GridLayout> (Resource.Id.imgcomprev);
				LinearLayout imgcontainercomprev = FindViewById<LinearLayout> (Resource.Id.imgcontainercomprev);
				Log.Debug("DELETEBUTTON","Inician las layouts");
				if(imgcomprev.ChildCount>0){
					imgcomprev.RemoveAllViews();
				}


				Log.Debug("DELETEBUTTON","vistas removidas");

				if(imagencomentario!=null){
					imagencomentario.Recycle();
					imagencomentario=null;
				}

				Log.Debug("DELETEBUTTON","reciclado");

				//deleteimgrev.Visibility=ViewStates.Gone;
				Log.Debug("DELETEBUTTON","se oculta boton borrar (deprecated)");
				imgcontainercomprev.Visibility=ViewStates.Gone;
				Log.Debug("DELETEBUTTON","se oculta el contenedor de subir imagenes");
				imagenrev = FindViewById<Button> (Resource.Id.imagenrev);
				imagenrev.Visibility=ViewStates.Visible;
				Log.Debug("DELETEBUTTON","se muestra el boton añadir");

				fossbytes.Clear();
				Log.Debug("DELETEBUTTON","El Arraylist de bytes se resetea");

				imgcount=0;
				Log.Debug("DELETEBUTTON","se resetea el contador de cuantas imagenes se subieron");
				masimagenes.Text="Carga 3 imágenes más!";
				Log.Debug("DELETEBUTTON","Reseteamos el texto de las imagenes");


			};

			deleteimgnegocio.Click += async (sender, e) => {
				//LinearLayout imgcomprev = FindViewById<LinearLayout> (Resource.Id.imgcomprev);
				//LinearLayout imgcontainercomprev = FindViewById<LinearLayout> (Resource.Id.imgcontainercomprev);
				Log.Debug("DELETEBUTTON","Inician las layouts");
				if(imgnegocioprev.ChildCount>0){
					imgnegocioprev.RemoveAllViews();
				}


				Log.Debug("DELETEBUTTON","vistas removidas");

				if(imagencomentario!=null){
					imagencomentario.Recycle();
					imagencomentario=null;
				}

				Log.Debug("DELETEBUTTON","reciclado");
				//deleteimgrev.Visibility=ViewStates.Gone;
				Log.Debug("DELETEBUTTON","se oculta boton borrar (deprecated)");
				layoutdejaimagenes.Visibility=ViewStates.Gone;
				Log.Debug("DELETEBUTTON","se oculta el contenedor de subir imagenes");

				fossbytes.Clear();
				Log.Debug("DELETEBUTTON","El Arraylist de bytes se resetea");

				imgcount=0;
				Log.Debug("DELETEBUTTON","se resetea el contador de cuantas imagenes se subieron");
				masimagenesnegocio.Text="Carga 10 imágenes más!";
				Log.Debug("DELETEBUTTON","Reseteamos el texto de las imagenes");
			};

			imagenrev.Click += async (object sender, EventArgs e) => {

				LinearLayout imgcontainercomprev = FindViewById<LinearLayout> (Resource.Id.imgcontainercomprev);
				imgcontainercomprev.Visibility=ViewStates.Visible;
				imagenrev.Visibility=ViewStates.Gone;

			};

			imagennegocio.Click += async (object sender, EventArgs e) => {
				source=1;
				ProcesarImagenes(imgnegocioprev, 10, masimagenesnegocio);
			};

			imagencamaranegocio.Click += async (object sender, EventArgs e) => {
				source=2;
				ProcesarImagenes(imgnegocioprev, 10, masimagenesnegocio);
			};

			imagenrev2.Click += async (object sender, EventArgs e) => {
				source=1;
				GridLayout imgcomprev = FindViewById<GridLayout> (Resource.Id.imgcomprev);
				ProcesarImagenes(imgcomprev,3,masimagenes);

			};//imagenrev click

			imagencamara.Click += async (sender, e) => {
				source=2;
				GridLayout imgcomprev = FindViewById<GridLayout> (Resource.Id.imgcomprev);
				ProcesarImagenes(imgcomprev,3,masimagenes);
			};

			enviarimgneg.Click += async (object sender, EventArgs e) => {
				if(imgcount>0){

					diccionario = new Dictionary<string, string>();
					diccionario.Add("negocio", idres); 
					diccionario.Add("description", "Foto en "+titulores); 
					diccionario.Add("autor", prefs.GetString("id", null));


					//LIMPIAMOS LA PANTALLA Y DESHABILITAMOS LOS BOTONES
					ProgressBar waitnegociors=FindViewById<ProgressBar>(Resource.Id.waitnegociors);
					waitnegociors.Visibility=ViewStates.Visible;

					TextView subiendofotos = FindViewById<TextView> (Resource.Id.subiendofotos);
					subiendofotos.Visibility=ViewStates.Visible;
					//deleteimgrev.PerformClick();

					//se deshabilitan ambos botones
					//enviarrev.Enabled=false;
					//imagenrev.Enabled=false;



					//LinearLayout imgcontainercomprev = FindViewById<LinearLayout> (Resource.Id.imgcontainercomprev); 
					layoutdejaimagenes.Visibility=ViewStates.Gone;
					Log.Debug("EnviarImagen","se oculta el contenedor de subir imagenes");
					imagenrev = FindViewById<Button> (Resource.Id.imagenrev);
					imagenrev.Visibility=ViewStates.Visible;
					Log.Debug("EnviarImagenes","se muestra el boton añadir");
					masimagenesnegocio.Text="Carga 10 imágenes más!";
					Log.Debug("EnviarImagenes","Reseteamos el texto de las imagenes");


					int countbytes=fossbytes.Count;
					if(fossbytes!=null && countbytes>0){
						Log.Debug ("EnviarImagenes", "Si hay imágenes byte en el array!");
						Log.Debug("CONVERTIR","Elementos convertidos a Byte: "+countbytes);

					}


					string resp = await plifserver.PostMultiPartForm ("http://plif.mx/pages/UploadImg/0", fossbytes, "nada", "file[]", "image/jpeg", diccionario, false);
					Log.Debug("SUBIRIMAGENES",resp);
					waitnegociors.Visibility=ViewStates.Gone;
					subiendofotos.Visibility=ViewStates.Gone;
					deleteimgnegocio.PerformClick();

					var fabee = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition);
					Snackbar
						.Make (fabee, "Hemos recibido tus fotos. Gracias por ser parte de Plif!", Snackbar.LengthLong)
						.SetAction ("Ok", (view) => {  })
						.Show ();	

				}else{
					var fabee = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition);
					Snackbar
						.Make (fabee, "Selecciona al menos una imágen!", Snackbar.LengthLong)
						.SetAction ("Ok", (view) => {  })
						.Show ();		
				}

			};

			enviarrev.Click += async (object sender, EventArgs e) => {
				if(calificacion==0){
					var fabee = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition);
					Snackbar
						.Make (fabee, "Por favor califica al negocio!", Snackbar.LengthLong)
						.SetAction ("Ok", (view) => {  })
						.Show ();	
				}else{
					if(commentrev.Text==""){
						var fabee = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition);
						Snackbar
							.Make (fabee, "Por favor escribe un comentario!", Snackbar.LengthLong)
							.SetAction ("Ok", (view) => {  })
							.Show ();	
					}else{
						//Aqui mero!!!!



						diccionario = new Dictionary<string, string>();
						diccionario.Add("comentario", commentrev.Text); 
						diccionario.Add("autor", prefs.GetString("id", null));
						diccionario.Add("calificacion", calificacion.ToString());
						diccionario.Add("negocio", idres);
						diccionario.Add("titulo", titulores);
						Log.Debug("EnviarComentario","Clickeo");

						//LIMPIAMOS LA PANTALLA Y DESHABILITAMOS LOS BOTONES
						ProgressBar waitrs=FindViewById<ProgressBar>(Resource.Id.waitrs);
						waitrs.Visibility=ViewStates.Visible;
						//deleteimgrev.PerformClick();

						//se deshabilitan ambos botones
						enviarrev.Enabled=false;
						imagenrev.Enabled=false;

						LinearLayout imgcontainercomprev = FindViewById<LinearLayout> (Resource.Id.imgcontainercomprev); 
						imgcontainercomprev.Visibility=ViewStates.Gone;
						Log.Debug("EnviarComentario","se oculta el contenedor de subir imagenes");
						imagenrev = FindViewById<Button> (Resource.Id.imagenrev);
						imagenrev.Visibility=ViewStates.Visible;
						Log.Debug("EnviarComentario","se muestra el boton añadir");
						masimagenes.Text="Carga 3 imágenes más!";
						Log.Debug("EnviarComentario","Reseteamos el texto de las imagenes");

						string filename="";
						int countbytes=fossbytes.Count;
						if(fossbytes!=null && countbytes>0){
							Log.Debug ("EnviarComentario", "Si hay imágenes byte en el array!");
							Log.Debug("CONVERTIR","Elementos convertidos a Byte: "+countbytes);

						}

						//AQUI LO ENVIAMOS, EL PRIMER PARAMETRO ES LA PÁGINA, EL SEGUNDO ES LA IMAGEN CODIFICADA EN BITS, EL TERCERO ES EL NOMBRE DEL PARÁMETRO QUE RECIBE PHP, EL CUARTO ES EL MIMETYPE DE LA IMAGEN, Y EL ULTIMO ES EL DICCTIONARY CON TODOS LOS DEMÁS VALORES STRING
						string resp = await plifserver.PostMultiPartForm ("http://plif.mx/comentario_negocio", fossbytes, filename, "file[]", "image/jpeg", diccionario, false);

						//deleteimgrev.PerformClick();
						enviarrev.Enabled=true;
						imagenrev.Enabled=true;
						waitrs.Visibility=ViewStates.Gone;
						calificacion=0;
						commentrev.Text="";

						califspan.StartAnimation(flip);
						califspan.Text="0.0";
						calificacion=0;
						e1.SetImageResource(Resource.Drawable.estrellaempty);
						e2.SetImageResource(Resource.Drawable.estrellaempty);
						e3.SetImageResource(Resource.Drawable.estrellaempty);
						e4.SetImageResource(Resource.Drawable.estrellaempty);
						e5.SetImageResource(Resource.Drawable.estrellaempty);

						Log.Debug("MULTIPARTRESPONSE",resp);
						deleteimgrev.PerformClick();

						var fabee = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition);
						Snackbar
							.Make (fabee, "Tu reseña ha sido enviada. ¡Gracias por ser parte de Plif!", Snackbar.LengthLong)
							.SetAction ("Ok", (view) => {  })
							.Show ();	

					}
				}

			};


			fullfotos.Click += delegate(object sender, EventArgs e) {
				var galeriaimg = new Intent (this, typeof(GaleriaImagenes));
				galeriaimg.PutExtra("negocioid",idres);

				/*negocio.PutExtra("id",negItems [e.Position].NegocioId);
				negocio.PutExtra("nombre",negItems [e.Position].NegocioName);
				negocio.PutExtra("direccion",negItems [e.Position].NegocioDir);
				negocio.PutExtra("categoria",negItems [e.Position].NegocioCat);
				negocio.PutExtra("calificacion",negItems [e.Position].NegocioCal);*/
				StartActivity (galeriaimg);
				//StartActivity(typeof(GaleriaImagenes));
				/*
				var fabee = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition);
				Snackbar
					.Make (fabee, "El lunes se lo pongo!", Snackbar.LengthLong)
					.SetAction ("Ok", (view) => {  })
					.Show ();	
					*/
			};



			abiertocerrado.Click += delegate {
				if(!horariovisible){
					//layoutdiascontainer.Animate().TranslationY(300);
					layoutdiascontainer.Visibility=ViewStates.Visible;
					//int val=GetX(layoutdiascontainer);
					//scrollview.ScrollTo(0,val);
					horariovisible=true;
				}else{
					//layoutdiascontainer.Animate().TranslationY(0);
					layoutdiascontainer.Visibility=ViewStates.Gone;
					horariovisible=false;
				}


			};

			addlike.Click += async (sender, e) => {

				if(!dandolike){
					dandolike=true;

				try{
					if(!haslike){
						haslike=true;
						addlike.StartAnimation(bounce);
						addlike.Text = GetString (Resource.String.heart);
						numlikes++;
						likes.Text=numlikes+" Personas";
						//JsonValue likeans=await plifserver.FetchWeatherAsync("http://plif.mx/mobile/like_neg_asset?nid="+Intent.GetStringExtra("id")+"&uid="+userid+"&case=1");
							string likestring="http://plif.mx/pages/LikeNegocio/"+negocioid+"/1?uid="+userid;
							Log.Debug("Like","La URL Es: "+likestring);
							JsonValue likeans=await plifserver.FetchWeatherAsync("http://plif.mx/pages/LikeNegocio/"+negocioid+"/1?uid="+userid);
						dandolike=false;

					}else{
						haslike=false;
						addlike.StartAnimation(bounce);
						addlike.Text = GetString (Resource.String.heartempty);
						numlikes--;
						likes.Text=numlikes+" Personas";
						//JsonValue likeans=await plifserver.FetchWeatherAsync("http://plif.mx/mobile/like_neg_asset?nid="+Intent.GetStringExtra("id")+"&uid="+userid+"&case=2");
							string likestring="http://plif.mx/pages/LikeNegocio/"+negocioid+"/2?uid="+userid;
							Log.Debug("Like","La URL Es: "+likestring);
							JsonValue likeans=await plifserver.FetchWeatherAsync(likestring);

						dandolike=false;

					}
				}catch(Exception ex){
					waitpb.Visibility=ViewStates.Gone;
					//var fab = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition);
					Snackbar
						.Make (fab, "Ooops! Ocurrió un error al intentar procesar tu solicitud. Inténtalo nuevamente!", Snackbar.LengthLong)
						.SetAction ("Ok", (view) => {  })
						.Show ();
				}

			}else{
					Log.Debug("AddLike","Like en proceso! Por favor espera!!");
				}

			};

			//REDES SOCIALES


		}
Esempio n. 48
0
        public void CreateGUI()
        {
            GUI.RootComponent.ClearChildren();
            Games.Clear();
            const int edgePadding = 32;
            Panel mainWindow = new Panel(GUI, GUI.RootComponent)
            {
                LocalBounds = new Rectangle(edgePadding, edgePadding, Game.GraphicsDevice.Viewport.Width - edgePadding * 2, Game.GraphicsDevice.Viewport.Height - edgePadding * 2)
            };
            GridLayout layout = new GridLayout(GUI, mainWindow, 10, 4);

            Label title = new Label(GUI, layout, "Load Game", GUI.TitleFont);
            layout.SetComponentPosition(title, 0, 0, 1, 1);

            scroller = new ScrollView(GUI, layout);
            layout.SetComponentPosition(scroller, 0, 1, 3, 8);

            LoadWorlds();

            layout.UpdateSizes();

            int cols = Math.Max(scroller.LocalBounds.Width / 256, 1);
            int rows = Math.Max(Math.Max(scroller.LocalBounds.Height / 256, 1), (int)Math.Ceiling((float)Games.Count / (float)cols));

            scrollGrid = new GridLayout(GUI, scroller, rows, cols)
            {
                LocalBounds = new Rectangle(edgePadding, edgePadding, scroller.LocalBounds.Width - edgePadding, rows * 256),
                WidthSizeMode = GUIComponent.SizeMode.Fixed,
                HeightSizeMode = GUIComponent.SizeMode.Fixed
            };

            CreateGamePictures(scrollGrid, cols);

            CreateLoadThreads(4);

            PropertiesPanel = new GroupBox(GUI, layout, "Selected");

            layout.SetComponentPosition(PropertiesPanel, 3, 1, 1, 8);

            Button back = new Button(GUI, layout, "Back", GUI.DefaultFont, Button.ButtonMode.ToolButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.LeftArrow));
            layout.SetComponentPosition(back, 3, 9, 1, 1);
            back.OnClicked += back_OnClicked;
        }
		//--->TERMINAN COSAS DE SELECCIONAR IMAGEN DE LA CAMARA<---//

		//INICIA PROCESAR IMAGENES
		public void ProcesarImagenes (GridLayout imgcomprev, int limite, TextView imgrestantes){

			if(imgcount<limite){
				GetImage(((b, p) => {
					int countimage = p.Count;
					Log.Debug("GetImage","Imagenes en el list: "+countimage);
					int imgcount2=imgcount+countimage;
					Log.Debug("GetImage","Imagenes totales: "+imgcount2);

					if(imgcount2>limite){
						//int total = limite-imgcount;
						var fabee = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition);
						Snackbar
							.Make (fabee, "No puedes publicar mas de "+limite+" imágenes!", Snackbar.LengthLong)
							.SetAction ("Ok", (view) => {  })
							.Show ();	
					}else{
						//ya aqui se hace lo de poner cada imagen
						imgcount=imgcount2;
						Log.Debug("GetImage","Nuevo imgcount: "+imgcount);


						for(int i=0; i<countimage; i++){
							//filenameres= p[i].Substring (p[i].LastIndexOf ("/") + 1);
							//fileextres= filenameres.Substring (filenameres.LastIndexOf(".")+1);

							//Si por algún acaso la memoria no ha sido liberada, la liberamos primero.
							if (imagencomentario != null && !imagencomentario.IsRecycled) {
								imagencomentario.Recycle();
								imagencomentario = null; 
							}

							Java.IO.File f = new Java.IO.File(p[i]);
							stream = this.ContentResolver.OpenInputStream(Android.Net.Uri.FromFile(f));
							imagencomentario=BitmapFactory.DecodeStream(stream);
							//POR AHORA VAMOS A QUITAR ESTO PARA QUE LO HAGA MAS RAPIDO Y DEJAMOS QUE EL SERVIDOR SE ENCARGUE

							/*
							try{
								Android.Media.ExifInterface ei = new Android.Media.ExifInterface(p[i]);
								var orientation= ei.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, -1);
								Log.Debug("GetImageCamera","El orientation es: "+orientation);

								if(orientation==1){
									//No hagas nada, si está bien la imagen. No tiene caso .-.
								}else{


								Log.Debug("Orientation", "Inicia Mutable");
								Bitmap mutable;
								Canvas cnv;
								Matrix matrix;
								Log.Debug("Orientation", "Termina Mutable");

								Log.Debug("Orientation", "Inicia Switch");
								switch(orientation){
								case 6:
									//90 grados
									mutable = imagencomentario.Copy(Bitmap.Config.Argb8888, true);
									cnv = new Canvas(mutable);
									matrix = new Matrix();
									Log.Debug("Orientation", "90 Grados");
									matrix.PostRotate(90);
									imagencomentario=Bitmap.CreateBitmap(mutable, 0, 0,  imagencomentario.Width, imagencomentario.Height, matrix, true);
									break;

								case 3:
									//180 grados
									mutable = imagencomentario.Copy(Bitmap.Config.Argb8888, true);
									cnv = new Canvas(mutable);
									matrix = new Matrix();
									Log.Debug("Orientation", "180 Grados");
									matrix.PostRotate(180);
									imagencomentario=Bitmap.CreateBitmap(mutable, 0, 0,  imagencomentario.Width, imagencomentario.Height, matrix, true);
									break;

								case 8:
									//270 grados
									mutable = imagencomentario.Copy(Bitmap.Config.Argb8888, true);
									cnv = new Canvas(mutable);
									matrix = new Matrix();
									Log.Debug("Orientation", "270 Grados");
									matrix.PostRotate(270);
									imagencomentario=Bitmap.CreateBitmap(mutable, 0, 0,  imagencomentario.Width, imagencomentario.Height, matrix, true);
									break;

								default:
									Log.Debug("Orientation", "0 Grados (0 360, como se quiera ver :P)");
									//0 grados
									//No hagas nada
									break;
								};

								Log.Debug("Orientation", "Termina Switch");
								}//ELSE orientation = 1
							}catch(Exception ex){
								Log.Debug("Orientation", "ERROR! Posiblemente no hay EXIF: "+ex);
							}
							*/

							if(imagencomentario!=null){
								//Toast.MakeText(this, "Si se creó el Bitmap!!!", ToastLength.Long).Show();
								//Lo añadimos a la lista
								//Bitmap tmp = imagencomentario;

								Log.Debug("FOSSBYTES","Inicia conversión a bytes!");
								byte[] tmp2 = PathToByte2(p[i]);
								Log.Debug("FOSSBYTES","Termina conversión a bytes!");
								fossbytes.Add(tmp2);
								//Toast.MakeText(this, "Elementos en lista: "+contenedorimagenes.Count, ToastLength.Long).Show();

								//aqui haremos el img


								//Creamos el imageview con sus parámetros
								ImageView prev = new ImageView(this);
								imgcomprev.AddView(prev);
								GridLayout.LayoutParams lp = new  GridLayout.LayoutParams();    
								lp.SetMargins(15,15,0,15);
								lp.Width=130;
								lp.Height=130;
								prev.LayoutParameters=lp;
								prev.SetScaleType(ImageView.ScaleType.CenterCrop);
								prev.SetImageBitmap(Bitmap.CreateScaledBitmap(imagencomentario, 175, 175, false));
								//prev.StartAnimation(bounce);





								//imgcount++;

								//Liberamos la memoria Inmediatamente!
								if (imagencomentario != null && !imagencomentario.IsRecycled) {
									imagencomentario.Recycle();
									imagencomentario = null; 
								}
								//Mala idea, esto causó que tronara .-. si lo voy a hacer pero cuando no tenga que usarlo

							}else{//por si algun acaso intenta procesar una ruta null
								var fabee = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition);
								Snackbar
									.Make (fabee, "Ocurrió un error. Por favor intenta con una imágen diferente", Snackbar.LengthLong)
									.SetAction ("Ok", (view) => {  })
									.Show ();	
								break;
							}

						}//TERMINA EL FOR PARA CADA IMAGEN 


						int restantes=limite-imgcount;
						if(restantes==0){
							imgrestantes.Text="¡Excelente!";
						}else{
							imgrestantes.Text="Puedes cargar "+restantes+" imágenes más!";
						}



					}//TERMINA EL ELSE DE COMPROBAR SI HAY MAS IMAGENES DE LAS QUE SE PUEDEN CARGAR

				}));//GETIMAGE

			}else{

				var fabee = FindViewById<CoordinatorLayout> (Resource.Id.snackbarPosition);
				Snackbar
					.Make (fabee, "Solo puedes subir hasta 3 imágenes!", Snackbar.LengthLong)
					.SetAction ("Ok", (view) => {  })
					.Show ();	

			}//ELSE COUNTIMAGES < 3

		}
Esempio n. 50
0
        public override void OnEnter()
        {
            PlayState.WorldWidth = Settings.Width;
            PlayState.WorldHeight = Settings.Height;
            PlayState.SeaLevel = Settings.SeaLevel;
            PlayState.Random = new ThreadSafeRandom(Seed);
            PlayState.WorldSize = new Point3(8, 1, 8);

            Overworld.Volcanoes = new List<Vector2>();

            DefaultFont = Game.Content.Load<SpriteFont>(ContentPaths.Fonts.Default);
            GUI = new DwarfGUI(Game, DefaultFont, Game.Content.Load<SpriteFont>(ContentPaths.Fonts.Title), Game.Content.Load<SpriteFont>(ContentPaths.Fonts.Small), Input);
            IsInitialized = true;
            Drawer = new Drawer2D(Game.Content, Game.GraphicsDevice);
            GenerationComplete = false;
            MainWindow = new Panel(GUI, GUI.RootComponent)
            {
                LocalBounds = new Rectangle(EdgePadding, EdgePadding, Game.GraphicsDevice.Viewport.Width - EdgePadding * 2, Game.GraphicsDevice.Viewport.Height - EdgePadding * 2)
            };

            GridLayout layout = new GridLayout(GUI, MainWindow, 7, 4)
            {
                LocalBounds = new Rectangle(0, 0, MainWindow.LocalBounds.Width, MainWindow.LocalBounds.Height)
            };

            Button startButton = new Button(GUI, layout, "Start!", GUI.DefaultFont, Button.ButtonMode.ToolButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.Check))
            {
                ToolTip = "Start the game with the currently generated world."
            };

            layout.SetComponentPosition(startButton, 2, 6, 1, 1);
            startButton.OnClicked += StartButtonOnClick;

            Button saveButton = new Button(GUI, layout, "Save", GUI.DefaultFont, Button.ButtonMode.ToolButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.Save))
            {
                ToolTip = "Save the generated world to a file."
            };
            layout.SetComponentPosition(saveButton, 1, 6, 1, 1);
            saveButton.OnClicked += saveButton_OnClicked;

            Button exitButton = new Button(GUI, layout, "Back", GUI.DefaultFont, Button.ButtonMode.ToolButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.LeftArrow))
            {
                ToolTip = "Back to the main menu."
            };
            layout.SetComponentPosition(exitButton, 0, 6, 1, 1);

            exitButton.OnClicked += ExitButtonOnClick;

            MapPanel = new ImagePanel(GUI, layout, worldMap)
            {
                ToolTip = "Map of the world.\nClick to select a location to embark."
            };

            GridLayout mapLayout = new GridLayout(GUI, MapPanel, 4, 5);

            ColorKeys = new ColorKey(GUI, mapLayout)
            {
                ColorEntries = Overworld.HeightColors
            };

            mapLayout.SetComponentPosition(ColorKeys, 3, 0, 1, 1);

            CloseupPanel = new ImagePanel(GUI, mapLayout, new ImageFrame(worldMap, new Rectangle(0, 0, 128, 128)))
            {
                KeepAspectRatio = true,
                ToolTip = "Closeup of the colony location"
            };

            mapLayout.SetComponentPosition(CloseupPanel, 3, 2, 2, 2);

            layout.SetComponentPosition(MapPanel, 0, 0, 3, 5);

            if(worldMap != null)
            {
                MapPanel.Image = new ImageFrame(worldMap);
            }

            MapPanel.OnClicked += OnMapClick;

            layout.UpdateSizes();

            GroupBox mapProperties = new GroupBox(GUI, layout, "Map Controls");

            GridLayout mapPropertiesLayout = new GridLayout(GUI, mapProperties, 7, 2)
            {
                LocalBounds = new Rectangle(mapProperties.LocalBounds.X, mapProperties.LocalBounds.Y + 32, mapProperties.LocalBounds.Width, mapProperties.LocalBounds.Height)
            };

            ComboBox worldSizeBox = new ComboBox(GUI, mapPropertiesLayout)
            {
                ToolTip = "Size of the colony spawn area."
            };

            worldSizeBox.AddValue("Tiny Colony");
            worldSizeBox.AddValue("Small Colony");
            worldSizeBox.AddValue("Medium Colony");
            worldSizeBox.AddValue("Large Colony");
            worldSizeBox.AddValue("Huge Colony");
            worldSizeBox.CurrentIndex = 1;

            worldSizeBox.OnSelectionModified += worldSizeBox_OnSelectionModified;
            mapPropertiesLayout.SetComponentPosition(worldSizeBox, 0, 0, 2, 1);

            ViewSelectionBox = new ComboBox(GUI, mapPropertiesLayout)
            {
                ToolTip = "Display type for the map."
            };

            ViewSelectionBox.AddValue("Height");
            ViewSelectionBox.AddValue("Factions");
            ViewSelectionBox.AddValue("Biomes");
            ViewSelectionBox.AddValue("Temp.");
            ViewSelectionBox.AddValue("Rain");
            ViewSelectionBox.AddValue("Erosion");
            ViewSelectionBox.AddValue("Faults");
            ViewSelectionBox.CurrentIndex = 0;

            mapPropertiesLayout.SetComponentPosition(ViewSelectionBox, 1, 1, 1, 1);

            Label selectLabel = new Label(GUI, mapPropertiesLayout, "Display", GUI.DefaultFont);
            mapPropertiesLayout.SetComponentPosition(selectLabel, 0, 1, 1, 1);
            selectLabel.Alignment = Drawer2D.Alignment.Right;

            layout.SetComponentPosition(mapProperties, 3, 0, 1, 6);

            Progress = new ProgressBar(GUI, layout, 0.0f);
            layout.SetComponentPosition(Progress, 0, 5, 3, 1);

            ViewSelectionBox.OnSelectionModified += DisplayModeModified;
            base.OnEnter();
        }
Esempio n. 51
0
 private static ILayout ChooseLayout(GraphLayoutType s)
 {
     EdgeDrawer ed = new EdgeDrawer();
     gd.EdgeDrawer = ed;
     ed.Color = Color.Red;
     VertexDrawer vd = new VertexDrawer();
     gd.VertexDrawer = vd;
     vd.Shape = VertexDrawer.VertexShape.Disk;
     ILayout fr = new FruchtermanReingoldLayout();
     switch (s)
     {
         case GraphLayoutType.Fruchterman_Reingold:
             fr = new FruchtermanReingoldLayout();
             break;
         case GraphLayoutType.Random:
             fr = new RandomLayout();
             break;
         case GraphLayoutType.Circle:
             fr = new CircleLayout();
             break;
         case GraphLayoutType.Kamada_Kawaii:
             fr = new KamadaKawaiiLayout();
             break;
         case GraphLayoutType.Grid:
             fr = new GridLayout();
             break;
         case GraphLayoutType.Sugiyama:
             SugiyamaEdgeDrawer eds = new SugiyamaEdgeDrawer();
             gd.EdgeDrawer = eds;
             eds.Color = Color.Red;
             SugiyamaVertexDrawer vds = new SugiyamaVertexDrawer();
             gd.VertexDrawer = vds;
             vds.Shape = VertexDrawer.VertexShape.Sphere;
             fr = new SugiyamaLayout();
             break;
     }
     return fr;
 }
Esempio n. 52
0
        /// <summary>
        /// Creates all of the sub-components of the GUI in for the PlayState (buttons, etc.)
        /// </summary>
        public void CreateGUIComponents()
        {
            GUI.RootComponent.ClearChildren();
            GridLayout layout = new GridLayout(GUI, GUI.RootComponent, 11, 11)
            {
                LocalBounds = new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height),
                WidthSizeMode = GUIComponent.SizeMode.Fixed,
                HeightSizeMode = GUIComponent.SizeMode.Fixed
            };

            GUI.RootComponent.AddChild(Master.Debugger.MainPanel);
            layout.AddChild(Master.ToolBar);
            Master.ToolBar.Parent = layout;
            layout.SetComponentPosition(Master.ToolBar, 7, 10, 4, 1);

            GUIComponent companyInfoComponent = new GUIComponent(GUI, layout);

            layout.SetComponentPosition(companyInfoComponent, 0, 0, 4, 2);

            GUIComponent resourceInfoComponent = new ResourceInfoComponent(GUI, layout, Master.Faction);
            layout.SetComponentPosition(resourceInfoComponent, 7, 0, 2, 2);

            GridLayout infoLayout = new GridLayout(GUI, companyInfoComponent, 3, 4);

            CompanyLogoPanel = new ImagePanel(GUI, infoLayout, PlayerCompany.Logo);
            infoLayout.SetComponentPosition(CompanyLogoPanel, 0, 0, 1, 1);

            CompanyNameLabel = new Label(GUI, infoLayout, PlayerCompany.Name, GUI.DefaultFont)
            {
                TextColor = Color.White,
                StrokeColor = new Color(0, 0, 0, 255),
                ToolTip = "Our company Name.",
                Alignment = Drawer2D.Alignment.Top,
            };
            infoLayout.SetComponentPosition(CompanyNameLabel, 1, 0, 1, 1);

            MoneyLabel = new DynamicLabel(GUI, infoLayout, "Money:\n", "", GUI.DefaultFont, "C2", () => Master.Faction.Economy.CurrentMoney)
            {
                TextColor = Color.White,
                StrokeColor = new Color(0, 0, 0, 255),
                ToolTip = "Amount of money in our treasury.",
                Alignment = Drawer2D.Alignment.Top,
            };
            infoLayout.SetComponentPosition(MoneyLabel, 3, 0, 1, 1);

            StockLabel = new DynamicLabel(GUI, infoLayout, "Stock:\n", "", GUI.DefaultFont, "C2", () => Master.Faction.Economy.Company.StockPrice)
            {
                TextColor = Color.White,
                StrokeColor = new Color(0, 0, 0, 255),
                ToolTip = "The price of our company stock.",
                Alignment = Drawer2D.Alignment.Top,
            };
            infoLayout.SetComponentPosition(StockLabel, 5, 0, 1, 1);

            TimeLabel = new Label(GUI, layout, Time.CurrentDate.ToShortDateString() + " " + Time.CurrentDate.ToShortTimeString(), GUI.SmallFont)
            {
                TextColor = Color.White,
                StrokeColor = new Color(0, 0, 0, 255),
                Alignment = Drawer2D.Alignment.Top,
                ToolTip = "Current time and date."
            };
            layout.SetComponentPosition(TimeLabel, 6, 0, 1, 1);

            CurrentLevelLabel = new Label(GUI, infoLayout, "Slice: " + ChunkManager.ChunkData.MaxViewingLevel, GUI.DefaultFont)
            {
                TextColor = Color.White,
                StrokeColor = new Color(0, 0, 0, 255),
                ToolTip = "The maximum height of visible terrain"
            };
            infoLayout.SetComponentPosition(CurrentLevelLabel, 0, 1, 1, 1);

            CurrentLevelUpButton = new Button(GUI, infoLayout, "", GUI.DefaultFont, Button.ButtonMode.ImageButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.SmallArrowUp))
            {
                ToolTip = "Go up one level of visible terrain",
                KeepAspectRatio = true,
                DontMakeBigger = true,
                DontMakeSmaller = true
            };

            infoLayout.SetComponentPosition(CurrentLevelUpButton, 1, 1, 1, 1);
            CurrentLevelUpButton.OnClicked += CurrentLevelUpButton_OnClicked;

            CurrentLevelDownButton = new Button(GUI, infoLayout, "", GUI.DefaultFont, Button.ButtonMode.ImageButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.SmallArrowDown))
            {
                ToolTip = "Go down one level of visible terrain",
                KeepAspectRatio = true,
                DontMakeBigger = true,
                DontMakeSmaller = true
            };
            infoLayout.SetComponentPosition(CurrentLevelDownButton, 1, 2, 1, 1);
            CurrentLevelDownButton.OnClicked += CurrentLevelDownButton_OnClicked;

            /*
            LevelSlider = new Slider(GUI, layout, "", ChunkManager.ChunkData.MaxViewingLevel, 0, ChunkManager.ChunkData.ChunkSizeY, Slider.SliderMode.Integer)
            {
                Orient = Slider.Orientation.Vertical,
                ToolTip = "Controls the maximum height of visible terrain",
                DrawLabel = false
            };

            layout.SetComponentPosition(LevelSlider, 0, 1, 1, 6);
            LevelSlider.OnClicked += LevelSlider_OnClicked;
            LevelSlider.InvertValue = true;
            */

            MiniMap = new Minimap(GUI, layout, 192, 192, this, TextureManager.GetTexture(ContentPaths.Terrain.terrain_colormap), TextureManager.GetTexture(ContentPaths.GUI.gui_minimap))
            {
                IsVisible =  true
            };

            layout.SetComponentPosition(MiniMap, 0, 8, 4, 4);
            Rectangle rect = layout.GetRect(new Rectangle(0, 8, 4, 4));
            layout.SetComponentOffset(MiniMap,  new Point(0, rect.Height - 250));

            Button moneyButton = new Button(GUI, layout, "Economy", GUI.SmallFont, Button.ButtonMode.ImageButton, new ImageFrame(TextureManager.GetTexture(ContentPaths.GUI.icons), 32, 2, 1))
            {
                KeepAspectRatio = true,
                ToolTip = "Opens the Economy Menu",
                DontMakeBigger = true,
                DrawFrame = true,
                TextColor = Color.White
            };

            moneyButton.OnClicked += moneyButton_OnClicked;

            Button settingsButton = new Button(GUI, layout, "Settings", GUI.SmallFont, Button.ButtonMode.ImageButton, new ImageFrame(TextureManager.GetTexture(ContentPaths.GUI.icons), 32, 4, 1))
            {
                KeepAspectRatio = true,
                ToolTip = "Opens the Settings Menu",
                DontMakeBigger = true,
                DrawFrame = true,
                TextColor = Color.White
            };

            settingsButton.OnClicked += OpenPauseMenu;

            layout.SetComponentPosition(settingsButton, 10, 0, 1, 1);

            layout.SetComponentPosition(moneyButton, 9, 0, 1, 1);

            InputManager.KeyReleasedCallback -= InputManager_KeyReleasedCallback;
            InputManager.KeyReleasedCallback += InputManager_KeyReleasedCallback;

            AnnouncementViewer = new AnnouncementViewer(GUI, layout, AnnouncementManager);
            layout.SetComponentPosition(AnnouncementViewer, 3, 10, 3, 1);
            layout.UpdateSizes();
        }
Esempio n. 53
0
        protected override async void  OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.DeliveryNotification);
            dbConfig.ServiceURL           = "https://026821060357.signin.aws.amazon.com/console/dynamobdb/";
            dbConfig.AuthenticationRegion = "dynamodb.us-east-1.amazonaws.com";
            dbConfig.RegionEndpoint       = RegionEndpoint.USEast1;
            EditText             edtDeliveryMessage      = FindViewById <EditText>(Resource.Id.edtDeliveryMessage);
            AmazonDynamoDBClient dynDBClient             = new AmazonDynamoDBClient("AKIAIMDIMZSEHYRAI6CQ", "6B2FRtd4JZiwq2iqiQJOmJPytboQ7EDOb08xovN3", dbConfig.RegionEndpoint);
            GridLayout           grdDeliveryNotification = FindViewById <GridLayout>(Resource.Id.grdDeliveryNotification);

            //dynDBClient.Config.ServiceURL= "https://console.aws.amazon.com/dynamodb/";
            dynDBClient.Config.ServiceURL     = "https://026821060357.signin.aws.amazon.com/console/dynamodb/";
            dynDBClient.Config.RegionEndpoint = RegionEndpoint.USEast1;
            DynamoDBContext dynContext = new DynamoDBContext(dynDBClient);
            Button          btnHome    = FindViewById <Button>(Resource.Id.btnHome);
            AsyncSearch <DeliveryNotification> listDeliveries = dynContext.FromScanAsync <DeliveryNotification>(new ScanOperationConfig()
            {
                ConsistentRead = true
            });


            List <DeliveryNotification> lstDataDeliveries = await listDeliveries.GetRemainingAsync();


            AsyncSearch <CreditCardNotification> listCCNotification = dynContext.FromScanAsync <CreditCardNotification>(new ScanOperationConfig()
            {
                ConsistentRead = true
            });


            List <CreditCardNotification> lstDataCCNotification = await listCCNotification.GetRemainingAsync();

            var theDeliveries = from aDelivery in lstDataDeliveries
                                where aDelivery.NotifyID == 0
                                select aDelivery;
            int newDeliveryCount = 0;

            foreach (DeliveryNotification deliv in lstDataDeliveries)
            {
                if (deliv.DeliveryItemID == 0)
                {
                    break;
                }
                TextView tvSubject = new TextView(this);
                tvSubject.Text = string.Concat(deliv.CustomerName, " ", deliv.ProductDescription, " ", deliv.DeliveryDate);
                tvSubject.SetBackgroundResource(Resource.Drawable.StoreName);
                tvSubject.SetTextColor(Android.Graphics.Color.Black);
                if (deliv.NotifyID == 0)
                {
                    ++newDeliveryCount;
                    tvSubject.SetTypeface(Android.Graphics.Typeface.Default, Android.Graphics.TypefaceStyle.Bold);
                }
                tvSubject.Click += (sender, e) =>
                {
                    CreditCardNotification ccPurchaseQuery = lstDataCCNotification.Find(x => x.CardNumber == deliv.CreditCardNum && x.ItemDescription == deliv.ProductDescription && x.Amount == deliv.Cost);
                    string        strMerchant = ccPurchaseQuery.Merchant;
                    string        strCCNum    = ccPurchaseQuery.CardNumber;
                    StringBuilder sbMessage   = new StringBuilder();
                    sbMessage.Append(deliv.CustomerName + " ordered " + deliv.ProductDescription + " from " + strMerchant);
                    sbMessage.AppendLine(" for " + deliv.Cost.ToString() + " to be delivered at ");
                    sbMessage.AppendLine(deliv.CustomerAddress + ", " + deliv.CustomerCity + ", " + deliv.CustomerState + ", " + deliv.CustomerZip);
                    sbMessage.AppendLine(" on " + deliv.DeliveryDate + " time: " + deliv.DeliveryTime + ", CC#" + strCCNum);
                    edtDeliveryMessage.Text = sbMessage.ToString();
                    // edtDeliveryMessage.Text = string.Format("{0} ordered {1} from {2} for {3} to be delivered at {4}, {5}, {6}, {7} on {8}, Time: {9) CC# {10}", deliv.CustomerName, deliv.ProductDescription,strMerchant,deliv.Cost, deliv.CustomerAddress, deliv.CustomerCity, deliv.CustomerState, deliv.CustomerZip,deliv.DeliveryDate, deliv.DeliveryTime,strCCNum);
                };
                grdDeliveryNotification.AddView(tvSubject);
            }
            if (newDeliveryCount > 0)
            {
                var dlgNewDeliveryNote = new AlertDialog.Builder(this);
                dlgNewDeliveryNote.SetMessage("You have new orders to deliver.");
                dlgNewDeliveryNote.SetNeutralButton("OK", delegate { });
                dlgNewDeliveryNote.Show();
            }
            btnHome.Click += (sender, e) =>
            {
                var intentHomeScreen = new Intent(this, typeof(GoShoppingActivity));
                StartActivity(intentHomeScreen);
            };
        }
Esempio n. 54
0
        public CarouselSnapGallery()
        {
            //On<iOS>().SetLargeTitleDisplay(LargeTitleDisplayMode.Never);

            var viewModel = new CarouselItemsGalleryViewModel(false, false);

            Title = $"CarouselView Snap Options";

            var layout = new Grid
            {
                RowDefinitions = new RowDefinitionCollection
                {
                    new RowDefinition {
                        Height = GridLength.Auto
                    },
                    new RowDefinition {
                        Height = GridLength.Auto
                    },
                    new RowDefinition {
                        Height = GridLength.Star
                    }
                }
            };

            var snapPointsStack = new StackLayout
            {
                Margin = new Thickness(12)
            };

            var snapPointsLabel = new Label {
                FontSize = 10, Text = "SnapPointsType:"
            };
            var snapPointsTypes = Enum.GetNames(typeof(SnapPointsType)).Select(b => b).ToList();

            var snapPointsTypePicker = new Microsoft.Maui.Controls.Picker
            {
                ItemsSource  = snapPointsTypes,
                SelectedItem = snapPointsTypes[1]
            };

            snapPointsStack.Children.Add(snapPointsLabel);
            snapPointsStack.Children.Add(snapPointsTypePicker);

            layout.Children.Add(snapPointsStack);

            var snapPointsAlignmentsStack = new StackLayout
            {
                Margin = new Thickness(12)
            };

            var snapPointsAlignmentsLabel = new Label {
                FontSize = 10, Text = "SnapPointsAlignment:"
            };
            var snapPointsAlignments = Enum.GetNames(typeof(SnapPointsAlignment)).Select(b => b).ToList();

            var snapPointsAlignmentPicker = new Picker
            {
                ItemsSource  = snapPointsAlignments,
                SelectedItem = snapPointsAlignments[0]
            };

            snapPointsAlignmentsStack.Children.Add(snapPointsAlignmentsLabel);
            snapPointsAlignmentsStack.Children.Add(snapPointsAlignmentPicker);

            GridLayout.SetRow(snapPointsAlignmentsStack, 1);
            layout.Children.Add(snapPointsAlignmentsStack);

            var itemsLayout = new LinearItemsLayout(ItemsLayoutOrientation.Horizontal)
            {
                SnapPointsType      = SnapPointsType.Mandatory,
                SnapPointsAlignment = SnapPointsAlignment.Start
            };

            var itemTemplate = GetCarouselTemplate();

            var carouselView = new CarouselView
            {
                ItemsSource     = viewModel.Items,
                ItemsLayout     = itemsLayout,
                ItemTemplate    = itemTemplate,
                BackgroundColor = Colors.LightGray,
                PeekAreaInsets  = new Thickness(0, 0, 100, 0),
                Margin          = new Thickness(12),
                AutomationId    = "TheCarouselView"
            };

            GridLayout.SetRow(carouselView, 2);
            layout.Children.Add(carouselView);


            snapPointsTypePicker.SelectedIndexChanged += (sender, e) =>
            {
                if (carouselView.ItemsLayout is LinearItemsLayout linearItemsLayout)
                {
                    Enum.TryParse(snapPointsTypePicker.SelectedItem.ToString(), out SnapPointsType snapPointsType);
                    linearItemsLayout.SnapPointsType = snapPointsType;
                }
            };

            snapPointsAlignmentPicker.SelectedIndexChanged += (sender, e) =>
            {
                if (carouselView.ItemsLayout is LinearItemsLayout linearItemsLayout)
                {
                    Enum.TryParse(snapPointsAlignmentPicker.SelectedItem.ToString(), out SnapPointsAlignment snapPointsAlignment);
                    linearItemsLayout.SnapPointsAlignment = snapPointsAlignment;
                }
            };

            Content        = layout;
            BindingContext = viewModel;
        }
Esempio n. 55
0
        private void UpdateSelection()
        {
            if (SelectedDescriptor == null || !SelectedDescriptor.IsLoaded)
            {
                return;
            }

            PropertiesPanel.ClearChildren();
            GridLayout layout = new GridLayout(GUI, PropertiesPanel, 5, 1);

            ImagePanel worldPanel = new ImagePanel(GUI, layout, SelectedDescriptor.Button.Image)
            {
                KeepAspectRatio = true
            };
            layout.SetComponentPosition(worldPanel, 0, 1, 1, 1);

            Label worldLabel = new Label(GUI, PropertiesPanel, SelectedDescriptor.Button.Text, GUI.DefaultFont);
            layout.SetComponentPosition(worldLabel, 0, 2, 1, 1);

            Button loadButton = new Button(GUI, layout, "Load", GUI.DefaultFont, Button.ButtonMode.ToolButton,
                GUI.Skin.GetSpecialFrame(GUISkin.Tile.Save));

            layout.SetComponentPosition(loadButton, 0, 3, 1, 1);

            loadButton.OnClicked += loadButton_OnClicked;

            Button deleteButton = new Button(GUI, layout, "Delete", GUI.DefaultFont, Button.ButtonMode.ToolButton, GUI.Skin.GetSpecialFrame(GUISkin.Tile.Ex));
            layout.SetComponentPosition(deleteButton, 0, 4, 1, 1);

            deleteButton.OnClicked += deleteButton_OnClicked;
        }
Esempio n. 56
0
        public override void FloodFill(GridLayout grid, GameObject brushTarget, Vector3Int position)
        {
            var zPosition = new Vector3Int(position.x, position.y, z);

            base.FloodFill(grid, brushTarget, zPosition);
        }
Esempio n. 57
0
        /// <summary>
        /// Called whenever the escape button is pressed. Opens a small menu for saving/loading, etc.
        /// </summary>
        public void OpenPauseMenu()
        {
            if (PausePanel != null && PausePanel.IsVisible) return;

            Paused = true;

            int w = 200;
            int h = 200;

            PausePanel = new Panel(GUI, GUI.RootComponent)
            {
                LocalBounds = new Rectangle(GraphicsDevice.Viewport.Width / 2 - w / 2, GraphicsDevice.Viewport.Height / 2 - h / 2, w, h)
            };

            GridLayout pauseLayout = new GridLayout(GUI, PausePanel, 1, 1);

            ListSelector pauseSelector = new ListSelector(GUI, pauseLayout)
            {
                Label = "-Menu-",
                DrawPanel = false,
                Mode = ListItem.SelectionMode.Selector
            };
            pauseLayout.SetComponentPosition(pauseSelector, 0, 0, 1, 1);
            pauseLayout.UpdateSizes();
            pauseSelector.AddItem("Continue");
            pauseSelector.AddItem("Options");
            pauseSelector.AddItem("Save");
            pauseSelector.AddItem("Quit");

            pauseSelector.OnItemClicked += () => pauseSelector_OnItemClicked(pauseSelector);
        }
Esempio n. 58
0
        public override void PaintPreview(GridLayout grid, GameObject brushTarget, Vector3Int position)
        {
            var zPosition = new Vector3Int(position.x, position.y, coordinateBrush.z);

            base.PaintPreview(grid, brushTarget, zPosition);
        }
Esempio n. 59
0
        void Initialize()
        {
            GUI = new DwarfGUI(Game, Game.Content.Load<SpriteFont>(ContentPaths.Fonts.Default), Game.Content.Load<SpriteFont>(ContentPaths.Fonts.Title), Game.Content.Load<SpriteFont>(ContentPaths.Fonts.Small), Input)
            {
                DebugDraw = false
            };
            IsInitialized = true;
            Drawer = new Drawer2D(Game.Content, Game.GraphicsDevice);
            MainWindow = new Panel(GUI, GUI.RootComponent)
            {
                LocalBounds = new Rectangle(EdgePadding, EdgePadding, Game.GraphicsDevice.Viewport.Width - EdgePadding * 2, Game.GraphicsDevice.Viewport.Height - EdgePadding * 2)
            };
            Layout = new GridLayout(GUI, MainWindow, 11, 4);
            Label title = new Label(GUI, Layout, "You Lose!", GUI.TitleFont);
            Layout.SetComponentPosition(title, 0, 0, 4, 4);

            Label text = new Label(GUI, Layout,
                "The heady days of exploration for " + PlayState.Master.Faction.Economy.Company.Name +
                " are no more.\n Our stock is through the floor. Our investors have all jumped ship! \n We are going to have to sell the company. If only we had shipped more goods...",
                GUI.DefaultFont)
            {
                WordWrap = true
            };

            Layout.SetComponentPosition(text, 0, 4, 4, 4);

            Button okButton = new Button(GUI, Layout, "OK", GUI.DefaultFont, Button.ButtonMode.PushButton, null);
            okButton.OnClicked += okButton_OnClicked;
            Layout.SetComponentPosition(okButton, 2, 10, 2, 1);
            Layout.UpdateSizes();
        }
        public static void Generate(Labyrinth labyrinth, GridLayout layout, Context context)
        {
            foreach (Room room in labyrinth.Rooms)
            {
                ImageView cell = new ImageView(context);

                cell.SetImageResource(Resource.Drawable.Cell);

                if (room.AdjacentRooms.Count == 1)
                {
                    int direction = 0;

                    foreach (Room adjacent in room.AdjacentRooms)
                    {
                        if (adjacent.XCoord > room.XCoord)
                        {
                            direction += 3;
                        }
                        if (adjacent.XCoord < room.XCoord)
                        {
                            direction += 8;
                        }
                        if (adjacent.YCoord > room.YCoord)
                        {
                            direction += 4;
                        }
                        if (adjacent.YCoord < room.YCoord)
                        {
                            direction += 2;
                        }
                    }

                    if (direction == 3)
                    {
                        cell.Rotation = -90;
                    }
                    if (direction == 8)
                    {
                        cell.Rotation = 90;
                    }
                    if (direction == 4)
                    {
                        cell.Rotation = 0;
                    }
                    if (direction == 2)
                    {
                        cell.Rotation = 180;
                    }

                    cell.SetImageResource(Resource.Drawable.ThreeBound);
                }

                if (room.AdjacentRooms.Count == 2)
                {
                    int direction = 0;

                    foreach (Room adjacent in room.AdjacentRooms)
                    {
                        if (adjacent.XCoord > room.XCoord)
                        {
                            direction += 3;
                        }
                        if (adjacent.XCoord < room.XCoord)
                        {
                            direction += 8;
                        }
                        if (adjacent.YCoord > room.YCoord)
                        {
                            direction += 4;
                        }
                        if (adjacent.YCoord < room.YCoord)
                        {
                            direction += 2;
                        }
                    }

                    if (direction == 10)
                    {
                        cell.Rotation = 90;
                    }
                    if (direction == 7 || direction == 11)
                    {
                        cell.Rotation = -90;
                    }
                    if (direction == 5)
                    {
                        cell.Rotation = 180;
                    }
                    if (direction == 12)
                    {
                        cell.Rotation = 0;
                    }

                    if (room.AdjacentRooms[0].XCoord == room.AdjacentRooms[1].XCoord ||
                        room.AdjacentRooms[0].YCoord == room.AdjacentRooms[1].YCoord)
                    {
                        cell.SetImageResource(Resource.Drawable.TwoBoundPar);
                    }
                    else
                    {
                        cell.SetImageResource(Resource.Drawable.TwoBoundCor);
                    }
                }

                if (room.AdjacentRooms.Count == 3)
                {
                    int direction = 0;

                    foreach (Room adjacent in room.AdjacentRooms)
                    {
                        if (adjacent.XCoord > room.XCoord)
                        {
                            direction += 3;
                        }
                        if (adjacent.XCoord < room.XCoord)
                        {
                            direction += 8;
                        }
                        if (adjacent.YCoord > room.YCoord)
                        {
                            direction += 4;
                        }
                        if (adjacent.YCoord < room.YCoord)
                        {
                            direction += 2;
                        }
                    }

                    if (direction == 15)
                    {
                        cell.Rotation = -90;
                    }
                    if (direction == 14)
                    {
                        cell.Rotation = 0;
                    }
                    if (direction == 13)
                    {
                        cell.Rotation = 90;
                    }
                    if (direction == 9)
                    {
                        cell.Rotation = 180;
                    }

                    cell.SetImageResource(Resource.Drawable.OneBound);
                }
                if (room == labyrinth.Finish)
                {
                    cell.SetImageResource(Resource.Drawable.Cell);
                }

                cell.TranslationX = room.XCoord;
                cell.TranslationY = room.YCoord;

                layout.AddView(cell);
            }
        }