Preliminary support for tabs and also fix an issue with scroll view collider

- Added preliminary support for tabs: Added config support for "categoryType" specifying "none" or "auto". None means no tabs. Auto means that we create 3 tabs - Quest, Go/GearVR and 2D. These apps types are distinguished based on package information.
- Added support in UI for showing / hiding 2D apps.
- Fixed an issue with scroll view collider: Looks like Unity UI scroll view object does not interact very well in a VR environment. This one was a doozy. I noticed, although the scroll view masks UI that falls outside its rectangle (as it should), it does not suppress colliders. This means that it's possible to interact with colliders that get scrolled above the scroll view (i.e. like clicking on a cell to launch an app when that cell is outside the scroll view). The bigger problem is that this interfered with the tabs, which are above the scroll view. After contemplating several solutions, I ended up with a simple but effective one:
            // To fix this issue, we cast a ray from current pointer to the scroll view's box collider.
            // If we get a hit, it means we're inside the scroll view - so we enable all the children box
            // colliders, which will behave as expected.
            // If we do not get a hit, it means that we're outside the scroll view - so we disable all the children
            // box colliders, which addresses the issue above.
This commit is contained in:
tverona1
2019-07-27 16:48:07 -07:00
parent de5225c19a
commit 3eb5fd2198
12 changed files with 1063 additions and 421 deletions
+8
View File
@@ -12,6 +12,11 @@ namespace QuestAppLauncher
[Serializable]
public class Config
{
// Supported category types
public const string Category_None = "none";
public const string Category_Auto = "auto";
public const string Category_Custom = "custom";
/// <summary>
/// Grid size
/// </summary>
@@ -24,6 +29,9 @@ namespace QuestAppLauncher
public GridSize gridSize = new GridSize();
public bool show2D = false;
// Category types: "none", "automatic", "custom"
public string categoryType = Category_Auto;
}
/// <summary>
+190 -79
View File
@@ -26,17 +26,35 @@ namespace QuestAppLauncher
const string IconOverrideExtSearch = "*.jpg";
// Grid container game object
public GameObject gridContainer;
public GameObject panelContainer;
// Grid content game object
public GameObject gridContent;
// Scroll container game object
public GameObject scrollContainer;
// App info GameObject (a cell in the grid content)
public GameObject prefab;
// Tab container
public GameObject tabContainer;
// Tracking space
public GameObject trackingSpace;
// App info prefab (a cell in the grid content)
public GameObject prefabCell;
// Scroll view prefab
public GameObject prefabScrollView;
// Tab prefab
public GameObject prefabTab;
// Reference to executing populate routine
private Coroutine populateCoroutine;
// Built-in tab names
private const string Tab_None = "None";
private const string Tab_Quest = "Quest";
private const string Tab_Go = "Go/Gear";
private const string Tab_2D = "2D";
#region MonoBehaviour handler
void Start()
@@ -57,7 +75,7 @@ namespace QuestAppLauncher
#endregion
#region Private Functions
/// <summary>
/// Static method for launching an Android app
/// </summary>
@@ -123,7 +141,7 @@ namespace QuestAppLauncher
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
public void SetGridSize(int rows, int cols)
public void SetGridSize(GameObject gridContent, int rows, int cols)
{
// Make sure grid size have sane value
cols = Math.Min(cols, 10);
@@ -132,7 +150,7 @@ namespace QuestAppLauncher
rows = Math.Max(rows, 1);
// Get cell size, spacing & padding from the grid layout
var gridLayoutGroup = this.gridContent.GetComponent<GridLayoutGroup>();
var gridLayoutGroup = gridContent.GetComponent<GridLayoutGroup>();
var cellHeight = gridLayoutGroup.cellSize.y;
var cellWidth = gridLayoutGroup.cellSize.x;
var paddingX = gridLayoutGroup.padding.horizontal;
@@ -150,7 +168,7 @@ namespace QuestAppLauncher
Debug.Log(string.Format("Grid size calculated width x height: {0} x {1}", width, height));
// Adjust grid container rect transform
var gridTransform = this.gridContainer.GetComponent<RectTransform>();
var gridTransform = this.panelContainer.GetComponent<RectTransform>();
gridTransform.sizeDelta = new Vector2(width, height);
// Adjust grid container Y position to maintain constant height.
@@ -185,21 +203,26 @@ namespace QuestAppLauncher
Config config = new Config();
ConfigPersistence.LoadConfig(config);
// Clear any existing elements in grid
for (int i = 0; i < this.gridContent.transform.childCount; i++)
{
Destroy(this.gridContent.transform.GetChild(i).gameObject);
}
// Set grid size
SetGridSize(config.gridSize.rows, config.gridSize.cols);
using (AndroidJavaClass unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
using (AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity"))
{
// Dictionary to hold package name -> app index, app name
var packageNameToAppName = new Dictionary<string, (int Index, string AppName)>();
var packageNameToAppName = new Dictionary<string, (int Index, string TabName, string AppName)>();
var excludedPackageNames = new HashSet<string>();
var tabList = new List<string>();
if (config.categoryType.Equals(Config.Category_None, StringComparison.OrdinalIgnoreCase))
{
// If no categories, just create a placeholder tab
tabList.Add(Tab_None);
}
else
{
// Create built-in categories
tabList.Add(Tab_Quest);
tabList.Add(Tab_Go);
tabList.Add(Tab_2D);
}
// Get # of installed apps
int numApps = currentActivity.Call<int>("getSize");
@@ -236,19 +259,30 @@ namespace QuestAppLauncher
continue;
}
if (!config.show2D)
// Determine app type (Quest, Go or 2D)
string tabName;
if (currentActivity.Call<bool>("is2DApp", i))
{
var is2D = currentActivity.Call<bool>("is2DApp", i);
if (is2D)
if (!config.show2D)
{
// Skip 2D apps
Debug.LogFormat("Skipping 2D [{0}] Package: {1}, name: {2}", i, packageName, appName);
continue;
}
tabName = Tab_2D;
}
else if (currentActivity.Call<bool>("isQuestApp", i))
{
tabName = Tab_Quest;
}
else
{
tabName = Tab_Go;
}
packageNameToAppName.Add(packageName, (i, appName));
Debug.Log("[" + i + "] package: " + packageName + ", name: " + appName);
packageNameToAppName.Add(packageName, (i, tabName, appName));
Debug.LogFormat("[{0}] package: {1}, name: {2}, tab: {3}", i, packageName, appName, tabName);
yield return null;
}
@@ -264,7 +298,8 @@ namespace QuestAppLauncher
var entry = overriddenName.Split(',');
if (2 == entry.Length && packageNameToAppName.ContainsKey(entry[0]))
{
packageNameToAppName[entry[0]] = (packageNameToAppName[entry[0]].Index, entry[1]);
packageNameToAppName[entry[0]] = (packageNameToAppName[entry[0]].Index,
packageNameToAppName[entry[0]].TabName, entry[1]);
}
}
}
@@ -296,60 +331,136 @@ namespace QuestAppLauncher
yield return null;
// Populate grid with app information (name & icon)
// Sort by app name
foreach (var app in packageNameToAppName.OrderBy(key => key.Value.AppName))
{
// Create new instances of our app info prefab
var newObj = (GameObject)Instantiate(this.prefab, this.gridContent.transform);
// Set app entry info
var appEntry = newObj.GetComponent("AppEntry") as AppEntry;
appEntry.packageId = app.Key;
appEntry.appName = app.Value.AppName;
// Get app icon
byte[] bytesIcon = null;
bool useApkIcon = true;
if (iconOverrides.ContainsKey(app.Key))
{
// Use overridden icon
try
{
bytesIcon = File.ReadAllBytes(iconOverrides[app.Key]);
useApkIcon = false;
}
catch (Exception e)
{
// Fall back to using the apk icon
Debug.Log(string.Format("Error reading app icon from file [{0}]: {1}", iconOverrides[app.Key], e.Message));
}
}
if (useApkIcon)
{
// Use built-in icon from the apk
bytesIcon = (byte[])(Array)currentActivity.Call<sbyte[]>("getIcon", app.Value.Index);
}
// Set the icon image
var image = newObj.transform.Find("AppIcon").GetComponentInChildren<Image>();
var texture = new Texture2D(2, 2, TextureFormat.RGB24, false);
texture.filterMode = FilterMode.Trilinear;
texture.anisoLevel = 16;
texture.LoadImage(bytesIcon);
var rect = new Rect(0, 0, texture.width, texture.height);
image.sprite = Sprite.Create(texture, rect, new Vector2(0.5f, 0.5f));
// Set app name in text
var text = newObj.transform.Find("AppName").GetComponentInChildren<TextMeshProUGUI>();
text.text = app.Value.AppName;
yield return null;
}
// Populate the panel content
yield return PopulatePanelContent(currentActivity, config, tabList, packageNameToAppName, iconOverrides);
}
}
private IEnumerator PopulatePanelContent(
AndroidJavaObject currentActivity,
Config config,
List<string> tabList,
Dictionary<string, (int Index, string TabName, string AppName)> apps,
Dictionary<string, string> iconOverrides)
{
// Destroy existing scrollviews and tabs
for (int i = 0; i < this.tabContainer.transform.childCount; i++)
{
Destroy(this.tabContainer.transform.GetChild(i).gameObject);
Destroy(this.scrollContainer.transform.GetChild(i).gameObject);
}
var gridContents = new Dictionary<string, (GameObject gridContent, GameObject scrollView, GameObject tab, bool isInUse)>();
bool isFirstTab = true;
// Create scroll views and tabs
foreach (string tabName in tabList)
{
Debug.LogFormat("Populating tab '{0}'", tabName);
// Create scroll view
var scrollView = (GameObject)Instantiate(this.prefabScrollView, this.scrollContainer.transform);
var scrollRectOverride = scrollView.GetComponent<ScrollRectOverride>();
scrollRectOverride.trackingSpace = this.trackingSpace.transform;
scrollRectOverride.name = tabName;
var gridContent = scrollRectOverride.content.gameObject;
scrollView.SetActive(isFirstTab);
// Set grid size
SetGridSize(gridContent, config.gridSize.rows, config.gridSize.cols);
// Create tab
var tab = (GameObject)Instantiate(this.prefabTab, this.tabContainer.transform);
tab.GetComponentInChildren<TextMeshProUGUI>().text = tabName;
var toggle = tab.GetComponent<Toggle>();
toggle.isOn = isFirstTab;
toggle.group = this.tabContainer.GetComponent<ToggleGroup>();
toggle.onValueChanged.AddListener(scrollView.SetActive);
if (config.categoryType.Equals(Config.Category_None, StringComparison.OrdinalIgnoreCase))
{
// Hide the "None" tab
tab.SetActive(false);
}
// Record the grid content
gridContents[tabName] = (scrollView.GetComponent<ScrollRect>().content.gameObject,
scrollView, tab, false);
isFirstTab = false;
}
// Populate grid with app information (name & icon)
// Sort by app name
foreach (var app in apps.OrderBy(key => key.Value.AppName))
{
// Create new instances of our app info prefabCell
var gridContent = gridContents[app.Value.TabName].gridContent;
var newObj = (GameObject)Instantiate(this.prefabCell, gridContent.transform);
// Mark that this grid content is in use
gridContents[app.Value.TabName] = (gridContent, gridContents[app.Value.TabName].scrollView,
gridContents[app.Value.TabName].tab, true);
// Set app entry info
var appEntry = newObj.GetComponent("AppEntry") as AppEntry;
appEntry.packageId = app.Key;
appEntry.appName = app.Value.AppName;
// Get app icon
byte[] bytesIcon = null;
bool useApkIcon = true;
if (iconOverrides.ContainsKey(app.Key))
{
// Use overridden icon
try
{
bytesIcon = File.ReadAllBytes(iconOverrides[app.Key]);
useApkIcon = false;
}
catch (Exception e)
{
// Fall back to using the apk icon
Debug.Log(string.Format("Error reading app icon from file [{0}]: {1}", iconOverrides[app.Key], e.Message));
}
}
if (useApkIcon)
{
// Use built-in icon from the apk
bytesIcon = (byte[])(Array)currentActivity.Call<sbyte[]>("getIcon", app.Value.Index);
}
// Set the icon image
var image = newObj.transform.Find("AppIcon").GetComponentInChildren<Image>();
var texture = new Texture2D(2, 2, TextureFormat.RGB24, false);
texture.filterMode = FilterMode.Trilinear;
texture.anisoLevel = 16;
texture.LoadImage(bytesIcon);
var rect = new Rect(0, 0, texture.width, texture.height);
image.sprite = Sprite.Create(texture, rect, new Vector2(0.5f, 0.5f));
// Set app name in text
var text = newObj.transform.Find("AppName").GetComponentInChildren<TextMeshProUGUI>();
text.text = app.Value.AppName;
yield return null;
}
// Remove any empty scroll views and tabs
foreach (string tabName in tabList)
{
if (gridContents[tabName].isInUse)
{
continue;
}
Debug.LogFormat("Removing empty tab '{0}'", tabName);
Destroy(gridContents[tabName].scrollView);
Destroy(gridContents[tabName].tab);
}
}
#endregion
}
}
#endregion
}
+84
View File
@@ -2,21 +2,77 @@
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using ControllerSelection;
namespace QuestAppLauncher
{
public class ScrollRectOverride : ScrollRect, IMoveHandler, IPointerClickHandler, IScrollHandler
{
// Scrolling speed multiplier
private const float speedMultiplier = 15f;
// Height of a single cell in the grid
private float cellHeight = 0f;
// Tracking space used for ray cast
public Transform trackingSpace = null;
// Box collider used for ray cast
private BoxCollider boxCollider = null;
// Whether the pointer is within bounds of the scroll rect
private bool isInBounds = false;
private OVRInput.Controller activeController = OVRInput.Controller.None;
void Start()
{
this.cellHeight = this.transform.GetComponentInChildren<GridLayoutGroup>().cellSize.y;
this.boxCollider = GetComponent<BoxCollider>();
}
void Update()
{
// The scroll view has a viewport that masks the UI that is outside the scroll view.
// However, it does not filter any ray casting that is outside the mask!
// This means that the box colliders of the individual cells still get hit outside the scroll view itself,
// which can interfer with the tabs above the scroll view.
//
// To fix this issue, we cast a ray from current pointer to the scroll view's box collider.
// If we get a hit, it means we're inside the scroll view - so we enable all the children box
// colliders, which will behave as expected.
// If we do not get a hit, it means that we're outside the scroll view - so we disable all the children
// box colliders, which addresses the issue above.
this.activeController = OVRInputHelpers.GetControllerForButton(OVRInput.Button.PrimaryIndexTrigger, this.activeController);
Ray pointer = OVRInputHelpers.GetSelectionRay(this.activeController, this.trackingSpace);
RaycastHit hit;
if (this.boxCollider.Raycast(pointer, out hit, 500))
{
// We got a hit in the scroll view. Check if we're already within the bounds - if so, do nothing.
if (!isInBounds)
{
// We entered the scroll view, so enable box colliders on children.
foreach (var boxCollider in this.content.gameObject.GetComponentsInChildren<BoxCollider>())
{
boxCollider.enabled = true;
}
isInBounds = true;
}
}
else if (isInBounds)
{
// We are outside the scroll view and were previously inside, so disable box colliders on children.
Debug.Log("ScrollRectOverride: Disabling box colliders on children");
foreach (var boxCollider in this.content.gameObject.GetComponentsInChildren<BoxCollider>())
{
boxCollider.enabled = false;
}
isInBounds = false;
}
// Get vector from either left or right thumbstick
var moveVector = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick);
if (moveVector.x == 0 && moveVector.y == 0)
@@ -24,6 +80,12 @@ namespace QuestAppLauncher
moveVector = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick);
}
if (moveVector.y == 0)
{
// No y-movement, so return
return;
}
// Scroll by a fixed amount proportional to thumbstick position on each frame
// and map this to a fraction of the total viewport size:
// moveVector.y: The thumbstick vertical position normalized to [-1,1].
@@ -36,6 +98,28 @@ namespace QuestAppLauncher
this.verticalNormalizedPosition = Mathf.Clamp01(this.verticalNormalizedPosition + verticalIncrement);
}
void OnEnable()
{
// When this scroll view is enabled, make sure we resize the box collider appropriately.
ResizeBoxCollider();
}
protected override void OnRectTransformDimensionsChange()
{
// When the scroll view rect size changes, make sure we resize the box collider appropriately.
ResizeBoxCollider();
}
private void ResizeBoxCollider()
{
// Resize the scroll view's box collider to match the scroll view rect size.
var rect = transform.GetComponent<RectTransform>();
var boxCollider = transform.GetComponent<BoxCollider>();
boxCollider.size = new Vector3(rect.rect.width, rect.rect.height, 0);
Debug.LogFormat("Resizing box collider: {0} x {1}", boxCollider.size.x, boxCollider.size.y);
}
public void OnPointerClick(PointerEventData e)
{
}
+1 -8
View File
@@ -84,7 +84,6 @@ namespace QuestAppLauncher
private void PersistConfig()
{
bool saveConfig = false;
bool resizeGrid = false;
bool rePopulate = false;
// Update grid size
@@ -96,7 +95,7 @@ namespace QuestAppLauncher
{
this.config.gridSize.cols = cols;
this.config.gridSize.rows = rows;
resizeGrid = true;
rePopulate = true;
saveConfig = true;
}
@@ -121,12 +120,6 @@ namespace QuestAppLauncher
Debug.Log("Re-populating panel");
this.gridPopulation.GetComponent<GridPopulation>().StartPopulate();
}
else if (resizeGrid)
{
// Update grid size
Debug.Log(string.Format("Resizing pael: {0} x {1}", cols, rows));
this.gridPopulation.GetComponent<GridPopulation>().SetGridSize(this.config.gridSize.rows, this.config.gridSize.cols);
}
}
}
}