From 4855eb2784055acb0e23154876b75a2b5ff15d4f Mon Sep 17 00:00:00 2001 From: Till Schneidereit Date: Thu, 11 Aug 2016 22:37:59 +0200 Subject: [PATCH 001/105] Bug 1293285 - Ignore reentrant calls to the JS shell's drainJobQueue function. r=efaust --- .../tests/promise/no-reentrant-drainjobqueue.js | 10 ++++++++++ js/src/shell/js.cpp | 11 ++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 js/src/jit-test/tests/promise/no-reentrant-drainjobqueue.js diff --git a/js/src/jit-test/tests/promise/no-reentrant-drainjobqueue.js b/js/src/jit-test/tests/promise/no-reentrant-drainjobqueue.js new file mode 100644 index 000000000000..7db07bdc73ee --- /dev/null +++ b/js/src/jit-test/tests/promise/no-reentrant-drainjobqueue.js @@ -0,0 +1,10 @@ +let thenCalled = false; +let p1 = new Promise(res => res('result')).then(val => { + Promise.resolve(1).then(_=>{thenCalled = true;}); + // This reentrant call is ignored. + drainJobQueue(); + assertEq(thenCalled, false); +}); + +drainJobQueue(); +assertEq(thenCalled, true); diff --git a/js/src/shell/js.cpp b/js/src/shell/js.cpp index 765bc8ddc38b..c85e50f90f87 100644 --- a/js/src/shell/js.cpp +++ b/js/src/shell/js.cpp @@ -264,6 +264,7 @@ struct ShellContext JS::PersistentRootedValue promiseRejectionTrackerCallback; JS::PersistentRooted jobQueue; ExclusiveData asyncTasks; + bool drainingJobQueue; #endif // SPIDERMONKEY_PROMISE /* @@ -428,6 +429,7 @@ ShellContext::ShellContext(JSContext* cx) #ifdef SPIDERMONKEY_PROMISE promiseRejectionTrackerCallback(cx, NullValue()), asyncTasks(cx), + drainingJobQueue(false), #endif // SPIDERMONKEY_PROMISE exitCode(0), quitting(false), @@ -771,7 +773,7 @@ DrainJobQueue(JSContext* cx) { #ifdef SPIDERMONKEY_PROMISE ShellContext* sc = GetShellContext(cx); - if (sc->quitting) + if (sc->quitting || sc->drainingJobQueue) return true; // Wait for any outstanding async tasks to finish so that the @@ -792,6 +794,12 @@ DrainJobQueue(JSContext* cx) asyncTasks->finished.clear(); } + // It doesn't make sense for job queue draining to be reentrant. At the + // same time we don't want to assert against it, because that'd make + // drainJobQueue unsafe for fuzzers. We do want fuzzers to test this, so + // we simply ignore nested calls of drainJobQueue. + sc->drainingJobQueue = true; + RootedObject job(cx); JS::HandleValueArray args(JS::HandleValueArray::empty()); RootedValue rval(cx); @@ -808,6 +816,7 @@ DrainJobQueue(JSContext* cx) sc->jobQueue[i].set(nullptr); } sc->jobQueue.clear(); + sc->drainingJobQueue = false; #endif // SPIDERMONKEY_PROMISE return true; } From 4839c748eb08654c0ddaa1c985ecf8ed82ee0963 Mon Sep 17 00:00:00 2001 From: Randall Barker Date: Wed, 24 Aug 2016 10:00:02 -0700 Subject: [PATCH 002/105] Bug 1297850 - part 1, Remove dead code left behind after JPZ removal. r=jchen --- gfx/layers/client/ClientLayerManager.cpp | 28 --- gfx/layers/client/ClientLayerManager.h | 16 -- .../org/mozilla/gecko/prompts/Prompt.java | 4 - .../java/org/mozilla/gecko/GeckoAppShell.java | 14 -- .../mozilla/gecko/gfx/GeckoLayerClient.java | 209 ------------------ .../java/org/mozilla/gecko/gfx/LayerView.java | 24 -- .../gecko/gfx/NativePanZoomController.java | 47 ---- .../mozilla/gecko/gfx/PanZoomController.java | 13 -- .../org/mozilla/gecko/gfx/PanZoomTarget.java | 1 - widget/android/AndroidBridge.cpp | 27 --- widget/android/AndroidBridge.h | 3 - widget/android/GeneratedJNINatives.h | 6 +- widget/android/GeneratedJNIWrappers.cpp | 19 -- widget/android/GeneratedJNIWrappers.h | 63 ------ widget/android/nsWindow.cpp | 19 -- 15 files changed, 1 insertion(+), 492 deletions(-) diff --git a/gfx/layers/client/ClientLayerManager.cpp b/gfx/layers/client/ClientLayerManager.cpp index 68d5d2ca48d9..0acc69260566 100644 --- a/gfx/layers/client/ClientLayerManager.cpp +++ b/gfx/layers/client/ClientLayerManager.cpp @@ -795,34 +795,6 @@ ClientLayerManager::GetBackendName(nsAString& aName) } } -bool -ClientLayerManager::ProgressiveUpdateCallback(bool aHasPendingNewThebesContent, - FrameMetrics& aMetrics, - bool aDrawingCritical) -{ -#ifdef MOZ_WIDGET_ANDROID - MOZ_ASSERT(aMetrics.IsScrollable()); - // This is derived from the code in - // gfx/layers/ipc/CompositorBridgeParent.cpp::TransformShadowTree. - CSSToLayerScale paintScale = aMetrics.LayersPixelsPerCSSPixel().ToScaleFactor(); - const CSSRect& metricsDisplayPort = - (aDrawingCritical && !aMetrics.GetCriticalDisplayPort().IsEmpty()) ? - aMetrics.GetCriticalDisplayPort() : aMetrics.GetDisplayPort(); - LayerRect displayPort = (metricsDisplayPort + aMetrics.GetScrollOffset()) * paintScale; - - ParentLayerPoint scrollOffset; - CSSToParentLayerScale zoom; - bool ret = AndroidBridge::Bridge()->ProgressiveUpdateCallback( - aHasPendingNewThebesContent, displayPort, paintScale.scale, aDrawingCritical, - scrollOffset, zoom); - aMetrics.SetScrollOffset(scrollOffset / zoom); - aMetrics.SetZoom(CSSToParentLayerScale2D(zoom)); - return ret; -#else - return false; -#endif -} - bool ClientLayerManager::AsyncPanZoomEnabled() const { diff --git a/gfx/layers/client/ClientLayerManager.h b/gfx/layers/client/ClientLayerManager.h index 6fd1d8ca1304..ad9f9ea71ea0 100644 --- a/gfx/layers/client/ClientLayerManager.h +++ b/gfx/layers/client/ClientLayerManager.h @@ -155,22 +155,6 @@ public: // Disable component alpha layers with the software compositor. virtual bool ShouldAvoidComponentAlphaLayers() override { return !IsCompositingCheap(); } - /** - * Called for each iteration of a progressive tile update. Updates - * aMetrics with the current scroll offset and scale being used to composite - * the primary scrollable layer in this manager, to determine what area - * intersects with the target composition bounds. - * aDrawingCritical will be true if the current drawing operation is using - * the critical displayport. - * Returns true if the update should continue, or false if it should be - * cancelled. - * This is only called if gfxPlatform::UseProgressiveTilePainting() returns - * true. - */ - bool ProgressiveUpdateCallback(bool aHasPendingNewThebesContent, - FrameMetrics& aMetrics, - bool aDrawingCritical); - bool InConstruction() { return mPhase == PHASE_CONSTRUCTION; } #ifdef DEBUG bool InDrawing() { return mPhase == PHASE_DRAWING; } diff --git a/mobile/android/base/java/org/mozilla/gecko/prompts/Prompt.java b/mobile/android/base/java/org/mozilla/gecko/prompts/Prompt.java index 401c9a999174..11121b2cce7d 100644 --- a/mobile/android/base/java/org/mozilla/gecko/prompts/Prompt.java +++ b/mobile/android/base/java/org/mozilla/gecko/prompts/Prompt.java @@ -179,10 +179,6 @@ public class Prompt implements OnClickListener, OnCancelListener, OnItemClickLis private void create(String title, String text, PromptListItem[] listItems, int choiceMode) throws IllegalStateException { - final LayerView view = GeckoAppShell.getLayerView(); - if (view != null) { - view.abortPanning(); - } AlertDialog.Builder builder = new AlertDialog.Builder(mContext); if (!TextUtils.isEmpty(title)) { diff --git a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoAppShell.java b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoAppShell.java index 8d3913873f91..3e256db3beef 100644 --- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoAppShell.java +++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoAppShell.java @@ -1143,20 +1143,6 @@ public class GeckoAppShell }); } - @WrapForJNI(calledFrom = "gecko") - public static void notifyDefaultPrevented(final boolean defaultPrevented) { - ThreadUtils.postToUiThread(new Runnable() { - @Override - public void run() { - LayerView view = getLayerView(); - PanZoomController controller = (view == null ? null : view.getPanZoomController()); - if (controller != null) { - controller.notifyDefaultActionPrevented(defaultPrevented); - } - } - }); - } - @WrapForJNI(calledFrom = "gecko") public static boolean isNetworkLinkUp() { ConnectivityManager cm = (ConnectivityManager) diff --git a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/GeckoLayerClient.java b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/GeckoLayerClient.java index 696ee6807733..ac586b98f7d6 100644 --- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/GeckoLayerClient.java +++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/GeckoLayerClient.java @@ -89,8 +89,6 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget * fields. */ private volatile ImmutableViewportMetrics mViewportMetrics; - private ZoomConstraints mZoomConstraints; - private volatile boolean mGeckoIsReady; private final PanZoomController mPanZoomController; @@ -125,11 +123,8 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); mViewportMetrics = new ImmutableViewportMetrics(displayMetrics) .setViewportSize(view.getWidth(), view.getHeight()); - mZoomConstraints = new ZoomConstraints(false); - Tab tab = Tabs.getInstance().getSelectedTab(); if (tab != null) { - mZoomConstraints = tab.getZoomConstraints(); mViewportMetrics = mViewportMetrics.setIsRTL(tab.getIsRTL()); } @@ -183,24 +178,6 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget mGeckoIsReady = false; } - /** - * Returns true if this client is fine with performing a redraw operation or false if it - * would prefer that the action didn't take place. - */ - private boolean getRedrawHint() { - if (mForceRedraw) { - mForceRedraw = false; - return true; - } - - if (!mPanZoomController.getRedrawHint()) { - return false; - } - - return DisplayPortCalculator.aboutToCheckerboard(mViewportMetrics, - mPanZoomController.getVelocityVector(), mDisplayPort); - } - public LayerView getView() { return mView; } @@ -318,24 +295,11 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget post(new Runnable() { @Override public void run() { - mPanZoomController.pageRectUpdated(); mView.requestRender(); } }); } - /** Aborts any pan/zoom animation that is currently in progress. */ - private void abortPanZoomAnimation() { - if (mPanZoomController != null) { - post(new Runnable() { - @Override - public void run() { - mPanZoomController.abortAnimation(); - } - }); - } - } - /** * The different types of Viewport messages handled. All viewport events * expect a display-port to be returned, but can handle one not being @@ -346,57 +310,6 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget PAGE_SIZE // The viewport's page-size has changed } - /** Viewport message handler. */ - private DisplayPortMetrics handleViewportMessage(ImmutableViewportMetrics messageMetrics, ViewportMessageType type) { - synchronized (getLock()) { - ImmutableViewportMetrics newMetrics; - ImmutableViewportMetrics oldMetrics = getViewportMetrics(); - - switch (type) { - default: - case UPDATE: - // Keep the old viewport size - newMetrics = messageMetrics.setViewportSize(oldMetrics.viewportRectWidth, oldMetrics.viewportRectHeight); - if (mToolbarAnimator.isResizing()) { - // If we're in the middle of a resize, we don't want to clobber - // the scroll offset, so grab the one from the oldMetrics and - // keep using that. We also don't want to abort animations, - // because at that point we're guaranteed to not be animating - // anyway, and calling abortPanZoomAnimation has a nasty - // side-effect of clmaping and clobbering the metrics, which - // we don't want here. - newMetrics = newMetrics.setViewportOrigin(oldMetrics.viewportRectLeft, oldMetrics.viewportRectTop); - break; - } - if (!oldMetrics.fuzzyEquals(newMetrics)) { - abortPanZoomAnimation(); - } - break; - case PAGE_SIZE: - // adjust the page dimensions to account for differences in zoom - // between the rendered content (which is what Gecko tells us) - // and our zoom level (which may have diverged). - float scaleFactor = oldMetrics.zoomFactor / messageMetrics.zoomFactor; - newMetrics = oldMetrics.setPageRect(RectUtils.scale(messageMetrics.getPageRect(), scaleFactor), messageMetrics.getCssPageRect()); - break; - } - - // Update the Gecko-side viewport metrics. Make sure to do this - // before modifying the metrics below. - final ImmutableViewportMetrics geckoMetrics = newMetrics.clamp(); - post(new Runnable() { - @Override - public void run() { - mGeckoViewport = geckoMetrics; - } - }); - - setViewportMetrics(newMetrics, type == ViewportMessageType.UPDATE); - mDisplayPort = DisplayPortCalculator.calculate(getViewportMetrics(), null); - } - return mDisplayPort; - } - @WrapForJNI(calledFrom = "gecko") void contentDocumentChanged() { mContentDocumentIsDisplayed = false; @@ -407,112 +320,6 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget return mContentDocumentIsDisplayed; } - // This is called on the Gecko thread to determine if we're still interested - // in the update of this display-port to continue. We can return true here - // to abort the current update and continue with any subsequent ones. This - // is useful for slow-to-render pages when the display-port starts lagging - // behind enough that continuing to draw it is wasted effort. - @WrapForJNI - public ProgressiveUpdateData progressiveUpdateCallback(boolean aHasPendingNewThebesContent, - float x, float y, float width, float height, - float resolution, boolean lowPrecision) { - // Reset the checkerboard risk flag when switching to low precision - // rendering. - if (lowPrecision && !mLastProgressiveUpdateWasLowPrecision) { - // Skip low precision rendering until we're at risk of checkerboarding. - if (!mProgressiveUpdateWasInDanger) { - mProgressiveUpdateData.abort = true; - return mProgressiveUpdateData; - } - mProgressiveUpdateWasInDanger = false; - } - mLastProgressiveUpdateWasLowPrecision = lowPrecision; - - // Grab a local copy of the last display-port sent to Gecko and the - // current viewport metrics to avoid races when accessing them. - DisplayPortMetrics displayPort = mDisplayPort; - ImmutableViewportMetrics viewportMetrics = mViewportMetrics; - mProgressiveUpdateData.setViewport(viewportMetrics); - mProgressiveUpdateData.abort = false; - - // Always abort updates if the resolution has changed. There's no use - // in drawing at the incorrect resolution. - if (!FloatUtils.fuzzyEquals(resolution, viewportMetrics.zoomFactor)) { - Log.d(LOGTAG, "Aborting draw due to resolution change: " + resolution + " != " + viewportMetrics.zoomFactor); - mProgressiveUpdateData.abort = true; - return mProgressiveUpdateData; - } - - // Store the high precision displayport for comparison when doing low - // precision updates. - if (!lowPrecision) { - if (!FloatUtils.fuzzyEquals(resolution, mProgressiveUpdateDisplayPort.resolution) || - !FloatUtils.fuzzyEquals(x, mProgressiveUpdateDisplayPort.getLeft()) || - !FloatUtils.fuzzyEquals(y, mProgressiveUpdateDisplayPort.getTop()) || - !FloatUtils.fuzzyEquals(x + width, mProgressiveUpdateDisplayPort.getRight()) || - !FloatUtils.fuzzyEquals(y + height, mProgressiveUpdateDisplayPort.getBottom())) { - mProgressiveUpdateDisplayPort = - new DisplayPortMetrics(x, y, x + width, y + height, resolution); - } - } - - // If we're not doing low precision draws and we're about to - // checkerboard, enable low precision drawing. - if (!lowPrecision && !mProgressiveUpdateWasInDanger) { - if (DisplayPortCalculator.aboutToCheckerboard(viewportMetrics, - mPanZoomController.getVelocityVector(), mProgressiveUpdateDisplayPort)) { - mProgressiveUpdateWasInDanger = true; - } - } - - // XXX All sorts of rounding happens inside Gecko that becomes hard to - // account exactly for. Given we align the display-port to tile - // boundaries (and so they rarely vary by sub-pixel amounts), just - // check that values are within a couple of pixels of the - // display-port bounds. - - // Never abort drawing if we can't be sure we've sent a more recent - // display-port. If we abort updating when we shouldn't, we can end up - // with blank regions on the screen and we open up the risk of entering - // an endless updating cycle. - if (Math.abs(displayPort.getLeft() - mProgressiveUpdateDisplayPort.getLeft()) <= 2 && - Math.abs(displayPort.getTop() - mProgressiveUpdateDisplayPort.getTop()) <= 2 && - Math.abs(displayPort.getBottom() - mProgressiveUpdateDisplayPort.getBottom()) <= 2 && - Math.abs(displayPort.getRight() - mProgressiveUpdateDisplayPort.getRight()) <= 2) { - return mProgressiveUpdateData; - } - - // Abort updates when the display-port no longer contains the visible - // area of the page (that is, the viewport cropped by the page - // boundaries). - // XXX This makes the assumption that we never let the visible area of - // the page fall outside of the display-port. - if (Math.max(viewportMetrics.viewportRectLeft, viewportMetrics.pageRectLeft) + 1 < x || - Math.max(viewportMetrics.viewportRectTop, viewportMetrics.pageRectTop) + 1 < y || - Math.min(viewportMetrics.viewportRectRight(), viewportMetrics.pageRectRight) - 1 > x + width || - Math.min(viewportMetrics.viewportRectBottom(), viewportMetrics.pageRectBottom) - 1 > y + height) { - Log.d(LOGTAG, "Aborting update due to viewport not in display-port"); - mProgressiveUpdateData.abort = true; - - // Enable low-precision drawing, as we're likely to be in danger if - // this situation has been encountered. - mProgressiveUpdateWasInDanger = true; - - return mProgressiveUpdateData; - } - - // Abort drawing stale low-precision content if there's a more recent - // display-port in the pipeline. - if (lowPrecision && !aHasPendingNewThebesContent) { - mProgressiveUpdateData.abort = true; - } - return mProgressiveUpdateData; - } - - void setZoomConstraints(ZoomConstraints constraints) { - mZoomConstraints = constraints; - } - void setIsRTL(boolean aIsRTL) { synchronized (getLock()) { ImmutableViewportMetrics newMetrics = getViewportMetrics().setIsRTL(aIsRTL); @@ -557,18 +364,8 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget if (tab != null) { mView.setBackgroundColor(tab.getBackgroundColor()); - setZoomConstraints(tab.getZoomConstraints()); } - // At this point, we have just switched to displaying a different document than we - // we previously displaying. This means we need to abort any panning/zooming animations - // that are in progress and send an updated display port request to browser.js as soon - // as possible. The call to PanZoomController.abortAnimation accomplishes this by calling the - // forceRedraw function, which sends the viewport to gecko. The display port request is - // actually a full viewport update, which is fine because if browser.js has somehow moved to - // be out of sync with this first-paint viewport, then we force them back in sync. - abortPanZoomAnimation(); - // Indicate that the document is about to be composited so the // LayerView background can be removed. if (mView.getPaintState() == LayerView.PAINT_START) { @@ -912,12 +709,6 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget return mViewportMetrics; } - /** Implementation of PanZoomTarget */ - @Override - public ZoomConstraints getZoomConstraints() { - return mZoomConstraints; - } - /** Implementation of PanZoomTarget */ @Override public FullScreenState getFullScreenState() { diff --git a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/LayerView.java b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/LayerView.java index 97c7fe2bfc53..0c2290483d62 100644 --- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/LayerView.java +++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/LayerView.java @@ -377,12 +377,6 @@ public class LayerView extends ScrollView implements Tabs.OnTabsChangedListener return mLayerClient.getViewportMetrics(); } - public void abortPanning() { - if (mPanZoomController != null) { - mPanZoomController.abortPanning(); - } - } - public PointF convertViewPointToLayerPoint(PointF viewPoint) { return mLayerClient.convertViewPointToLayerPoint(viewPoint); } @@ -407,27 +401,10 @@ public class LayerView extends ScrollView implements Tabs.OnTabsChangedListener } } - public void setZoomConstraints(ZoomConstraints constraints) { - mLayerClient.setZoomConstraints(constraints); - } - public void setIsRTL(boolean aIsRTL) { mLayerClient.setIsRTL(aIsRTL); } - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - if (!mLayerClient.isGeckoReady()) { - // If gecko isn't loaded yet, don't try sending events to the - // native code because it's just going to crash - return true; - } - if (mPanZoomController != null && mPanZoomController.onKeyEvent(event)) { - return true; - } - return false; - } - public void requestRender() { if (mCompositorCreated) { mCompositor.syncInvalidateAndScheduleComposite(); @@ -795,7 +772,6 @@ public class LayerView extends ScrollView implements Tabs.OnTabsChangedListener @Override public void onTabChanged(Tab tab, Tabs.TabEvents msg, String data) { if (msg == Tabs.TabEvents.VIEWPORT_CHANGE && Tabs.getInstance().isSelectedTab(tab) && mLayerClient != null) { - setZoomConstraints(tab.getZoomConstraints()); setIsRTL(tab.getIsRTL()); } } diff --git a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/NativePanZoomController.java b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/NativePanZoomController.java index c733bd1894a1..2db0d1ac1619 100644 --- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/NativePanZoomController.java +++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/NativePanZoomController.java @@ -190,58 +190,11 @@ class NativePanZoomController extends JNIObject implements PanZoomController { } } - @Override - public boolean onKeyEvent(KeyEvent event) { - // FIXME implement this - return false; - } - @Override public void onMotionEventVelocity(final long aEventTime, final float aSpeedY) { handleMotionEventVelocity(aEventTime, aSpeedY); } - @Override - public PointF getVelocityVector() { - // FIXME implement this - return new PointF(0, 0); - } - - @Override - public void pageRectUpdated() { - // no-op in APZC, I think - } - - @Override - public void abortPanning() { - // no-op in APZC, I think - } - - @Override - public void notifyDefaultActionPrevented(boolean prevented) { - // no-op: This could get called if accessibility is enabled and the events - // are sent to Gecko directly without going through APZ. In this case - // we just want to ignore this callback. - } - - @WrapForJNI(stubName = "AbortAnimation", calledFrom = "ui") - private native void nativeAbortAnimation(); - - @Override // PanZoomController - public void abortAnimation() - { - if (!mDestroyed) { - nativeAbortAnimation(); - } - } - - @Override // PanZoomController - public boolean getRedrawHint() - { - // FIXME implement this - return true; - } - @Override @WrapForJNI(calledFrom = "ui") // PanZoomController public void destroy() { if (mDestroyed || !mTarget.isGeckoReady()) { diff --git a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/PanZoomController.java b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/PanZoomController.java index d0ca251e0e24..be999729d9a4 100644 --- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/PanZoomController.java +++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/PanZoomController.java @@ -14,10 +14,6 @@ import android.view.MotionEvent; import android.view.View; public interface PanZoomController { - // The distance the user has to pan before we recognize it as such (e.g. to avoid 1-pixel pans - // between the touch-down and touch-up of a click). In units of density-independent pixels. - public static final float PAN_THRESHOLD = 1 / 16f * GeckoAppShell.getDpi(); - // Threshold for sending touch move events to content public static final float CLICK_THRESHOLD = 1 / 50f * GeckoAppShell.getDpi(); @@ -31,16 +27,7 @@ public interface PanZoomController { public boolean onTouchEvent(MotionEvent event); public boolean onMotionEvent(MotionEvent event); - public boolean onKeyEvent(KeyEvent event); public void onMotionEventVelocity(final long aEventTime, final float aSpeedY); - public void notifyDefaultActionPrevented(boolean prevented); - - public boolean getRedrawHint(); - public PointF getVelocityVector(); - - public void pageRectUpdated(); - public void abortPanning(); - public void abortAnimation(); public void setOverscrollHandler(final Overscroll controller); diff --git a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/PanZoomTarget.java b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/PanZoomTarget.java index 7d5b8b1eab4d..f3e7231aba6c 100644 --- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/PanZoomTarget.java +++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/PanZoomTarget.java @@ -12,7 +12,6 @@ import android.graphics.PointF; public interface PanZoomTarget { public ImmutableViewportMetrics getViewportMetrics(); - public ZoomConstraints getZoomConstraints(); public FullScreenState getFullScreenState(); public PointF getVisibleEndOfLayerView(); diff --git a/widget/android/AndroidBridge.cpp b/widget/android/AndroidBridge.cpp index 53440efb71fc..3d393564a4b7 100644 --- a/widget/android/AndroidBridge.cpp +++ b/widget/android/AndroidBridge.cpp @@ -1402,33 +1402,6 @@ AndroidBridge::IsContentDocumentDisplayed() return mLayerClient->IsContentDocumentDisplayed(); } -bool -AndroidBridge::ProgressiveUpdateCallback(bool aHasPendingNewThebesContent, - const LayerRect& aDisplayPort, float aDisplayResolution, - bool aDrawingCritical, ParentLayerPoint& aScrollOffset, - CSSToParentLayerScale& aZoom) -{ - if (!mLayerClient) { - ALOG_BRIDGE("Exceptional Exit: %s", __PRETTY_FUNCTION__); - return false; - } - - ProgressiveUpdateData::LocalRef progressiveUpdateData = - mLayerClient->ProgressiveUpdateCallback(aHasPendingNewThebesContent, - (float)aDisplayPort.x, - (float)aDisplayPort.y, - (float)aDisplayPort.width, - (float)aDisplayPort.height, - aDisplayResolution, - !aDrawingCritical); - - aScrollOffset.x = progressiveUpdateData->X(); - aScrollOffset.y = progressiveUpdateData->Y(); - aZoom.scale = progressiveUpdateData->Scale(); - - return progressiveUpdateData->Abort(); -} - class AndroidBridge::DelayedTask { using TimeStamp = mozilla::TimeStamp; diff --git a/widget/android/AndroidBridge.h b/widget/android/AndroidBridge.h index 14958c716459..f66724b28c42 100644 --- a/widget/android/AndroidBridge.h +++ b/widget/android/AndroidBridge.h @@ -151,9 +151,6 @@ public: void ContentDocumentChanged(); bool IsContentDocumentDisplayed(); - bool ProgressiveUpdateCallback(bool aHasPendingNewThebesContent, const LayerRect& aDisplayPort, float aDisplayResolution, bool aDrawingCritical, - mozilla::ParentLayerPoint& aScrollOffset, mozilla::CSSToParentLayerScale& aZoom); - void SetLayerClient(java::GeckoLayerClient::Param jobj); const java::GeckoLayerClient::Ref& GetLayerClient() { return mLayerClient; } diff --git a/widget/android/GeneratedJNINatives.h b/widget/android/GeneratedJNINatives.h index fe1cad852851..88921209b288 100644 --- a/widget/android/GeneratedJNINatives.h +++ b/widget/android/GeneratedJNINatives.h @@ -541,7 +541,7 @@ template class NativePanZoomController::Natives : public mozilla::jni::NativeImpl { public: - static const JNINativeMethod methods[8]; + static const JNINativeMethod methods[7]; }; template @@ -571,10 +571,6 @@ const JNINativeMethod NativePanZoomController::Natives::methods[] = { mozilla::jni::NativeStub ::template Wrap<&Impl::HandleScrollEvent>), - mozilla::jni::MakeNativeMethod( - mozilla::jni::NativeStub - ::template Wrap<&Impl::AbortAnimation>), - mozilla::jni::MakeNativeMethod( mozilla::jni::NativeStub ::template Wrap<&Impl::SetIsLongpressEnabled>) diff --git a/widget/android/GeneratedJNIWrappers.cpp b/widget/android/GeneratedJNIWrappers.cpp index 4bf3ae38650f..f29fe54b9f58 100644 --- a/widget/android/GeneratedJNIWrappers.cpp +++ b/widget/android/GeneratedJNIWrappers.cpp @@ -588,14 +588,6 @@ constexpr char GeckoAppShell::NotifyObservers_t::signature[]; constexpr char GeckoAppShell::NotifyAlertListener_t::name[]; constexpr char GeckoAppShell::NotifyAlertListener_t::signature[]; -constexpr char GeckoAppShell::NotifyDefaultPrevented_t::name[]; -constexpr char GeckoAppShell::NotifyDefaultPrevented_t::signature[]; - -auto GeckoAppShell::NotifyDefaultPrevented(bool a0) -> void -{ - return mozilla::jni::Method::Call(GeckoAppShell::Context(), nullptr, a0); -} - constexpr char GeckoAppShell::NotifyUriVisited_t::name[]; constexpr char GeckoAppShell::NotifyUriVisited_t::signature[]; @@ -1308,14 +1300,6 @@ auto GeckoLayerClient::OnGeckoReady() const -> void return mozilla::jni::Method::Call(GeckoLayerClient::mCtx, nullptr); } -constexpr char GeckoLayerClient::ProgressiveUpdateCallback_t::name[]; -constexpr char GeckoLayerClient::ProgressiveUpdateCallback_t::signature[]; - -auto GeckoLayerClient::ProgressiveUpdateCallback(bool a0, float a1, float a2, float a3, float a4, float a5, bool a6) const -> mozilla::jni::Object::LocalRef -{ - return mozilla::jni::Method::Call(GeckoLayerClient::mCtx, nullptr, a0, a1, a2, a3, a4, a5, a6); -} - constexpr char GeckoLayerClient::SetFirstPaintViewport_t::name[]; constexpr char GeckoLayerClient::SetFirstPaintViewport_t::signature[]; @@ -1506,9 +1490,6 @@ constexpr char NativePanZoomController::HandleMouseEvent_t::signature[]; constexpr char NativePanZoomController::HandleScrollEvent_t::name[]; constexpr char NativePanZoomController::HandleScrollEvent_t::signature[]; -constexpr char NativePanZoomController::AbortAnimation_t::name[]; -constexpr char NativePanZoomController::AbortAnimation_t::signature[]; - constexpr char NativePanZoomController::SetIsLongpressEnabled_t::name[]; constexpr char NativePanZoomController::SetIsLongpressEnabled_t::signature[]; diff --git a/widget/android/GeneratedJNIWrappers.h b/widget/android/GeneratedJNIWrappers.h index e52b1ac85e16..202e325a35be 100644 --- a/widget/android/GeneratedJNIWrappers.h +++ b/widget/android/GeneratedJNIWrappers.h @@ -1571,26 +1571,6 @@ public: mozilla::jni::DispatchTarget::GECKO; }; - struct NotifyDefaultPrevented_t { - typedef GeckoAppShell Owner; - typedef void ReturnType; - typedef void SetterType; - typedef mozilla::jni::Args< - bool> Args; - static constexpr char name[] = "notifyDefaultPrevented"; - static constexpr char signature[] = - "(Z)V"; - static const bool isStatic = true; - static const mozilla::jni::ExceptionMode exceptionMode = - mozilla::jni::ExceptionMode::ABORT; - static const mozilla::jni::CallingThread callingThread = - mozilla::jni::CallingThread::GECKO; - static const mozilla::jni::DispatchTarget dispatchTarget = - mozilla::jni::DispatchTarget::CURRENT; - }; - - static auto NotifyDefaultPrevented(bool) -> void; - struct NotifyUriVisited_t { typedef GeckoAppShell Owner; typedef void ReturnType; @@ -4258,32 +4238,6 @@ public: auto OnGeckoReady() const -> void; - struct ProgressiveUpdateCallback_t { - typedef GeckoLayerClient Owner; - typedef mozilla::jni::Object::LocalRef ReturnType; - typedef mozilla::jni::Object::Param SetterType; - typedef mozilla::jni::Args< - bool, - float, - float, - float, - float, - float, - bool> Args; - static constexpr char name[] = "progressiveUpdateCallback"; - static constexpr char signature[] = - "(ZFFFFFZ)Lorg/mozilla/gecko/gfx/ProgressiveUpdateData;"; - static const bool isStatic = false; - static const mozilla::jni::ExceptionMode exceptionMode = - mozilla::jni::ExceptionMode::ABORT; - static const mozilla::jni::CallingThread callingThread = - mozilla::jni::CallingThread::ANY; - static const mozilla::jni::DispatchTarget dispatchTarget = - mozilla::jni::DispatchTarget::CURRENT; - }; - - auto ProgressiveUpdateCallback(bool, float, float, float, float, float, bool) const -> mozilla::jni::Object::LocalRef; - struct SetFirstPaintViewport_t { typedef GeckoLayerClient Owner; typedef void ReturnType; @@ -4980,23 +4934,6 @@ public: mozilla::jni::DispatchTarget::CURRENT; }; - struct AbortAnimation_t { - typedef NativePanZoomController Owner; - typedef void ReturnType; - typedef void SetterType; - typedef mozilla::jni::Args<> Args; - static constexpr char name[] = "nativeAbortAnimation"; - static constexpr char signature[] = - "()V"; - static const bool isStatic = false; - static const mozilla::jni::ExceptionMode exceptionMode = - mozilla::jni::ExceptionMode::ABORT; - static const mozilla::jni::CallingThread callingThread = - mozilla::jni::CallingThread::UI; - static const mozilla::jni::DispatchTarget dispatchTarget = - mozilla::jni::DispatchTarget::CURRENT; - }; - struct SetIsLongpressEnabled_t { typedef NativePanZoomController Owner; typedef void ReturnType; diff --git a/widget/android/nsWindow.cpp b/widget/android/nsWindow.cpp index c603941a6aea..e7f6b6328a60 100644 --- a/widget/android/nsWindow.cpp +++ b/widget/android/nsWindow.cpp @@ -537,25 +537,6 @@ public: } public: - void AbortAnimation() - { - MOZ_ASSERT(AndroidBridge::IsJavaUiThread()); - - RefPtr controller; - RefPtr compositor; - - if (LockedWindowPtr window{mWindow}) { - controller = window->mAPZC; - compositor = window->GetCompositorBridgeParent(); - } - - if (controller && compositor) { - // TODO: Pass in correct values for presShellId and viewId. - controller->CancelAnimation(ScrollableLayerGuid( - compositor->RootLayerTreeId(), 0, 0)); - } - } - void AdjustScrollForSurfaceShift(float aX, float aY) { MOZ_ASSERT(AndroidBridge::IsJavaUiThread()); From d755533d9f07a34b49073ec53c90a0b791e0cfae Mon Sep 17 00:00:00 2001 From: Randall Barker Date: Wed, 24 Aug 2016 14:50:01 -0700 Subject: [PATCH 003/105] Bug 1297850 - part 2, Background is no longer cleared by Java. Remove unused setBackgroundColor. r=jchen --- .../base/java/org/mozilla/gecko/GeckoApp.java | 8 ---- .../java/org/mozilla/gecko/PrivateTab.java | 5 --- .../base/java/org/mozilla/gecko/Tab.java | 41 ------------------- .../base/java/org/mozilla/gecko/Tabs.java | 13 ------ .../mozilla/gecko/gfx/GeckoLayerClient.java | 4 -- .../java/org/mozilla/gecko/gfx/LayerView.java | 12 ------ 6 files changed, 83 deletions(-) diff --git a/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java b/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java index 7f037d8d735c..19688e72360e 100644 --- a/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java +++ b/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java @@ -367,14 +367,6 @@ public abstract class GeckoApp mFormAssistPopup.hide(); break; - case LOADED: - // Sync up the layer view and the tab if the tab is - // currently displayed. - LayerView layerView = mLayerView; - if (layerView != null && Tabs.getInstance().isSelectedTab(tab)) - layerView.setBackgroundColor(tab.getBackgroundColor()); - break; - case DESKTOP_MODE_CHANGE: if (Tabs.getInstance().isSelectedTab(tab)) invalidateOptionsMenu(); diff --git a/mobile/android/base/java/org/mozilla/gecko/PrivateTab.java b/mobile/android/base/java/org/mozilla/gecko/PrivateTab.java index cca46f17f0b2..f3a9bcb25cb0 100644 --- a/mobile/android/base/java/org/mozilla/gecko/PrivateTab.java +++ b/mobile/android/base/java/org/mozilla/gecko/PrivateTab.java @@ -13,11 +13,6 @@ import org.mozilla.gecko.db.BrowserDB; public class PrivateTab extends Tab { public PrivateTab(Context context, int id, String url, boolean external, int parentId, String title) { super(context, id, url, external, parentId, title); - - // Init background to private_toolbar_grey to ensure flicker-free - // private tab creation. Page loads will reset it to white as expected. - final int bgColor = ContextCompat.getColor(context, R.color.tabs_tray_grey_pressed); - setBackgroundColor(bgColor); } @Override diff --git a/mobile/android/base/java/org/mozilla/gecko/Tab.java b/mobile/android/base/java/org/mozilla/gecko/Tab.java index e033915f9f7d..425f7083b83a 100644 --- a/mobile/android/base/java/org/mozilla/gecko/Tab.java +++ b/mobile/android/base/java/org/mozilla/gecko/Tab.java @@ -74,7 +74,6 @@ public class Tab { private ZoomConstraints mZoomConstraints; private boolean mIsRTL; private final ArrayList mPluginViews; - private int mBackgroundColor; private int mState; private Bitmap mThumbnailBitmap; private boolean mDesktopMode; @@ -116,8 +115,6 @@ public class Tab { public static final int LOAD_PROGRESS_LOADED = 80; public static final int LOAD_PROGRESS_STOP = 100; - private static final int DEFAULT_BACKGROUND_COLOR = Color.WHITE; - public enum ErrorType { CERT_ERROR, // Pages with certificate problems BLOCKED, // Pages blocked for phishing or malware warnings @@ -143,11 +140,6 @@ public class Tab { mState = shouldShowProgress(url) ? STATE_LOADING : STATE_SUCCESS; mLoadProgress = LOAD_PROGRESS_INIT; - // At startup, the background is set to a color specified by LayerView - // when the LayerView is created. Shortly after, this background color - // will be used before the tab's content is shown. - mBackgroundColor = DEFAULT_BACKGROUND_COLOR; - updateBookmark(); } @@ -698,7 +690,6 @@ public class Tab { setSiteLogins(null); setZoomConstraints(new ZoomConstraints(true)); setHasTouchListeners(false); - setBackgroundColor(DEFAULT_BACKGROUND_COLOR); setErrorType(ErrorType.NONE); setLoadProgressIfLoading(LOAD_PROGRESS_LOCATION_CHANGE); @@ -803,38 +794,6 @@ public class Tab { return mPluginViews.toArray(new View[mPluginViews.size()]); } - public int getBackgroundColor() { - return mBackgroundColor; - } - - /** Sets a new color for the background. */ - public void setBackgroundColor(int color) { - mBackgroundColor = color; - } - - /** Parses and sets a new color for the background. */ - public void setBackgroundColor(String newColor) { - setBackgroundColor(parseColorFromGecko(newColor)); - } - - // Parses a color from an RGB triple of the form "rgb([0-9]+, [0-9]+, [0-9]+)". If the color - // cannot be parsed, returns white. - private static int parseColorFromGecko(String string) { - if (sColorPattern == null) { - sColorPattern = Pattern.compile("rgb\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)"); - } - - Matcher matcher = sColorPattern.matcher(string); - if (!matcher.matches()) { - return Color.WHITE; - } - - int r = Integer.parseInt(matcher.group(1)); - int g = Integer.parseInt(matcher.group(2)); - int b = Integer.parseInt(matcher.group(3)); - return Color.rgb(r, g, b); - } - public void setDesktopMode(boolean enabled) { mDesktopMode = enabled; } diff --git a/mobile/android/base/java/org/mozilla/gecko/Tabs.java b/mobile/android/base/java/org/mozilla/gecko/Tabs.java index e4b80342639a..2c7451048924 100644 --- a/mobile/android/base/java/org/mozilla/gecko/Tabs.java +++ b/mobile/android/base/java/org/mozilla/gecko/Tabs.java @@ -111,7 +111,6 @@ public class Tabs implements GeckoEventListener { "Content:StateChange", "Content:LoadError", "Content:PageShow", - "DOMContentLoaded", "DOMTitleChanged", "Link:Favicon", "Link:Feed", @@ -518,18 +517,6 @@ public class Tabs implements GeckoEventListener { tab.setLoadedFromCache(message.getBoolean("fromCache")); tab.updateUserRequested(message.getString("userRequested")); notifyListeners(tab, TabEvents.PAGE_SHOW); - } else if (event.equals("DOMContentLoaded")) { - tab.handleContentLoaded(); - String backgroundColor = message.getString("bgColor"); - if (backgroundColor != null) { - tab.setBackgroundColor(backgroundColor); - } else { - // Default to white if no color is given - tab.setBackgroundColor(Color.WHITE); - } - tab.setErrorType(message.optString("errorType")); - tab.setMetadata(message.optJSONObject("metadata")); - notifyListeners(tab, Tabs.TabEvents.LOADED); } else if (event.equals("DOMTitleChanged")) { tab.updateTitle(message.getString("title")); } else if (event.equals("Link:Favicon")) { diff --git a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/GeckoLayerClient.java b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/GeckoLayerClient.java index ac586b98f7d6..6786b7a683e7 100644 --- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/GeckoLayerClient.java +++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/GeckoLayerClient.java @@ -362,10 +362,6 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget setViewportMetrics(newMetrics); - if (tab != null) { - mView.setBackgroundColor(tab.getBackgroundColor()); - } - // Indicate that the document is about to be composited so the // LayerView background can be removed. if (mView.getPaintState() == LayerView.PAINT_START) { diff --git a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/LayerView.java b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/LayerView.java index 0c2290483d62..1852b93e5148 100644 --- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/LayerView.java +++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/LayerView.java @@ -55,7 +55,6 @@ public class LayerView extends ScrollView implements Tabs.OnTabsChangedListener private LayerRenderer mRenderer; /* Must be a PAINT_xxx constant */ private int mPaintState; - private int mBackgroundColor; private FullScreenState mFullScreenState; private SurfaceView mSurfaceView; @@ -171,7 +170,6 @@ public class LayerView extends ScrollView implements Tabs.OnTabsChangedListener super(context, attrs); mPaintState = PAINT_START; - mBackgroundColor = Color.WHITE; mFullScreenState = FullScreenState.NONE; if (Versions.feature14Plus) { @@ -385,16 +383,6 @@ public class LayerView extends ScrollView implements Tabs.OnTabsChangedListener return mLayerClient.getMatrixForLayerRectToViewRect(); } - int getBackgroundColor() { - return mBackgroundColor; - } - - @Override - public void setBackgroundColor(int newColor) { - mBackgroundColor = newColor; - requestRender(); - } - void setSurfaceBackgroundColor(int newColor) { if (mSurfaceView != null) { mSurfaceView.setBackgroundColor(newColor); From b4272bd4eda32c60458d4c7bf9170e32baac63e6 Mon Sep 17 00:00:00 2001 From: Mason Chang Date: Thu, 25 Aug 2016 08:53:07 -0700 Subject: [PATCH 004/105] Bug 1295214. Correct for negative vsync timestamps on windows. r=jrmuizel --- gfx/thebes/gfxWindowsPlatform.cpp | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/gfx/thebes/gfxWindowsPlatform.cpp b/gfx/thebes/gfxWindowsPlatform.cpp index f69b83d836fc..1d20b976246d 100755 --- a/gfx/thebes/gfxWindowsPlatform.cpp +++ b/gfx/thebes/gfxWindowsPlatform.cpp @@ -1816,16 +1816,22 @@ public: // In these error cases, normalize to Now(); if (vsync >= now) { vsync = vsync - mVsyncRate; - return vsync <= now ? vsync : now; } } // On Windows 7 and 8, DwmFlush wakes up AFTER qpcVBlankTime // from DWMGetCompositionTimingInfo. We can return the adjusted vsync. - // If we got here on Windows 10, it means we got a weird timestamp. if (vsync >= now) { vsync = now; } + + // Our vsync time is some time very far in the past, adjust to Now. + // 4 ms is arbitrary, so feel free to pick something else if this isn't + // working. See the comment above within IsWin10OrLater(). + if ((now - vsync).ToMilliseconds() > 4.0) { + vsync = now; + } + return vsync; } @@ -1891,6 +1897,12 @@ public: vsync = TimeStamp::Now(); } + if ((now - vsync).ToMilliseconds() > 2.0) { + // Account for time drift here where vsync never quite catches up to + // Now and we'd fall ever so slightly further behind Now(). + vsync = GetVBlankTime(); + } + mPrevVsync = vsync; } } // end for From 82b3f6d3c5022d68ef14d07144561f1e6be4ee9c Mon Sep 17 00:00:00 2001 From: Nathan Froyd Date: Thu, 25 Aug 2016 20:33:01 -0400 Subject: [PATCH 005/105] Bug 1297486 - mark xpc::NonVoidStringToJsval as an ordinary inline function instead of MOZ_ALWAYS_INLINE; r=bz This change has a negligible impact on benchmarks, and saves a lot of space (550K+ on x86-64 Linux). --- js/xpconnect/src/xpcpublic.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/xpconnect/src/xpcpublic.h b/js/xpconnect/src/xpcpublic.h index 28422695d179..33d28f1667f4 100644 --- a/js/xpconnect/src/xpcpublic.h +++ b/js/xpconnect/src/xpcpublic.h @@ -341,7 +341,7 @@ StringToJsval(JSContext* cx, const nsAString& str, JS::MutableHandleValue rval) /** * As above, but for mozilla::dom::DOMString. */ -MOZ_ALWAYS_INLINE +inline bool NonVoidStringToJsval(JSContext* cx, mozilla::dom::DOMString& str, JS::MutableHandleValue rval) { From 129f2f75a056448cf8fd4169956672975fedd7a2 Mon Sep 17 00:00:00 2001 From: kearwood Date: Fri, 22 Jul 2016 12:41:00 -0700 Subject: [PATCH 006/105] Bug 1186578 - [webvr] Implement OpenVR/SteamVR support,r=gw280 MozReview-Commit-ID: LmpcMJubrYR --HG-- extra : rebase_source : c5d767c635bed9fa74ca94b2ce75952f20106702 --- dom/vr/VRDisplay.cpp | 22 +- dom/vr/VRDisplay.h | 1 + gfx/thebes/gfxPrefs.h | 1 + gfx/vr/VRDisplayPresentation.h | 2 - gfx/vr/VRManager.cpp | 33 +- gfx/vr/gfxVR.h | 34 +- gfx/vr/gfxVROculus.cpp | 10 +- gfx/vr/gfxVROpenVR.cpp | 442 +++++ gfx/vr/gfxVROpenVR.h | 93 + gfx/vr/ipc/VRMessageUtils.h | 6 +- gfx/vr/moz.build | 2 + gfx/vr/openvr/LICENSE | 27 + gfx/vr/openvr/README | 2 + gfx/vr/openvr/openvr.h | 3352 ++++++++++++++++++++++++++++++++ modules/libpref/init/all.js | 4 + 15 files changed, 4013 insertions(+), 18 deletions(-) create mode 100644 gfx/vr/gfxVROpenVR.cpp create mode 100644 gfx/vr/gfxVROpenVR.h create mode 100644 gfx/vr/openvr/LICENSE create mode 100644 gfx/vr/openvr/README create mode 100644 gfx/vr/openvr/openvr.h diff --git a/dom/vr/VRDisplay.cpp b/dom/vr/VRDisplay.cpp index e580007cfd5e..0e947ab52361 100644 --- a/dom/vr/VRDisplay.cpp +++ b/dom/vr/VRDisplay.cpp @@ -352,7 +352,7 @@ VRPose::GetLinearAcceleration(JSContext* aCx, JS::MutableHandle aRetval, ErrorResult& aRv) { - if (!mLinearAcceleration && mVRState.flags & gfx::VRDisplayCapabilityFlags::Cap_Position) { + if (!mLinearAcceleration && mVRState.flags & gfx::VRDisplayCapabilityFlags::Cap_LinearAcceleration) { // Lazily create the Float32Array mLinearAcceleration = dom::Float32Array::Create(aCx, this, 3, mVRState.linearAcceleration); if (!mLinearAcceleration) { @@ -409,7 +409,7 @@ VRPose::GetAngularAcceleration(JSContext* aCx, JS::MutableHandle aRetval, ErrorResult& aRv) { - if (!mAngularAcceleration && mVRState.flags & gfx::VRDisplayCapabilityFlags::Cap_Orientation) { + if (!mAngularAcceleration && mVRState.flags & gfx::VRDisplayCapabilityFlags::Cap_AngularAcceleration) { // Lazily create the Float32Array mAngularAcceleration = dom::Float32Array::Create(aCx, this, 3, mVRState.angularAcceleration); if (!mAngularAcceleration) { @@ -441,9 +441,15 @@ VRDisplay::VRDisplay(nsPIDOMWindowInner* aWindow, gfx::VRDisplayClient* aClient) , mDepthNear(0.01f) // Default value from WebVR Spec , mDepthFar(10000.0f) // Default value from WebVR Spec { - mDisplayId = aClient->GetDisplayInfo().GetDisplayID(); - mDisplayName = NS_ConvertASCIItoUTF16(aClient->GetDisplayInfo().GetDisplayName()); - mCapabilities = new VRDisplayCapabilities(aWindow, aClient->GetDisplayInfo().GetCapabilities()); + const gfx::VRDisplayInfo& info = aClient->GetDisplayInfo(); + mDisplayId = info.GetDisplayID(); + mDisplayName = NS_ConvertASCIItoUTF16(info.GetDisplayName()); + mCapabilities = new VRDisplayCapabilities(aWindow, info.GetCapabilities()); + if (info.GetCapabilities() & gfx::VRDisplayCapabilityFlags::Cap_StageParameters) { + mStageParameters = new VRStageParameters(aWindow, + info.GetSittingToStandingTransform(), + info.GetStageSize()); + } mozilla::HoldJSObjects(this); } @@ -482,9 +488,7 @@ VRDisplay::Capabilities() VRStageParameters* VRDisplay::GetStageParameters() { - // XXX When we implement room scale experiences for OpenVR, we should return - // something here. - return nullptr; + return mStageParameters; } already_AddRefed @@ -645,7 +649,7 @@ VRDisplay::IsConnected() const return mClient->GetIsConnected(); } -NS_IMPL_CYCLE_COLLECTION_INHERITED(VRDisplay, DOMEventTargetHelper, mCapabilities) +NS_IMPL_CYCLE_COLLECTION_INHERITED(VRDisplay, DOMEventTargetHelper, mCapabilities, mStageParameters) NS_IMPL_ADDREF_INHERITED(VRDisplay, DOMEventTargetHelper) NS_IMPL_RELEASE_INHERITED(VRDisplay, DOMEventTargetHelper) diff --git a/dom/vr/VRDisplay.h b/dom/vr/VRDisplay.h index 4fdf1694f484..52f72a90df22 100644 --- a/dom/vr/VRDisplay.h +++ b/dom/vr/VRDisplay.h @@ -283,6 +283,7 @@ protected: nsString mDisplayName; RefPtr mCapabilities; + RefPtr mStageParameters; double mDepthNear; double mDepthFar; diff --git a/gfx/thebes/gfxPrefs.h b/gfx/thebes/gfxPrefs.h index b38e408a68ba..c6d7ce94e8f5 100644 --- a/gfx/thebes/gfxPrefs.h +++ b/gfx/thebes/gfxPrefs.h @@ -309,6 +309,7 @@ private: DECL_GFX_PREF(Live, "dom.meta-viewport.enabled", MetaViewportEnabled, bool, false); DECL_GFX_PREF(Once, "dom.vr.enabled", VREnabled, bool, false); DECL_GFX_PREF(Once, "dom.vr.oculus.enabled", VROculusEnabled, bool, true); + DECL_GFX_PREF(Once, "dom.vr.openvr.enabled", VROpenVREnabled, bool, false); DECL_GFX_PREF(Once, "dom.vr.osvr.enabled", VROSVREnabled, bool, false); DECL_GFX_PREF(Live, "dom.vr.poseprediction.enabled", VRPosePredictionEnabled, bool, false); DECL_GFX_PREF(Live, "dom.w3c_pointer_events.enabled", PointerEventsEnabled, bool, false); diff --git a/gfx/vr/VRDisplayPresentation.h b/gfx/vr/VRDisplayPresentation.h index 5deeda262728..39efb59433ba 100644 --- a/gfx/vr/VRDisplayPresentation.h +++ b/gfx/vr/VRDisplayPresentation.h @@ -12,9 +12,7 @@ namespace mozilla { namespace gfx { class VRDisplayClient; -namespace vr { class VRLayerChild; -} // namepsace vr class VRDisplayPresentation final { diff --git a/gfx/vr/VRManager.cpp b/gfx/vr/VRManager.cpp index c77c166ff44a..f7e8bb521acf 100644 --- a/gfx/vr/VRManager.cpp +++ b/gfx/vr/VRManager.cpp @@ -7,6 +7,7 @@ #include "VRManager.h" #include "VRManagerParent.h" #include "gfxVR.h" +#include "gfxVROpenVR.h" #include "mozilla/ClearOnShutdown.h" #include "mozilla/dom/VRDisplay.h" #include "mozilla/layers/TextureHost.h" @@ -51,6 +52,20 @@ VRManager::VRManager() RefPtr mgr; + /** + * We must add the VRDisplayManager's to mManagers in a careful order to + * ensure that we don't detect the same VRDisplay from multiple API's. + * + * Oculus comes first, as it will only enumerate Oculus HMD's and is the + * native interface for Oculus HMD's. + * + * OpenvR comes second, as it is the native interface for HTC Vive + * which is the most common HMD at this time. + * + * OSVR will be used if Oculus SDK and OpenVR don't detect any HMDS, + * to support everyone else. + */ + #if defined(XP_WIN) // The Oculus runtime is supported only on Windows mgr = VRDisplayManagerOculus::Create(); @@ -60,9 +75,15 @@ VRManager::VRManager() #endif #if defined(XP_WIN) || defined(XP_MACOSX) || defined(XP_LINUX) + // OpenVR is cross platform compatible + mgr = VRDisplayManagerOpenVR::Create(); + if (mgr) { + mManagers.AppendElement(mgr); + } + // OSVR is cross platform compatible mgr = VRDisplayManagerOSVR::Create(); - if (mgr){ + if (mgr) { mManagers.AppendElement(mgr); } #endif @@ -172,7 +193,15 @@ VRManager::RefreshVRDisplays(bool aMustDispatch) { nsTArray > displays; - for (uint32_t i = 0; i < mManagers.Length(); ++i) { + /** We don't wish to enumerate the same display from multiple managers, + * so stop as soon as we get a display. + * It is still possible to get multiple displays from a single manager, + * but do not wish to mix-and-match for risk of reporting a duplicate. + * + * XXX - Perhaps there will be a better way to detect duplicate displays + * in the future. + */ + for (uint32_t i = 0; i < mManagers.Length() && displays.Length() == 0; ++i) { mManagers[i]->GetHMDs(displays); } diff --git a/gfx/vr/gfxVR.h b/gfx/vr/gfxVR.h index ff57e02412f9..855fde3d27b9 100644 --- a/gfx/vr/gfxVR.h +++ b/gfx/vr/gfxVR.h @@ -26,6 +26,7 @@ class VRDisplayHost; enum class VRDisplayType : uint16_t { Oculus, + OpenVR, OSVR, NumVRDisplayTypes }; @@ -56,10 +57,25 @@ enum class VRDisplayCapabilityFlags : uint16_t { * or update non-VR UI because that content will not be visible. */ Cap_External = 1 << 4, + /** + * Cap_AngularAcceleration is set if the VRDisplay is capable of tracking its + * angular acceleration. + */ + Cap_AngularAcceleration = 1 << 5, + /** + * Cap_LinearAcceleration is set if the VRDisplay is capable of tracking its + * linear acceleration. + */ + Cap_LinearAcceleration = 1 << 6, + /** + * Cap_StageParameters is set if the VRDisplay is capable of room scale VR + * and can report the StageParameters to describe the space. + */ + Cap_StageParameters = 1 << 7, /** * Cap_All used for validity checking during IPC serialization */ - Cap_All = (1 << 5) - 1 + Cap_All = (1 << 8) - 1 }; MOZ_MAKE_ENUM_CLASS_BITWISE_OPERATORS(VRDisplayCapabilityFlags) @@ -70,6 +86,14 @@ struct VRFieldOfView { : upDegrees(up), rightDegrees(right), downDegrees(down), leftDegrees(left) {} + void SetFromTanRadians(double up, double right, double down, double left) + { + upDegrees = atan(up) * 180.0 / M_PI; + rightDegrees = atan(right) * 180.0 / M_PI; + downDegrees = atan(down) * 180.0 / M_PI; + leftDegrees = atan(left) * 180.0 / M_PI; + } + bool operator==(const VRFieldOfView& other) const { return other.upDegrees == upDegrees && other.downDegrees == downDegrees && @@ -108,6 +132,8 @@ struct VRDisplayInfo const VRFieldOfView& GetEyeFOV(uint32_t whichEye) const { return mEyeFOV[whichEye]; } bool GetIsConnected() const { return mIsConnected; } bool GetIsPresenting() const { return mIsPresenting; } + const Size& GetStageSize() const { return mStageSize; } + const Matrix4x4& GetSittingToStandingTransform() const { return mSittingToStandingTransform; } enum Eye { Eye_Left, @@ -124,6 +150,8 @@ struct VRDisplayInfo IntSize mEyeResolution; bool mIsConnected; bool mIsPresenting; + Size mStageSize; + Matrix4x4 mSittingToStandingTransform; bool operator==(const VRDisplayInfo& other) const { return mType == other.mType && @@ -136,7 +164,9 @@ struct VRDisplayInfo mEyeFOV[0] == other.mEyeFOV[0] && mEyeFOV[1] == other.mEyeFOV[1] && mEyeTranslation[0] == other.mEyeTranslation[0] && - mEyeTranslation[1] == other.mEyeTranslation[1]; + mEyeTranslation[1] == other.mEyeTranslation[1] && + mStageSize == other.mStageSize && + mSittingToStandingTransform == other.mSittingToStandingTransform; } bool operator!=(const VRDisplayInfo& other) const { diff --git a/gfx/vr/gfxVROculus.cpp b/gfx/vr/gfxVROculus.cpp index 5adf6f71cd63..72edad08eca3 100644 --- a/gfx/vr/gfxVROculus.cpp +++ b/gfx/vr/gfxVROculus.cpp @@ -24,8 +24,8 @@ #include "mozilla/gfx/Quaternion.h" #include -#include "../layers/d3d11/CompositorD3D11.h" -#include "mozilla/layers/TextureD3D11.h" +#include "CompositorD3D11.h" +#include "TextureD3D11.h" #include "gfxVROculus.h" @@ -337,9 +337,11 @@ VRDisplayOculus::VRDisplayOculus(ovrSession aSession) mDisplayInfo.mCapabilityFlags = VRDisplayCapabilityFlags::Cap_None; if (mDesc.AvailableTrackingCaps & ovrTrackingCap_Orientation) { mDisplayInfo.mCapabilityFlags |= VRDisplayCapabilityFlags::Cap_Orientation; + mDisplayInfo.mCapabilityFlags |= VRDisplayCapabilityFlags::Cap_AngularAcceleration; } if (mDesc.AvailableTrackingCaps & ovrTrackingCap_Position) { mDisplayInfo.mCapabilityFlags |= VRDisplayCapabilityFlags::Cap_Position; + mDisplayInfo.mCapabilityFlags |= VRDisplayCapabilityFlags::Cap_LinearAcceleration; } mDisplayInfo.mCapabilityFlags |= VRDisplayCapabilityFlags::Cap_External; mDisplayInfo.mCapabilityFlags |= VRDisplayCapabilityFlags::Cap_Present; @@ -441,6 +443,8 @@ VRDisplayOculus::GetSensorState(double timeOffset) result.angularVelocity[1] = pose.AngularVelocity.y; result.angularVelocity[2] = pose.AngularVelocity.z; + result.flags |= VRDisplayCapabilityFlags::Cap_AngularAcceleration; + result.angularAcceleration[0] = pose.AngularAcceleration.x; result.angularAcceleration[1] = pose.AngularAcceleration.y; result.angularAcceleration[2] = pose.AngularAcceleration.z; @@ -457,6 +461,8 @@ VRDisplayOculus::GetSensorState(double timeOffset) result.linearVelocity[1] = pose.LinearVelocity.y; result.linearVelocity[2] = pose.LinearVelocity.z; + result.flags |= VRDisplayCapabilityFlags::Cap_LinearAcceleration; + result.linearAcceleration[0] = pose.LinearAcceleration.x; result.linearAcceleration[1] = pose.LinearAcceleration.y; result.linearAcceleration[2] = pose.LinearAcceleration.z; diff --git a/gfx/vr/gfxVROpenVR.cpp b/gfx/vr/gfxVROpenVR.cpp new file mode 100644 index 000000000000..9c088cd907e7 --- /dev/null +++ b/gfx/vr/gfxVROpenVR.cpp @@ -0,0 +1,442 @@ +/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*- + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include + +#include "prlink.h" +#include "prmem.h" +#include "prenv.h" +#include "gfxPrefs.h" +#include "nsString.h" +#include "mozilla/Preferences.h" + +#include "mozilla/gfx/Quaternion.h" + +#ifdef XP_WIN +#include "CompositorD3D11.h" +#include "TextureD3D11.h" +#endif // XP_WIN + +#include "gfxVROpenVR.h" + +#include "nsServiceManagerUtils.h" +#include "nsIScreenManager.h" +#include "openvr/openvr.h" + +#ifndef M_PI +# define M_PI 3.14159265358979323846 +#endif + +using namespace mozilla; +using namespace mozilla::gfx; +using namespace mozilla::gfx::impl; +using namespace mozilla::layers; + +namespace { +extern "C" { +typedef uint32_t (VR_CALLTYPE * pfn_VR_InitInternal)(::vr::HmdError *peError, ::vr::EVRApplicationType eApplicationType); +typedef void (VR_CALLTYPE * pfn_VR_ShutdownInternal)(); +typedef bool (VR_CALLTYPE * pfn_VR_IsHmdPresent)(); +typedef bool (VR_CALLTYPE * pfn_VR_IsRuntimeInstalled)(); +typedef const char * (VR_CALLTYPE * pfn_VR_GetStringForHmdError)(::vr::HmdError error); +typedef void * (VR_CALLTYPE * pfn_VR_GetGenericInterface)(const char *pchInterfaceVersion, ::vr::HmdError *peError); +} // extern "C" +} // namespace + +static pfn_VR_InitInternal vr_InitInternal = nullptr; +static pfn_VR_ShutdownInternal vr_ShutdownInternal = nullptr; +static pfn_VR_IsHmdPresent vr_IsHmdPresent = nullptr; +static pfn_VR_IsRuntimeInstalled vr_IsRuntimeInstalled = nullptr; +static pfn_VR_GetStringForHmdError vr_GetStringForHmdError = nullptr; +static pfn_VR_GetGenericInterface vr_GetGenericInterface = nullptr; + +bool +LoadOpenVRRuntime() +{ + static PRLibrary *openvrLib = nullptr; + + nsAdoptingCString openvrPath = Preferences::GetCString("gfx.vr.openvr-runtime"); + if (!openvrPath) + return false; + + openvrLib = PR_LoadLibrary(openvrPath.BeginReading()); + if (!openvrLib) + return false; + +#define REQUIRE_FUNCTION(_x) do { \ + *(void **)&vr_##_x = (void *) PR_FindSymbol(openvrLib, "VR_" #_x); \ + if (!vr_##_x) { printf_stderr("VR_" #_x " symbol missing\n"); return false; } \ + } while (0) + + REQUIRE_FUNCTION(InitInternal); + REQUIRE_FUNCTION(ShutdownInternal); + REQUIRE_FUNCTION(IsHmdPresent); + REQUIRE_FUNCTION(IsRuntimeInstalled); + REQUIRE_FUNCTION(GetStringForHmdError); + REQUIRE_FUNCTION(GetGenericInterface); + +#undef REQUIRE_FUNCTION + + return true; +} + +VRDisplayOpenVR::VRDisplayOpenVR(::vr::IVRSystem *aVRSystem, + ::vr::IVRChaperone *aVRChaperone, + ::vr::IVRCompositor *aVRCompositor) + : VRDisplayHost(VRDisplayType::OpenVR) + , mVRSystem(aVRSystem) + , mVRChaperone(aVRChaperone) + , mVRCompositor(aVRCompositor) + , mIsPresenting(false) +{ + MOZ_COUNT_CTOR_INHERITED(VRDisplayOpenVR, VRDisplayHost); + + mDisplayInfo.mDisplayName.AssignLiteral("OpenVR HMD"); + mDisplayInfo.mIsConnected = true; + mDisplayInfo.mCapabilityFlags = VRDisplayCapabilityFlags::Cap_None | + VRDisplayCapabilityFlags::Cap_Orientation | + VRDisplayCapabilityFlags::Cap_Position | + VRDisplayCapabilityFlags::Cap_External | + VRDisplayCapabilityFlags::Cap_Present | + VRDisplayCapabilityFlags::Cap_StageParameters; + + mVRCompositor->SetTrackingSpace(::vr::TrackingUniverseSeated); + + uint32_t w, h; + mVRSystem->GetRecommendedRenderTargetSize(&w, &h); + mDisplayInfo.mEyeResolution.width = w; + mDisplayInfo.mEyeResolution.height = h; + + // SteamVR gives the application a single FOV to use; it's not configurable as with Oculus + for (uint32_t eye = 0; eye < 2; ++eye) { + // get l/r/t/b clip plane coordinates + float l, r, t, b; + mVRSystem->GetProjectionRaw(static_cast<::vr::Hmd_Eye>(eye), &l, &r, &t, &b); + mDisplayInfo.mEyeFOV[eye].SetFromTanRadians(-t, r, b, -l); + + ::vr::HmdMatrix34_t eyeToHead = mVRSystem->GetEyeToHeadTransform(static_cast<::vr::Hmd_Eye>(eye)); + + mDisplayInfo.mEyeTranslation[eye].x = eyeToHead.m[0][3]; + mDisplayInfo.mEyeTranslation[eye].y = eyeToHead.m[1][3]; + mDisplayInfo.mEyeTranslation[eye].z = eyeToHead.m[2][3]; + } + + UpdateStageParameters(); +} + +VRDisplayOpenVR::~VRDisplayOpenVR() +{ + Destroy(); + MOZ_COUNT_DTOR_INHERITED(VRDisplayOpenVR, VRDisplayHost); +} + +void +VRDisplayOpenVR::Destroy() +{ + StopPresentation(); + vr_ShutdownInternal(); +} + +void +VRDisplayOpenVR::UpdateStageParameters() +{ + float sizeX = 0.0f; + float sizeZ = 0.0f; + if (mVRChaperone->GetPlayAreaSize(&sizeX, &sizeZ)) { + ::vr::HmdMatrix34_t t = mVRSystem->GetSeatedZeroPoseToStandingAbsoluteTrackingPose(); + mDisplayInfo.mStageSize.width = sizeX; + mDisplayInfo.mStageSize.height = sizeZ; + + mDisplayInfo.mSittingToStandingTransform._11 = t.m[0][0]; + mDisplayInfo.mSittingToStandingTransform._12 = t.m[1][0]; + mDisplayInfo.mSittingToStandingTransform._13 = t.m[2][0]; + mDisplayInfo.mSittingToStandingTransform._14 = 0.0f; + + mDisplayInfo.mSittingToStandingTransform._21 = t.m[0][1]; + mDisplayInfo.mSittingToStandingTransform._22 = t.m[1][1]; + mDisplayInfo.mSittingToStandingTransform._23 = t.m[2][1]; + mDisplayInfo.mSittingToStandingTransform._24 = 0.0f; + + mDisplayInfo.mSittingToStandingTransform._31 = t.m[0][2]; + mDisplayInfo.mSittingToStandingTransform._32 = t.m[1][2]; + mDisplayInfo.mSittingToStandingTransform._33 = t.m[2][2]; + mDisplayInfo.mSittingToStandingTransform._34 = 0.0f; + + mDisplayInfo.mSittingToStandingTransform._41 = t.m[0][3]; + mDisplayInfo.mSittingToStandingTransform._42 = t.m[1][3]; + mDisplayInfo.mSittingToStandingTransform._43 = t.m[2][3]; + mDisplayInfo.mSittingToStandingTransform._44 = 1.0f; + } else { + // If we fail, fall back to reasonable defaults. + // 1m x 1m space, 0.75m high in seated position + + mDisplayInfo.mStageSize.width = 1.0f; + mDisplayInfo.mStageSize.height = 1.0f; + + mDisplayInfo.mSittingToStandingTransform._11 = 1.0f; + mDisplayInfo.mSittingToStandingTransform._12 = 0.0f; + mDisplayInfo.mSittingToStandingTransform._13 = 0.0f; + mDisplayInfo.mSittingToStandingTransform._14 = 0.0f; + + mDisplayInfo.mSittingToStandingTransform._21 = 0.0f; + mDisplayInfo.mSittingToStandingTransform._22 = 1.0f; + mDisplayInfo.mSittingToStandingTransform._23 = 0.0f; + mDisplayInfo.mSittingToStandingTransform._24 = 0.0f; + + mDisplayInfo.mSittingToStandingTransform._31 = 0.0f; + mDisplayInfo.mSittingToStandingTransform._32 = 0.0f; + mDisplayInfo.mSittingToStandingTransform._33 = 1.0f; + mDisplayInfo.mSittingToStandingTransform._34 = 0.0f; + + mDisplayInfo.mSittingToStandingTransform._41 = 0.0f; + mDisplayInfo.mSittingToStandingTransform._42 = 0.75f; + mDisplayInfo.mSittingToStandingTransform._43 = 0.0f; + mDisplayInfo.mSittingToStandingTransform._44 = 1.0f; + } +} + +void +VRDisplayOpenVR::ZeroSensor() +{ + mVRSystem->ResetSeatedZeroPose(); + UpdateStageParameters(); +} + +VRHMDSensorState +VRDisplayOpenVR::GetSensorState() +{ + return GetSensorState(0.0f); +} + +VRHMDSensorState +VRDisplayOpenVR::GetImmediateSensorState() +{ + return GetSensorState(0.0f); +} + +VRHMDSensorState +VRDisplayOpenVR::GetSensorState(double timeOffset) +{ + { + ::vr::VREvent_t event; + while (mVRSystem->PollNextEvent(&event, sizeof(event))) { + // ignore + } + } + + ::vr::TrackedDevicePose_t poses[::vr::k_unMaxTrackedDeviceCount]; + // Note: We *must* call WaitGetPoses in order for any rendering to happen at all + mVRCompositor->WaitGetPoses(poses, ::vr::k_unMaxTrackedDeviceCount, nullptr, 0); + + VRHMDSensorState result; + result.Clear(); + result.timestamp = PR_Now(); + + if (poses[::vr::k_unTrackedDeviceIndex_Hmd].bDeviceIsConnected && + poses[::vr::k_unTrackedDeviceIndex_Hmd].bPoseIsValid && + poses[::vr::k_unTrackedDeviceIndex_Hmd].eTrackingResult == ::vr::TrackingResult_Running_OK) + { + const ::vr::TrackedDevicePose_t& pose = poses[::vr::k_unTrackedDeviceIndex_Hmd]; + + gfx::Matrix4x4 m; + // NOTE! mDeviceToAbsoluteTracking is a 3x4 matrix, not 4x4. But + // because of its arrangement, we can copy the 12 elements in and + // then transpose them to the right place. We do this so we can + // pull out a Quaternion. + memcpy(&m._11, &pose.mDeviceToAbsoluteTracking, sizeof(float) * 12); + m.Transpose(); + + gfx::Quaternion rot; + rot.SetFromRotationMatrix(m); + rot.Invert(); + + result.flags |= VRDisplayCapabilityFlags::Cap_Orientation; + result.orientation[0] = rot.x; + result.orientation[1] = rot.y; + result.orientation[2] = rot.z; + result.orientation[3] = rot.w; + result.angularVelocity[0] = pose.vAngularVelocity.v[0]; + result.angularVelocity[1] = pose.vAngularVelocity.v[1]; + result.angularVelocity[2] = pose.vAngularVelocity.v[2]; + + result.flags |= VRDisplayCapabilityFlags::Cap_Position; + result.position[0] = m._41; + result.position[1] = m._42; + result.position[2] = m._43; + result.linearVelocity[0] = pose.vVelocity.v[0]; + result.linearVelocity[1] = pose.vVelocity.v[1]; + result.linearVelocity[2] = pose.vVelocity.v[2]; + } + + return result; +} + +void +VRDisplayOpenVR::StartPresentation() +{ + if (mIsPresenting) { + return; + } + mIsPresenting = true; +} + +void +VRDisplayOpenVR::StopPresentation() +{ + if (!mIsPresenting) { + return; + } + + mVRCompositor->ClearLastSubmittedFrame(); + + mIsPresenting = false; +} + + +#if defined(XP_WIN) + +void +VRDisplayOpenVR::SubmitFrame(TextureSourceD3D11* aSource, + const IntSize& aSize, + const VRHMDSensorState& aSensorState, + const gfx::Rect& aLeftEyeRect, + const gfx::Rect& aRightEyeRect) +{ + if (!mIsPresenting) { + return; + } + + ::vr::Texture_t tex; + tex.handle = (void *)aSource->GetD3D11Texture(); + tex.eType = ::vr::EGraphicsAPIConvention::API_DirectX; + tex.eColorSpace = ::vr::EColorSpace::ColorSpace_Auto; + + ::vr::VRTextureBounds_t bounds; + bounds.uMin = aLeftEyeRect.x; + bounds.vMin = 1.0 - aLeftEyeRect.y; + bounds.uMax = aLeftEyeRect.x + aLeftEyeRect.width; + bounds.vMax = 1.0 - aLeftEyeRect.y - aLeftEyeRect.height; + + ::vr::EVRCompositorError err; + err = mVRCompositor->Submit(::vr::EVREye::Eye_Left, &tex, &bounds); + if (err != ::vr::EVRCompositorError::VRCompositorError_None) { + printf_stderr("OpenVR Compositor Submit() failed.\n"); + } + + bounds.uMin = aRightEyeRect.x; + bounds.vMin = 1.0 - aRightEyeRect.y; + bounds.uMax = aRightEyeRect.x + aRightEyeRect.width; + bounds.vMax = 1.0 - aRightEyeRect.y - aRightEyeRect.height; + + err = mVRCompositor->Submit(::vr::EVREye::Eye_Right, &tex, &bounds); + if (err != ::vr::EVRCompositorError::VRCompositorError_None) { + printf_stderr("OpenVR Compositor Submit() failed.\n"); + } + + mVRCompositor->PostPresentHandoff(); + + // Trigger the next VSync immediately + VRManager *vm = VRManager::Get(); + MOZ_ASSERT(vm); + vm->NotifyVRVsync(mDisplayInfo.mDisplayID); +} + +#endif + +void +VRDisplayOpenVR::NotifyVSync() +{ + // We update mIsConneced once per frame. + mDisplayInfo.mIsConnected = vr_IsHmdPresent(); +} + +VRDisplayManagerOpenVR::VRDisplayManagerOpenVR() + : mOpenVRInstalled(false) +{ +} + +/*static*/ already_AddRefed +VRDisplayManagerOpenVR::Create() +{ + MOZ_ASSERT(NS_IsMainThread()); + + if (!gfxPrefs::VREnabled() || !gfxPrefs::VROpenVREnabled()) { + return nullptr; + } + + if (!LoadOpenVRRuntime()) { + return nullptr; + } + + RefPtr manager = new VRDisplayManagerOpenVR(); + return manager.forget(); +} + +bool +VRDisplayManagerOpenVR::Init() +{ + if (mOpenVRInstalled) + return true; + + if (!vr_IsRuntimeInstalled()) + return false; + + mOpenVRInstalled = true; + return true; +} + +void +VRDisplayManagerOpenVR::Destroy() +{ + if (mOpenVRInstalled) { + if (mOpenVRHMD) { + mOpenVRHMD = nullptr; + } + mOpenVRInstalled = false; + } +} + +void +VRDisplayManagerOpenVR::GetHMDs(nsTArray>& aHMDResult) +{ + if (!mOpenVRInstalled) { + return; + } + + if (!vr_IsHmdPresent()) { + if (mOpenVRHMD) { + mOpenVRHMD = nullptr; + } + } else if (mOpenVRHMD == nullptr) { + ::vr::HmdError err; + + vr_InitInternal(&err, ::vr::EVRApplicationType::VRApplication_Scene); + if (err) { + return; + } + + ::vr::IVRSystem *system = (::vr::IVRSystem *)vr_GetGenericInterface(::vr::IVRSystem_Version, &err); + if (err || !system) { + vr_ShutdownInternal(); + return; + } + ::vr::IVRChaperone *chaperone = (::vr::IVRChaperone *)vr_GetGenericInterface(::vr::IVRChaperone_Version, &err); + if (err || !chaperone) { + vr_ShutdownInternal(); + return; + } + ::vr::IVRCompositor *compositor = (::vr::IVRCompositor*)vr_GetGenericInterface(::vr::IVRCompositor_Version, &err); + if (err || !compositor) { + vr_ShutdownInternal(); + return; + } + + mOpenVRHMD = new VRDisplayOpenVR(system, chaperone, compositor); + } + + if (mOpenVRHMD) { + aHMDResult.AppendElement(mOpenVRHMD); + } +} diff --git a/gfx/vr/gfxVROpenVR.h b/gfx/vr/gfxVROpenVR.h new file mode 100644 index 000000000000..b84a20861fc0 --- /dev/null +++ b/gfx/vr/gfxVROpenVR.h @@ -0,0 +1,93 @@ +/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*- + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#ifndef GFX_VR_OPENVR_H +#define GFX_VR_OPENVR_H + +#include "nsTArray.h" +#include "nsIScreen.h" +#include "nsCOMPtr.h" +#include "mozilla/RefPtr.h" + +#include "mozilla/gfx/2D.h" +#include "mozilla/EnumeratedArray.h" + +#include "gfxVR.h" + +// OpenVR Interfaces +namespace vr { +class IVRChaperone; +class IVRCompositor; +class IVRSystem; +struct TrackedDevicePose_t; +} + +namespace mozilla { +namespace gfx { +namespace impl { + +class VRDisplayOpenVR : public VRDisplayHost +{ +public: + virtual void NotifyVSync() override; + virtual VRHMDSensorState GetSensorState() override; + virtual VRHMDSensorState GetImmediateSensorState() override; + void ZeroSensor() override; + +protected: + virtual void StartPresentation() override; + virtual void StopPresentation() override; +#if defined(XP_WIN) + virtual void SubmitFrame(mozilla::layers::TextureSourceD3D11* aSource, + const IntSize& aSize, + const VRHMDSensorState& aSensorState, + const gfx::Rect& aLeftEyeRect, + const gfx::Rect& aRightEyeRect) override; +#endif + +public: + explicit VRDisplayOpenVR(::vr::IVRSystem *aVRSystem, + ::vr::IVRChaperone *aVRChaperone, + ::vr::IVRCompositor *aVRCompositor); + +protected: + virtual ~VRDisplayOpenVR(); + void Destroy(); + + VRHMDSensorState GetSensorState(double timeOffset); + + // not owned by us; global from OpenVR + ::vr::IVRSystem *mVRSystem; + ::vr::IVRChaperone *mVRChaperone; + ::vr::IVRCompositor *mVRCompositor; + + bool mIsPresenting; + + void UpdateStageParameters(); +}; + +} // namespace impl + +class VRDisplayManagerOpenVR : public VRDisplayManager +{ +public: + static already_AddRefed Create(); + + virtual bool Init() override; + virtual void Destroy() override; + virtual void GetHMDs(nsTArray >& aHMDResult) override; +protected: + VRDisplayManagerOpenVR(); + + // there can only be one + RefPtr mOpenVRHMD; + bool mOpenVRInstalled; +}; + +} // namespace gfx +} // namespace mozilla + + +#endif /* GFX_VR_OPENVR_H */ diff --git a/gfx/vr/ipc/VRMessageUtils.h b/gfx/vr/ipc/VRMessageUtils.h index 07c05261b86f..e7fe9aff7814 100644 --- a/gfx/vr/ipc/VRMessageUtils.h +++ b/gfx/vr/ipc/VRMessageUtils.h @@ -40,6 +40,8 @@ struct ParamTraits WriteParam(aMsg, aParam.mEyeResolution); WriteParam(aMsg, aParam.mIsConnected); WriteParam(aMsg, aParam.mIsPresenting); + WriteParam(aMsg, aParam.mStageSize); + WriteParam(aMsg, aParam.mSittingToStandingTransform); for (int i = 0; i < mozilla::gfx::VRDisplayInfo::NumEyes; i++) { WriteParam(aMsg, aParam.mEyeFOV[i]); WriteParam(aMsg, aParam.mEyeTranslation[i]); @@ -54,7 +56,9 @@ struct ParamTraits !ReadParam(aMsg, aIter, &(aResult->mCapabilityFlags)) || !ReadParam(aMsg, aIter, &(aResult->mEyeResolution)) || !ReadParam(aMsg, aIter, &(aResult->mIsConnected)) || - !ReadParam(aMsg, aIter, &(aResult->mIsPresenting))) { + !ReadParam(aMsg, aIter, &(aResult->mIsPresenting)) || + !ReadParam(aMsg, aIter, &(aResult->mStageSize)) || + !ReadParam(aMsg, aIter, &(aResult->mSittingToStandingTransform))) { return false; } for (int i = 0; i < mozilla::gfx::VRDisplayInfo::NumEyes; i++) { diff --git a/gfx/vr/moz.build b/gfx/vr/moz.build index b5fdaa2af901..e67c8e738ccb 100644 --- a/gfx/vr/moz.build +++ b/gfx/vr/moz.build @@ -16,11 +16,13 @@ EXPORTS += [ ] LOCAL_INCLUDES += [ + '/gfx/layers/d3d11', '/gfx/thebes', ] UNIFIED_SOURCES += [ 'gfxVR.cpp', + 'gfxVROpenVR.cpp', 'gfxVROSVR.cpp', 'ipc/VRLayerChild.cpp', 'ipc/VRLayerParent.cpp', diff --git a/gfx/vr/openvr/LICENSE b/gfx/vr/openvr/LICENSE new file mode 100644 index 000000000000..ee83337d7fcb --- /dev/null +++ b/gfx/vr/openvr/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2015, Valve Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors +may be used to endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/gfx/vr/openvr/README b/gfx/vr/openvr/README new file mode 100644 index 000000000000..5e67e5a3a947 --- /dev/null +++ b/gfx/vr/openvr/README @@ -0,0 +1,2 @@ +See https://github.com/ValveSoftware/openvr/ + diff --git a/gfx/vr/openvr/openvr.h b/gfx/vr/openvr/openvr.h new file mode 100644 index 000000000000..deb3142fd4ec --- /dev/null +++ b/gfx/vr/openvr/openvr.h @@ -0,0 +1,3352 @@ +#pragma once + +// openvr.h +//========= Copyright Valve Corporation ============// +// Dynamically generated file. Do not modify this file directly. + +#ifndef _OPENVR_API +#define _OPENVR_API + +#include + + + +// vrtypes.h +#ifndef _INCLUDE_VRTYPES_H +#define _INCLUDE_VRTYPES_H + +namespace vr +{ + +#if defined(__linux__) || defined(__APPLE__) + // The 32-bit version of gcc has the alignment requirement for uint64 and double set to + // 4 meaning that even with #pragma pack(8) these types will only be four-byte aligned. + // The 64-bit version of gcc has the alignment requirement for these types set to + // 8 meaning that unless we use #pragma pack(4) our structures will get bigger. + // The 64-bit structure packing has to match the 32-bit structure packing for each platform. + #pragma pack( push, 4 ) +#else + #pragma pack( push, 8 ) +#endif + +typedef void* glSharedTextureHandle_t; +typedef int32_t glInt_t; +typedef uint32_t glUInt_t; + +// right-handed system +// +y is up +// +x is to the right +// -z is going away from you +// Distance unit is meters +struct HmdMatrix34_t +{ + float m[3][4]; +}; + +struct HmdMatrix44_t +{ + float m[4][4]; +}; + +struct HmdVector3_t +{ + float v[3]; +}; + +struct HmdVector4_t +{ + float v[4]; +}; + +struct HmdVector3d_t +{ + double v[3]; +}; + +struct HmdVector2_t +{ + float v[2]; +}; + +struct HmdQuaternion_t +{ + double w, x, y, z; +}; + +struct HmdColor_t +{ + float r, g, b, a; +}; + +struct HmdQuad_t +{ + HmdVector3_t vCorners[ 4 ]; +}; + +struct HmdRect2_t +{ + HmdVector2_t vTopLeft; + HmdVector2_t vBottomRight; +}; + +/** Used to return the post-distortion UVs for each color channel. +* UVs range from 0 to 1 with 0,0 in the upper left corner of the +* source render target. The 0,0 to 1,1 range covers a single eye. */ +struct DistortionCoordinates_t +{ + float rfRed[2]; + float rfGreen[2]; + float rfBlue[2]; +}; + +enum EVREye +{ + Eye_Left = 0, + Eye_Right = 1 +}; + +enum EGraphicsAPIConvention +{ + API_DirectX = 0, // Normalized Z goes from 0 at the viewer to 1 at the far clip plane + API_OpenGL = 1, // Normalized Z goes from 1 at the viewer to -1 at the far clip plane +}; + +enum EColorSpace +{ + ColorSpace_Auto = 0, // Assumes 'gamma' for 8-bit per component formats, otherwise 'linear'. This mirrors the DXGI formats which have _SRGB variants. + ColorSpace_Gamma = 1, // Texture data can be displayed directly on the display without any conversion (a.k.a. display native format). + ColorSpace_Linear = 2, // Same as gamma but has been converted to a linear representation using DXGI's sRGB conversion algorithm. +}; + +struct Texture_t +{ + void* handle; // Native d3d texture pointer or GL texture id. + EGraphicsAPIConvention eType; + EColorSpace eColorSpace; +}; + +enum ETrackingResult +{ + TrackingResult_Uninitialized = 1, + + TrackingResult_Calibrating_InProgress = 100, + TrackingResult_Calibrating_OutOfRange = 101, + + TrackingResult_Running_OK = 200, + TrackingResult_Running_OutOfRange = 201, +}; + +static const uint32_t k_unTrackingStringSize = 32; +static const uint32_t k_unMaxDriverDebugResponseSize = 32768; + +/** Used to pass device IDs to API calls */ +typedef uint32_t TrackedDeviceIndex_t; +static const uint32_t k_unTrackedDeviceIndex_Hmd = 0; +static const uint32_t k_unMaxTrackedDeviceCount = 16; +static const uint32_t k_unTrackedDeviceIndexOther = 0xFFFFFFFE; +static const uint32_t k_unTrackedDeviceIndexInvalid = 0xFFFFFFFF; + +/** Describes what kind of object is being tracked at a given ID */ +enum ETrackedDeviceClass +{ + TrackedDeviceClass_Invalid = 0, // the ID was not valid. + TrackedDeviceClass_HMD = 1, // Head-Mounted Displays + TrackedDeviceClass_Controller = 2, // Tracked controllers + TrackedDeviceClass_TrackingReference = 4, // Camera and base stations that serve as tracking reference points + + TrackedDeviceClass_Other = 1000, +}; + + +/** Describes what specific role associated with a tracked device */ +enum ETrackedControllerRole +{ + TrackedControllerRole_Invalid = 0, // Invalid value for controller type + TrackedControllerRole_LeftHand = 1, // Tracked device associated with the left hand + TrackedControllerRole_RightHand = 2, // Tracked device associated with the right hand +}; + + +/** describes a single pose for a tracked object */ +struct TrackedDevicePose_t +{ + HmdMatrix34_t mDeviceToAbsoluteTracking; + HmdVector3_t vVelocity; // velocity in tracker space in m/s + HmdVector3_t vAngularVelocity; // angular velocity in radians/s (?) + ETrackingResult eTrackingResult; + bool bPoseIsValid; + + // This indicates that there is a device connected for this spot in the pose array. + // It could go from true to false if the user unplugs the device. + bool bDeviceIsConnected; +}; + +/** Identifies which style of tracking origin the application wants to use +* for the poses it is requesting */ +enum ETrackingUniverseOrigin +{ + TrackingUniverseSeated = 0, // Poses are provided relative to the seated zero pose + TrackingUniverseStanding = 1, // Poses are provided relative to the safe bounds configured by the user + TrackingUniverseRawAndUncalibrated = 2, // Poses are provided in the coordinate system defined by the driver. You probably don't want this one. +}; + + +/** Each entry in this enum represents a property that can be retrieved about a +* tracked device. Many fields are only valid for one ETrackedDeviceClass. */ +enum ETrackedDeviceProperty +{ + // general properties that apply to all device classes + Prop_TrackingSystemName_String = 1000, + Prop_ModelNumber_String = 1001, + Prop_SerialNumber_String = 1002, + Prop_RenderModelName_String = 1003, + Prop_WillDriftInYaw_Bool = 1004, + Prop_ManufacturerName_String = 1005, + Prop_TrackingFirmwareVersion_String = 1006, + Prop_HardwareRevision_String = 1007, + Prop_AllWirelessDongleDescriptions_String = 1008, + Prop_ConnectedWirelessDongle_String = 1009, + Prop_DeviceIsWireless_Bool = 1010, + Prop_DeviceIsCharging_Bool = 1011, + Prop_DeviceBatteryPercentage_Float = 1012, // 0 is empty, 1 is full + Prop_StatusDisplayTransform_Matrix34 = 1013, + Prop_Firmware_UpdateAvailable_Bool = 1014, + Prop_Firmware_ManualUpdate_Bool = 1015, + Prop_Firmware_ManualUpdateURL_String = 1016, + Prop_HardwareRevision_Uint64 = 1017, + Prop_FirmwareVersion_Uint64 = 1018, + Prop_FPGAVersion_Uint64 = 1019, + Prop_VRCVersion_Uint64 = 1020, + Prop_RadioVersion_Uint64 = 1021, + Prop_DongleVersion_Uint64 = 1022, + Prop_BlockServerShutdown_Bool = 1023, + Prop_CanUnifyCoordinateSystemWithHmd_Bool = 1024, + Prop_ContainsProximitySensor_Bool = 1025, + Prop_DeviceProvidesBatteryStatus_Bool = 1026, + Prop_DeviceCanPowerOff_Bool = 1027, + Prop_Firmware_ProgrammingTarget_String = 1028, + Prop_DeviceClass_Int32 = 1029, + Prop_HasCamera_Bool = 1030, + Prop_DriverVersion_String = 1031, + Prop_Firmware_ForceUpdateRequired_Bool = 1032, + + // Properties that are unique to TrackedDeviceClass_HMD + Prop_ReportsTimeSinceVSync_Bool = 2000, + Prop_SecondsFromVsyncToPhotons_Float = 2001, + Prop_DisplayFrequency_Float = 2002, + Prop_UserIpdMeters_Float = 2003, + Prop_CurrentUniverseId_Uint64 = 2004, + Prop_PreviousUniverseId_Uint64 = 2005, + Prop_DisplayFirmwareVersion_Uint64 = 2006, + Prop_IsOnDesktop_Bool = 2007, + Prop_DisplayMCType_Int32 = 2008, + Prop_DisplayMCOffset_Float = 2009, + Prop_DisplayMCScale_Float = 2010, + Prop_EdidVendorID_Int32 = 2011, + Prop_DisplayMCImageLeft_String = 2012, + Prop_DisplayMCImageRight_String = 2013, + Prop_DisplayGCBlackClamp_Float = 2014, + Prop_EdidProductID_Int32 = 2015, + Prop_CameraToHeadTransform_Matrix34 = 2016, + Prop_DisplayGCType_Int32 = 2017, + Prop_DisplayGCOffset_Float = 2018, + Prop_DisplayGCScale_Float = 2019, + Prop_DisplayGCPrescale_Float = 2020, + Prop_DisplayGCImage_String = 2021, + Prop_LensCenterLeftU_Float = 2022, + Prop_LensCenterLeftV_Float = 2023, + Prop_LensCenterRightU_Float = 2024, + Prop_LensCenterRightV_Float = 2025, + Prop_UserHeadToEyeDepthMeters_Float = 2026, + Prop_CameraFirmwareVersion_Uint64 = 2027, + Prop_CameraFirmwareDescription_String = 2028, + Prop_DisplayFPGAVersion_Uint64 = 2029, + Prop_DisplayBootloaderVersion_Uint64 = 2030, + Prop_DisplayHardwareVersion_Uint64 = 2031, + Prop_AudioFirmwareVersion_Uint64 = 2032, + Prop_CameraCompatibilityMode_Int32 = 2033, + Prop_ScreenshotHorizontalFieldOfViewDegrees_Float = 2034, + Prop_ScreenshotVerticalFieldOfViewDegrees_Float = 2035, + Prop_DisplaySuppressed_Bool = 2036, + + // Properties that are unique to TrackedDeviceClass_Controller + Prop_AttachedDeviceId_String = 3000, + Prop_SupportedButtons_Uint64 = 3001, + Prop_Axis0Type_Int32 = 3002, // Return value is of type EVRControllerAxisType + Prop_Axis1Type_Int32 = 3003, // Return value is of type EVRControllerAxisType + Prop_Axis2Type_Int32 = 3004, // Return value is of type EVRControllerAxisType + Prop_Axis3Type_Int32 = 3005, // Return value is of type EVRControllerAxisType + Prop_Axis4Type_Int32 = 3006, // Return value is of type EVRControllerAxisType + Prop_ControllerRoleHint_Int32 = 3007, // Return value is of type ETrackedControllerRole + + // Properties that are unique to TrackedDeviceClass_TrackingReference + Prop_FieldOfViewLeftDegrees_Float = 4000, + Prop_FieldOfViewRightDegrees_Float = 4001, + Prop_FieldOfViewTopDegrees_Float = 4002, + Prop_FieldOfViewBottomDegrees_Float = 4003, + Prop_TrackingRangeMinimumMeters_Float = 4004, + Prop_TrackingRangeMaximumMeters_Float = 4005, + Prop_ModeLabel_String = 4006, + + // Vendors are free to expose private debug data in this reserved region + Prop_VendorSpecific_Reserved_Start = 10000, + Prop_VendorSpecific_Reserved_End = 10999, +}; + +/** No string property will ever be longer than this length */ +static const uint32_t k_unMaxPropertyStringSize = 32 * 1024; + +/** Used to return errors that occur when reading properties. */ +enum ETrackedPropertyError +{ + TrackedProp_Success = 0, + TrackedProp_WrongDataType = 1, + TrackedProp_WrongDeviceClass = 2, + TrackedProp_BufferTooSmall = 3, + TrackedProp_UnknownProperty = 4, + TrackedProp_InvalidDevice = 5, + TrackedProp_CouldNotContactServer = 6, + TrackedProp_ValueNotProvidedByDevice = 7, + TrackedProp_StringExceedsMaximumLength = 8, + TrackedProp_NotYetAvailable = 9, // The property value isn't known yet, but is expected soon. Call again later. +}; + +/** Allows the application to control what part of the provided texture will be used in the +* frame buffer. */ +struct VRTextureBounds_t +{ + float uMin, vMin; + float uMax, vMax; +}; + + +/** Allows the application to control how scene textures are used by the compositor when calling Submit. */ +enum EVRSubmitFlags +{ + // Simple render path. App submits rendered left and right eye images with no lens distortion correction applied. + Submit_Default = 0x00, + + // App submits final left and right eye images with lens distortion already applied (lens distortion makes the images appear + // barrel distorted with chromatic aberration correction applied). The app would have used the data returned by + // vr::IVRSystem::ComputeDistortion() to apply the correct distortion to the rendered images before calling Submit(). + Submit_LensDistortionAlreadyApplied = 0x01, + + // If the texture pointer passed in is actually a renderbuffer (e.g. for MSAA in OpenGL) then set this flag. + Submit_GlRenderBuffer = 0x02, +}; + + +/** Status of the overall system or tracked objects */ +enum EVRState +{ + VRState_Undefined = -1, + VRState_Off = 0, + VRState_Searching = 1, + VRState_Searching_Alert = 2, + VRState_Ready = 3, + VRState_Ready_Alert = 4, + VRState_NotReady = 5, + VRState_Standby = 6, + VRState_Ready_Alert_Low = 7, +}; + +/** The types of events that could be posted (and what the parameters mean for each event type) */ +enum EVREventType +{ + VREvent_None = 0, + + VREvent_TrackedDeviceActivated = 100, + VREvent_TrackedDeviceDeactivated = 101, + VREvent_TrackedDeviceUpdated = 102, + VREvent_TrackedDeviceUserInteractionStarted = 103, + VREvent_TrackedDeviceUserInteractionEnded = 104, + VREvent_IpdChanged = 105, + VREvent_EnterStandbyMode = 106, + VREvent_LeaveStandbyMode = 107, + VREvent_TrackedDeviceRoleChanged = 108, + VREvent_WatchdogWakeUpRequested = 109, + + VREvent_ButtonPress = 200, // data is controller + VREvent_ButtonUnpress = 201, // data is controller + VREvent_ButtonTouch = 202, // data is controller + VREvent_ButtonUntouch = 203, // data is controller + + VREvent_MouseMove = 300, // data is mouse + VREvent_MouseButtonDown = 301, // data is mouse + VREvent_MouseButtonUp = 302, // data is mouse + VREvent_FocusEnter = 303, // data is overlay + VREvent_FocusLeave = 304, // data is overlay + VREvent_Scroll = 305, // data is mouse + VREvent_TouchPadMove = 306, // data is mouse + VREvent_OverlayFocusChanged = 307, // data is overlay, global event + + VREvent_InputFocusCaptured = 400, // data is process DEPRECATED + VREvent_InputFocusReleased = 401, // data is process DEPRECATED + VREvent_SceneFocusLost = 402, // data is process + VREvent_SceneFocusGained = 403, // data is process + VREvent_SceneApplicationChanged = 404, // data is process - The App actually drawing the scene changed (usually to or from the compositor) + VREvent_SceneFocusChanged = 405, // data is process - New app got access to draw the scene + VREvent_InputFocusChanged = 406, // data is process + VREvent_SceneApplicationSecondaryRenderingStarted = 407, // data is process + + VREvent_HideRenderModels = 410, // Sent to the scene application to request hiding render models temporarily + VREvent_ShowRenderModels = 411, // Sent to the scene application to request restoring render model visibility + + VREvent_OverlayShown = 500, + VREvent_OverlayHidden = 501, + VREvent_DashboardActivated = 502, + VREvent_DashboardDeactivated = 503, + VREvent_DashboardThumbSelected = 504, // Sent to the overlay manager - data is overlay + VREvent_DashboardRequested = 505, // Sent to the overlay manager - data is overlay + VREvent_ResetDashboard = 506, // Send to the overlay manager + VREvent_RenderToast = 507, // Send to the dashboard to render a toast - data is the notification ID + VREvent_ImageLoaded = 508, // Sent to overlays when a SetOverlayRaw or SetOverlayFromFile call finishes loading + VREvent_ShowKeyboard = 509, // Sent to keyboard renderer in the dashboard to invoke it + VREvent_HideKeyboard = 510, // Sent to keyboard renderer in the dashboard to hide it + VREvent_OverlayGamepadFocusGained = 511, // Sent to an overlay when IVROverlay::SetFocusOverlay is called on it + VREvent_OverlayGamepadFocusLost = 512, // Send to an overlay when it previously had focus and IVROverlay::SetFocusOverlay is called on something else + VREvent_OverlaySharedTextureChanged = 513, + VREvent_DashboardGuideButtonDown = 514, + VREvent_DashboardGuideButtonUp = 515, + VREvent_ScreenshotTriggered = 516, // Screenshot button combo was pressed, Dashboard should request a screenshot + VREvent_ImageFailed = 517, // Sent to overlays when a SetOverlayRaw or SetOverlayfromFail fails to load + + // Screenshot API + VREvent_RequestScreenshot = 520, // Sent by vrclient application to compositor to take a screenshot + VREvent_ScreenshotTaken = 521, // Sent by compositor to the application that the screenshot has been taken + VREvent_ScreenshotFailed = 522, // Sent by compositor to the application that the screenshot failed to be taken + VREvent_SubmitScreenshotToDashboard = 523, // Sent by compositor to the dashboard that a completed screenshot was submitted + VREvent_ScreenshotProgressToDashboard = 524, // Sent by compositor to the dashboard that a completed screenshot was submitted + + VREvent_Notification_Shown = 600, + VREvent_Notification_Hidden = 601, + VREvent_Notification_BeginInteraction = 602, + VREvent_Notification_Destroyed = 603, + + VREvent_Quit = 700, // data is process + VREvent_ProcessQuit = 701, // data is process + VREvent_QuitAborted_UserPrompt = 702, // data is process + VREvent_QuitAcknowledged = 703, // data is process + VREvent_DriverRequestedQuit = 704, // The driver has requested that SteamVR shut down + + VREvent_ChaperoneDataHasChanged = 800, + VREvent_ChaperoneUniverseHasChanged = 801, + VREvent_ChaperoneTempDataHasChanged = 802, + VREvent_ChaperoneSettingsHaveChanged = 803, + VREvent_SeatedZeroPoseReset = 804, + + VREvent_AudioSettingsHaveChanged = 820, + + VREvent_BackgroundSettingHasChanged = 850, + VREvent_CameraSettingsHaveChanged = 851, + VREvent_ReprojectionSettingHasChanged = 852, + VREvent_ModelSkinSettingsHaveChanged = 853, + VREvent_EnvironmentSettingsHaveChanged = 854, + + VREvent_StatusUpdate = 900, + + VREvent_MCImageUpdated = 1000, + + VREvent_FirmwareUpdateStarted = 1100, + VREvent_FirmwareUpdateFinished = 1101, + + VREvent_KeyboardClosed = 1200, + VREvent_KeyboardCharInput = 1201, + VREvent_KeyboardDone = 1202, // Sent when DONE button clicked on keyboard + + VREvent_ApplicationTransitionStarted = 1300, + VREvent_ApplicationTransitionAborted = 1301, + VREvent_ApplicationTransitionNewAppStarted = 1302, + VREvent_ApplicationListUpdated = 1303, + VREvent_ApplicationMimeTypeLoad = 1304, + + VREvent_Compositor_MirrorWindowShown = 1400, + VREvent_Compositor_MirrorWindowHidden = 1401, + VREvent_Compositor_ChaperoneBoundsShown = 1410, + VREvent_Compositor_ChaperoneBoundsHidden = 1411, + + VREvent_TrackedCamera_StartVideoStream = 1500, + VREvent_TrackedCamera_StopVideoStream = 1501, + VREvent_TrackedCamera_PauseVideoStream = 1502, + VREvent_TrackedCamera_ResumeVideoStream = 1503, + + VREvent_PerformanceTest_EnableCapture = 1600, + VREvent_PerformanceTest_DisableCapture = 1601, + VREvent_PerformanceTest_FidelityLevel = 1602, + + // Vendors are free to expose private events in this reserved region + VREvent_VendorSpecific_Reserved_Start = 10000, + VREvent_VendorSpecific_Reserved_End = 19999, +}; + + +/** Level of Hmd activity */ +enum EDeviceActivityLevel +{ + k_EDeviceActivityLevel_Unknown = -1, + k_EDeviceActivityLevel_Idle = 0, + k_EDeviceActivityLevel_UserInteraction = 1, + k_EDeviceActivityLevel_UserInteraction_Timeout = 2, + k_EDeviceActivityLevel_Standby = 3, +}; + + +/** VR controller button and axis IDs */ +enum EVRButtonId +{ + k_EButton_System = 0, + k_EButton_ApplicationMenu = 1, + k_EButton_Grip = 2, + k_EButton_DPad_Left = 3, + k_EButton_DPad_Up = 4, + k_EButton_DPad_Right = 5, + k_EButton_DPad_Down = 6, + k_EButton_A = 7, + + k_EButton_Axis0 = 32, + k_EButton_Axis1 = 33, + k_EButton_Axis2 = 34, + k_EButton_Axis3 = 35, + k_EButton_Axis4 = 36, + + // aliases for well known controllers + k_EButton_SteamVR_Touchpad = k_EButton_Axis0, + k_EButton_SteamVR_Trigger = k_EButton_Axis1, + + k_EButton_Dashboard_Back = k_EButton_Grip, + + k_EButton_Max = 64 +}; + +inline uint64_t ButtonMaskFromId( EVRButtonId id ) { return 1ull << id; } + +/** used for controller button events */ +struct VREvent_Controller_t +{ + uint32_t button; // EVRButtonId enum +}; + + +/** used for simulated mouse events in overlay space */ +enum EVRMouseButton +{ + VRMouseButton_Left = 0x0001, + VRMouseButton_Right = 0x0002, + VRMouseButton_Middle = 0x0004, +}; + + +/** used for simulated mouse events in overlay space */ +struct VREvent_Mouse_t +{ + float x, y; // co-ords are in GL space, bottom left of the texture is 0,0 + uint32_t button; // EVRMouseButton enum +}; + +/** used for simulated mouse wheel scroll in overlay space */ +struct VREvent_Scroll_t +{ + float xdelta, ydelta; // movement in fraction of the pad traversed since last delta, 1.0 for a full swipe + uint32_t repeatCount; +}; + +/** when in mouse input mode you can receive data from the touchpad, these events are only sent if the users finger + is on the touchpad (or just released from it) +**/ +struct VREvent_TouchPadMove_t +{ + // true if the users finger is detected on the touch pad + bool bFingerDown; + + // How long the finger has been down in seconds + float flSecondsFingerDown; + + // These values indicate the starting finger position (so you can do some basic swipe stuff) + float fValueXFirst; + float fValueYFirst; + + // This is the raw sampled coordinate without deadzoning + float fValueXRaw; + float fValueYRaw; +}; + +/** notification related events. Details will still change at this point */ +struct VREvent_Notification_t +{ + uint64_t ulUserValue; + uint32_t notificationId; +}; + +/** Used for events about processes */ +struct VREvent_Process_t +{ + uint32_t pid; + uint32_t oldPid; + bool bForced; +}; + + +/** Used for a few events about overlays */ +struct VREvent_Overlay_t +{ + uint64_t overlayHandle; +}; + + +/** Used for a few events about overlays */ +struct VREvent_Status_t +{ + uint32_t statusState; // EVRState enum +}; + +/** Used for keyboard events **/ +struct VREvent_Keyboard_t +{ + char cNewInput[8]; // Up to 11 bytes of new input + uint64_t uUserValue; // Possible flags about the new input +}; + +struct VREvent_Ipd_t +{ + float ipdMeters; +}; + +struct VREvent_Chaperone_t +{ + uint64_t m_nPreviousUniverse; + uint64_t m_nCurrentUniverse; +}; + +/** Not actually used for any events */ +struct VREvent_Reserved_t +{ + uint64_t reserved0; + uint64_t reserved1; +}; + +struct VREvent_PerformanceTest_t +{ + uint32_t m_nFidelityLevel; +}; + +struct VREvent_SeatedZeroPoseReset_t +{ + bool bResetBySystemMenu; +}; + +struct VREvent_Screenshot_t +{ + uint32_t handle; + uint32_t type; +}; + +struct VREvent_ScreenshotProgress_t +{ + float progress; +}; + +struct VREvent_ApplicationLaunch_t +{ + uint32_t pid; + uint32_t unArgsHandle; +}; + +/** If you change this you must manually update openvr_interop.cs.py */ +typedef union +{ + VREvent_Reserved_t reserved; + VREvent_Controller_t controller; + VREvent_Mouse_t mouse; + VREvent_Scroll_t scroll; + VREvent_Process_t process; + VREvent_Notification_t notification; + VREvent_Overlay_t overlay; + VREvent_Status_t status; + VREvent_Keyboard_t keyboard; + VREvent_Ipd_t ipd; + VREvent_Chaperone_t chaperone; + VREvent_PerformanceTest_t performanceTest; + VREvent_TouchPadMove_t touchPadMove; + VREvent_SeatedZeroPoseReset_t seatedZeroPoseReset; + VREvent_Screenshot_t screenshot; + VREvent_ScreenshotProgress_t screenshotProgress; + VREvent_ApplicationLaunch_t applicationLaunch; +} VREvent_Data_t; + +/** An event posted by the server to all running applications */ +struct VREvent_t +{ + uint32_t eventType; // EVREventType enum + TrackedDeviceIndex_t trackedDeviceIndex; + float eventAgeSeconds; + // event data must be the end of the struct as its size is variable + VREvent_Data_t data; +}; + + +/** The mesh to draw into the stencil (or depth) buffer to perform +* early stencil (or depth) kills of pixels that will never appear on the HMD. +* This mesh draws on all the pixels that will be hidden after distortion. +* +* If the HMD does not provide a visible area mesh pVertexData will be +* NULL and unTriangleCount will be 0. */ +struct HiddenAreaMesh_t +{ + const HmdVector2_t *pVertexData; + uint32_t unTriangleCount; +}; + + +/** Identifies what kind of axis is on the controller at index n. Read this type +* with pVRSystem->Get( nControllerDeviceIndex, Prop_Axis0Type_Int32 + n ); +*/ +enum EVRControllerAxisType +{ + k_eControllerAxis_None = 0, + k_eControllerAxis_TrackPad = 1, + k_eControllerAxis_Joystick = 2, + k_eControllerAxis_Trigger = 3, // Analog trigger data is in the X axis +}; + + +/** contains information about one axis on the controller */ +struct VRControllerAxis_t +{ + float x; // Ranges from -1.0 to 1.0 for joysticks and track pads. Ranges from 0.0 to 1.0 for triggers were 0 is fully released. + float y; // Ranges from -1.0 to 1.0 for joysticks and track pads. Is always 0.0 for triggers. +}; + + +/** the number of axes in the controller state */ +static const uint32_t k_unControllerStateAxisCount = 5; + + +/** Holds all the state of a controller at one moment in time. */ +struct VRControllerState001_t +{ + // If packet num matches that on your prior call, then the controller state hasn't been changed since + // your last call and there is no need to process it + uint32_t unPacketNum; + + // bit flags for each of the buttons. Use ButtonMaskFromId to turn an ID into a mask + uint64_t ulButtonPressed; + uint64_t ulButtonTouched; + + // Axis data for the controller's analog inputs + VRControllerAxis_t rAxis[ k_unControllerStateAxisCount ]; +}; + + +typedef VRControllerState001_t VRControllerState_t; + + +/** determines how to provide output to the application of various event processing functions. */ +enum EVRControllerEventOutputType +{ + ControllerEventOutput_OSEvents = 0, + ControllerEventOutput_VREvents = 1, +}; + + + +/** Collision Bounds Style */ +enum ECollisionBoundsStyle +{ + COLLISION_BOUNDS_STYLE_BEGINNER = 0, + COLLISION_BOUNDS_STYLE_INTERMEDIATE, + COLLISION_BOUNDS_STYLE_SQUARES, + COLLISION_BOUNDS_STYLE_ADVANCED, + COLLISION_BOUNDS_STYLE_NONE, + + COLLISION_BOUNDS_STYLE_COUNT +}; + +/** Allows the application to customize how the overlay appears in the compositor */ +struct Compositor_OverlaySettings +{ + uint32_t size; // sizeof(Compositor_OverlaySettings) + bool curved, antialias; + float scale, distance, alpha; + float uOffset, vOffset, uScale, vScale; + float gridDivs, gridWidth, gridScale; + HmdMatrix44_t transform; +}; + +/** used to refer to a single VR overlay */ +typedef uint64_t VROverlayHandle_t; + +static const VROverlayHandle_t k_ulOverlayHandleInvalid = 0; + +/** Errors that can occur around VR overlays */ +enum EVROverlayError +{ + VROverlayError_None = 0, + + VROverlayError_UnknownOverlay = 10, + VROverlayError_InvalidHandle = 11, + VROverlayError_PermissionDenied = 12, + VROverlayError_OverlayLimitExceeded = 13, // No more overlays could be created because the maximum number already exist + VROverlayError_WrongVisibilityType = 14, + VROverlayError_KeyTooLong = 15, + VROverlayError_NameTooLong = 16, + VROverlayError_KeyInUse = 17, + VROverlayError_WrongTransformType = 18, + VROverlayError_InvalidTrackedDevice = 19, + VROverlayError_InvalidParameter = 20, + VROverlayError_ThumbnailCantBeDestroyed = 21, + VROverlayError_ArrayTooSmall = 22, + VROverlayError_RequestFailed = 23, + VROverlayError_InvalidTexture = 24, + VROverlayError_UnableToLoadFile = 25, + VROVerlayError_KeyboardAlreadyInUse = 26, + VROverlayError_NoNeighbor = 27, +}; + +/** enum values to pass in to VR_Init to identify whether the application will +* draw a 3D scene. */ +enum EVRApplicationType +{ + VRApplication_Other = 0, // Some other kind of application that isn't covered by the other entries + VRApplication_Scene = 1, // Application will submit 3D frames + VRApplication_Overlay = 2, // Application only interacts with overlays + VRApplication_Background = 3, // Application should not start SteamVR if it's not already running, and should not + // keep it running if everything else quits. + VRApplication_Utility = 4, // Init should not try to load any drivers. The application needs access to utility + // interfaces (like IVRSettings and IVRApplications) but not hardware. + VRApplication_VRMonitor = 5, // Reserved for vrmonitor + VRApplication_SteamWatchdog = 6,// Reserved for Steam + + VRApplication_Max +}; + + +/** error codes for firmware */ +enum EVRFirmwareError +{ + VRFirmwareError_None = 0, + VRFirmwareError_Success = 1, + VRFirmwareError_Fail = 2, +}; + + +/** error codes for notifications */ +enum EVRNotificationError +{ + VRNotificationError_OK = 0, + VRNotificationError_InvalidNotificationId = 100, + VRNotificationError_NotificationQueueFull = 101, + VRNotificationError_InvalidOverlayHandle = 102, + VRNotificationError_SystemWithUserValueAlreadyExists = 103, +}; + + +/** error codes returned by Vr_Init */ + +// Please add adequate error description to https://developer.valvesoftware.com/w/index.php?title=Category:SteamVRHelp +enum EVRInitError +{ + VRInitError_None = 0, + VRInitError_Unknown = 1, + + VRInitError_Init_InstallationNotFound = 100, + VRInitError_Init_InstallationCorrupt = 101, + VRInitError_Init_VRClientDLLNotFound = 102, + VRInitError_Init_FileNotFound = 103, + VRInitError_Init_FactoryNotFound = 104, + VRInitError_Init_InterfaceNotFound = 105, + VRInitError_Init_InvalidInterface = 106, + VRInitError_Init_UserConfigDirectoryInvalid = 107, + VRInitError_Init_HmdNotFound = 108, + VRInitError_Init_NotInitialized = 109, + VRInitError_Init_PathRegistryNotFound = 110, + VRInitError_Init_NoConfigPath = 111, + VRInitError_Init_NoLogPath = 112, + VRInitError_Init_PathRegistryNotWritable = 113, + VRInitError_Init_AppInfoInitFailed = 114, + VRInitError_Init_Retry = 115, // Used internally to cause retries to vrserver + VRInitError_Init_InitCanceledByUser = 116, // The calling application should silently exit. The user canceled app startup + VRInitError_Init_AnotherAppLaunching = 117, + VRInitError_Init_SettingsInitFailed = 118, + VRInitError_Init_ShuttingDown = 119, + VRInitError_Init_TooManyObjects = 120, + VRInitError_Init_NoServerForBackgroundApp = 121, + VRInitError_Init_NotSupportedWithCompositor = 122, + VRInitError_Init_NotAvailableToUtilityApps = 123, + VRInitError_Init_Internal = 124, + VRInitError_Init_HmdDriverIdIsNone = 125, + VRInitError_Init_HmdNotFoundPresenceFailed = 126, + VRInitError_Init_VRMonitorNotFound = 127, + VRInitError_Init_VRMonitorStartupFailed = 128, + VRInitError_Init_LowPowerWatchdogNotSupported = 129, + VRInitError_Init_InvalidApplicationType = 130, + VRInitError_Init_NotAvailableToWatchdogApps = 131, + VRInitError_Init_WatchdogDisabledInSettings = 132, + + VRInitError_Driver_Failed = 200, + VRInitError_Driver_Unknown = 201, + VRInitError_Driver_HmdUnknown = 202, + VRInitError_Driver_NotLoaded = 203, + VRInitError_Driver_RuntimeOutOfDate = 204, + VRInitError_Driver_HmdInUse = 205, + VRInitError_Driver_NotCalibrated = 206, + VRInitError_Driver_CalibrationInvalid = 207, + VRInitError_Driver_HmdDisplayNotFound = 208, + VRInitError_Driver_TrackedDeviceInterfaceUnknown = 209, + // VRInitError_Driver_HmdDisplayNotFoundAfterFix = 210, // not needed: here for historic reasons + VRInitError_Driver_HmdDriverIdOutOfBounds = 211, + VRInitError_Driver_HmdDisplayMirrored = 212, + + VRInitError_IPC_ServerInitFailed = 300, + VRInitError_IPC_ConnectFailed = 301, + VRInitError_IPC_SharedStateInitFailed = 302, + VRInitError_IPC_CompositorInitFailed = 303, + VRInitError_IPC_MutexInitFailed = 304, + VRInitError_IPC_Failed = 305, + VRInitError_IPC_CompositorConnectFailed = 306, + VRInitError_IPC_CompositorInvalidConnectResponse = 307, + VRInitError_IPC_ConnectFailedAfterMultipleAttempts = 308, + + VRInitError_Compositor_Failed = 400, + VRInitError_Compositor_D3D11HardwareRequired = 401, + VRInitError_Compositor_FirmwareRequiresUpdate = 402, + VRInitError_Compositor_OverlayInitFailed = 403, + VRInitError_Compositor_ScreenshotsInitFailed = 404, + + VRInitError_VendorSpecific_UnableToConnectToOculusRuntime = 1000, + + VRInitError_VendorSpecific_HmdFound_CantOpenDevice = 1101, + VRInitError_VendorSpecific_HmdFound_UnableToRequestConfigStart = 1102, + VRInitError_VendorSpecific_HmdFound_NoStoredConfig = 1103, + VRInitError_VendorSpecific_HmdFound_ConfigTooBig = 1104, + VRInitError_VendorSpecific_HmdFound_ConfigTooSmall = 1105, + VRInitError_VendorSpecific_HmdFound_UnableToInitZLib = 1106, + VRInitError_VendorSpecific_HmdFound_CantReadFirmwareVersion = 1107, + VRInitError_VendorSpecific_HmdFound_UnableToSendUserDataStart = 1108, + VRInitError_VendorSpecific_HmdFound_UnableToGetUserDataStart = 1109, + VRInitError_VendorSpecific_HmdFound_UnableToGetUserDataNext = 1110, + VRInitError_VendorSpecific_HmdFound_UserDataAddressRange = 1111, + VRInitError_VendorSpecific_HmdFound_UserDataError = 1112, + VRInitError_VendorSpecific_HmdFound_ConfigFailedSanityCheck = 1113, + + VRInitError_Steam_SteamInstallationNotFound = 2000, +}; + +enum EVRScreenshotType +{ + VRScreenshotType_None = 0, + VRScreenshotType_Mono = 1, // left eye only + VRScreenshotType_Stereo = 2, + VRScreenshotType_Cubemap = 3, + VRScreenshotType_MonoPanorama = 4, + VRScreenshotType_StereoPanorama = 5 +}; + +enum EVRScreenshotPropertyFilenames +{ + VRScreenshotPropertyFilenames_Preview = 0, + VRScreenshotPropertyFilenames_VR = 1, +}; + +enum EVRTrackedCameraError +{ + VRTrackedCameraError_None = 0, + VRTrackedCameraError_OperationFailed = 100, + VRTrackedCameraError_InvalidHandle = 101, + VRTrackedCameraError_InvalidFrameHeaderVersion = 102, + VRTrackedCameraError_OutOfHandles = 103, + VRTrackedCameraError_IPCFailure = 104, + VRTrackedCameraError_NotSupportedForThisDevice = 105, + VRTrackedCameraError_SharedMemoryFailure = 106, + VRTrackedCameraError_FrameBufferingFailure = 107, + VRTrackedCameraError_StreamSetupFailure = 108, + VRTrackedCameraError_InvalidGLTextureId = 109, + VRTrackedCameraError_InvalidSharedTextureHandle = 110, + VRTrackedCameraError_FailedToGetGLTextureId = 111, + VRTrackedCameraError_SharedTextureFailure = 112, + VRTrackedCameraError_NoFrameAvailable = 113, + VRTrackedCameraError_InvalidArgument = 114, + VRTrackedCameraError_InvalidFrameBufferSize = 115, +}; + +enum EVRTrackedCameraFrameType +{ + VRTrackedCameraFrameType_Distorted = 0, // This is the camera video frame size in pixels, still distorted. + VRTrackedCameraFrameType_Undistorted, // In pixels, an undistorted inscribed rectangle region without invalid regions. This size is subject to changes shortly. + VRTrackedCameraFrameType_MaximumUndistorted, // In pixels, maximum undistorted with invalid regions. Non zero alpha component identifies valid regions. + MAX_CAMERA_FRAME_TYPES +}; + +typedef uint64_t TrackedCameraHandle_t; +#define INVALID_TRACKED_CAMERA_HANDLE ((vr::TrackedCameraHandle_t)0) + +struct CameraVideoStreamFrameHeader_t +{ + EVRTrackedCameraFrameType eFrameType; + + uint32_t nWidth; + uint32_t nHeight; + uint32_t nBytesPerPixel; + + uint32_t nFrameSequence; + + TrackedDevicePose_t standingTrackedDevicePose; +}; + +// Screenshot types +typedef uint32_t ScreenshotHandle_t; + +static const uint32_t k_unScreenshotHandleInvalid = 0; + +#pragma pack( pop ) + +// figure out how to import from the VR API dll +#if defined(_WIN32) + +#ifdef VR_API_EXPORT +#define VR_INTERFACE extern "C" __declspec( dllexport ) +#else +#define VR_INTERFACE extern "C" __declspec( dllimport ) +#endif + +#elif defined(__GNUC__) || defined(COMPILER_GCC) || defined(__APPLE__) + +#ifdef VR_API_EXPORT +#define VR_INTERFACE extern "C" __attribute__((visibility("default"))) +#else +#define VR_INTERFACE extern "C" +#endif + +#else +#error "Unsupported Platform." +#endif + + +#if defined( _WIN32 ) +#define VR_CALLTYPE __cdecl +#else +#define VR_CALLTYPE +#endif + +} // namespace vr + +#endif // _INCLUDE_VRTYPES_H + + +// vrannotation.h +#ifdef API_GEN +# define VR_CLANG_ATTR(ATTR) __attribute__((annotate( ATTR ))) +#else +# define VR_CLANG_ATTR(ATTR) +#endif + +#define VR_METHOD_DESC(DESC) VR_CLANG_ATTR( "desc:" #DESC ";" ) +#define VR_IGNOREATTR() VR_CLANG_ATTR( "ignore" ) +#define VR_OUT_STRUCT() VR_CLANG_ATTR( "out_struct: ;" ) +#define VR_OUT_STRING() VR_CLANG_ATTR( "out_string: ;" ) +#define VR_OUT_ARRAY_CALL(COUNTER,FUNCTION,PARAMS) VR_CLANG_ATTR( "out_array_call:" #COUNTER "," #FUNCTION "," #PARAMS ";" ) +#define VR_OUT_ARRAY_COUNT(COUNTER) VR_CLANG_ATTR( "out_array_count:" #COUNTER ";" ) +#define VR_ARRAY_COUNT(COUNTER) VR_CLANG_ATTR( "array_count:" #COUNTER ";" ) +#define VR_ARRAY_COUNT_D(COUNTER, DESC) VR_CLANG_ATTR( "array_count:" #COUNTER ";desc:" #DESC ) +#define VR_BUFFER_COUNT(COUNTER) VR_CLANG_ATTR( "buffer_count:" #COUNTER ";" ) +#define VR_OUT_BUFFER_COUNT(COUNTER) VR_CLANG_ATTR( "out_buffer_count:" #COUNTER ";" ) +#define VR_OUT_STRING_COUNT(COUNTER) VR_CLANG_ATTR( "out_string_count:" #COUNTER ";" ) + +// ivrsystem.h +namespace vr +{ + +class IVRSystem +{ +public: + + + // ------------------------------------ + // Display Methods + // ------------------------------------ + + /** Suggested size for the intermediate render target that the distortion pulls from. */ + virtual void GetRecommendedRenderTargetSize( uint32_t *pnWidth, uint32_t *pnHeight ) = 0; + + /** The projection matrix for the specified eye */ + virtual HmdMatrix44_t GetProjectionMatrix( EVREye eEye, float fNearZ, float fFarZ, EGraphicsAPIConvention eProjType ) = 0; + + /** The components necessary to build your own projection matrix in case your + * application is doing something fancy like infinite Z */ + virtual void GetProjectionRaw( EVREye eEye, float *pfLeft, float *pfRight, float *pfTop, float *pfBottom ) = 0; + + /** Returns the result of the distortion function for the specified eye and input UVs. UVs go from 0,0 in + * the upper left of that eye's viewport and 1,1 in the lower right of that eye's viewport. */ + virtual DistortionCoordinates_t ComputeDistortion( EVREye eEye, float fU, float fV ) = 0; + + /** Returns the transform from eye space to the head space. Eye space is the per-eye flavor of head + * space that provides stereo disparity. Instead of Model * View * Projection the sequence is Model * View * Eye^-1 * Projection. + * Normally View and Eye^-1 will be multiplied together and treated as View in your application. + */ + virtual HmdMatrix34_t GetEyeToHeadTransform( EVREye eEye ) = 0; + + /** Returns the number of elapsed seconds since the last recorded vsync event. This + * will come from a vsync timer event in the timer if possible or from the application-reported + * time if that is not available. If no vsync times are available the function will + * return zero for vsync time and frame counter and return false from the method. */ + virtual bool GetTimeSinceLastVsync( float *pfSecondsSinceLastVsync, uint64_t *pulFrameCounter ) = 0; + + /** [D3D9 Only] + * Returns the adapter index that the user should pass into CreateDevice to set up D3D9 in such + * a way that it can go full screen exclusive on the HMD. Returns -1 if there was an error. + */ + virtual int32_t GetD3D9AdapterIndex() = 0; + + /** [D3D10/11 Only] + * Returns the adapter index and output index that the user should pass into EnumAdapters and EnumOutputs + * to create the device and swap chain in DX10 and DX11. If an error occurs both indices will be set to -1. + */ + virtual void GetDXGIOutputInfo( int32_t *pnAdapterIndex ) = 0; + + // ------------------------------------ + // Display Mode methods + // ------------------------------------ + + /** Use to determine if the headset display is part of the desktop (i.e. extended) or hidden (i.e. direct mode). */ + virtual bool IsDisplayOnDesktop() = 0; + + /** Set the display visibility (true = extended, false = direct mode). Return value of true indicates that the change was successful. */ + virtual bool SetDisplayVisibility( bool bIsVisibleOnDesktop ) = 0; + + // ------------------------------------ + // Tracking Methods + // ------------------------------------ + + /** The pose that the tracker thinks that the HMD will be in at the specified number of seconds into the + * future. Pass 0 to get the state at the instant the method is called. Most of the time the application should + * calculate the time until the photons will be emitted from the display and pass that time into the method. + * + * This is roughly analogous to the inverse of the view matrix in most applications, though + * many games will need to do some additional rotation or translation on top of the rotation + * and translation provided by the head pose. + * + * For devices where bPoseIsValid is true the application can use the pose to position the device + * in question. The provided array can be any size up to k_unMaxTrackedDeviceCount. + * + * Seated experiences should call this method with TrackingUniverseSeated and receive poses relative + * to the seated zero pose. Standing experiences should call this method with TrackingUniverseStanding + * and receive poses relative to the Chaperone Play Area. TrackingUniverseRawAndUncalibrated should + * probably not be used unless the application is the Chaperone calibration tool itself, but will provide + * poses relative to the hardware-specific coordinate system in the driver. + */ + virtual void GetDeviceToAbsoluteTrackingPose( ETrackingUniverseOrigin eOrigin, float fPredictedSecondsToPhotonsFromNow, VR_ARRAY_COUNT(unTrackedDevicePoseArrayCount) TrackedDevicePose_t *pTrackedDevicePoseArray, uint32_t unTrackedDevicePoseArrayCount ) = 0; + + /** Sets the zero pose for the seated tracker coordinate system to the current position and yaw of the HMD. After + * ResetSeatedZeroPose all GetDeviceToAbsoluteTrackingPose calls that pass TrackingUniverseSeated as the origin + * will be relative to this new zero pose. The new zero coordinate system will not change the fact that the Y axis + * is up in the real world, so the next pose returned from GetDeviceToAbsoluteTrackingPose after a call to + * ResetSeatedZeroPose may not be exactly an identity matrix. + * + * NOTE: This function overrides the user's previously saved seated zero pose and should only be called as the result of a user action. + * Users are also able to set their seated zero pose via the OpenVR Dashboard. + **/ + virtual void ResetSeatedZeroPose() = 0; + + /** Returns the transform from the seated zero pose to the standing absolute tracking system. This allows + * applications to represent the seated origin to used or transform object positions from one coordinate + * system to the other. + * + * The seated origin may or may not be inside the Play Area or Collision Bounds returned by IVRChaperone. Its position + * depends on what the user has set from the Dashboard settings and previous calls to ResetSeatedZeroPose. */ + virtual HmdMatrix34_t GetSeatedZeroPoseToStandingAbsoluteTrackingPose() = 0; + + /** Returns the transform from the tracking origin to the standing absolute tracking system. This allows + * applications to convert from raw tracking space to the calibrated standing coordinate system. */ + virtual HmdMatrix34_t GetRawZeroPoseToStandingAbsoluteTrackingPose() = 0; + + /** Get a sorted array of device indices of a given class of tracked devices (e.g. controllers). Devices are sorted right to left + * relative to the specified tracked device (default: hmd -- pass in -1 for absolute tracking space). Returns the number of devices + * in the list, or the size of the array needed if not large enough. */ + virtual uint32_t GetSortedTrackedDeviceIndicesOfClass( ETrackedDeviceClass eTrackedDeviceClass, VR_ARRAY_COUNT(unTrackedDeviceIndexArrayCount) vr::TrackedDeviceIndex_t *punTrackedDeviceIndexArray, uint32_t unTrackedDeviceIndexArrayCount, vr::TrackedDeviceIndex_t unRelativeToTrackedDeviceIndex = k_unTrackedDeviceIndex_Hmd ) = 0; + + /** Returns the level of activity on the device. */ + virtual EDeviceActivityLevel GetTrackedDeviceActivityLevel( vr::TrackedDeviceIndex_t unDeviceId ) = 0; + + /** Convenience utility to apply the specified transform to the specified pose. + * This properly transforms all pose components, including velocity and angular velocity + */ + virtual void ApplyTransform( TrackedDevicePose_t *pOutputPose, const TrackedDevicePose_t *pTrackedDevicePose, const HmdMatrix34_t *pTransform ) = 0; + + /** Returns the device index associated with a specific role, for example the left hand or the right hand. */ + virtual vr::TrackedDeviceIndex_t GetTrackedDeviceIndexForControllerRole( vr::ETrackedControllerRole unDeviceType ) = 0; + + /** Returns the controller type associated with a device index. */ + virtual vr::ETrackedControllerRole GetControllerRoleForTrackedDeviceIndex( vr::TrackedDeviceIndex_t unDeviceIndex ) = 0; + + // ------------------------------------ + // Property methods + // ------------------------------------ + + /** Returns the device class of a tracked device. If there has not been a device connected in this slot + * since the application started this function will return TrackedDevice_Invalid. For previous detected + * devices the function will return the previously observed device class. + * + * To determine which devices exist on the system, just loop from 0 to k_unMaxTrackedDeviceCount and check + * the device class. Every device with something other than TrackedDevice_Invalid is associated with an + * actual tracked device. */ + virtual ETrackedDeviceClass GetTrackedDeviceClass( vr::TrackedDeviceIndex_t unDeviceIndex ) = 0; + + /** Returns true if there is a device connected in this slot. */ + virtual bool IsTrackedDeviceConnected( vr::TrackedDeviceIndex_t unDeviceIndex ) = 0; + + /** Returns a bool property. If the device index is not valid or the property is not a bool type this function will return false. */ + virtual bool GetBoolTrackedDeviceProperty( vr::TrackedDeviceIndex_t unDeviceIndex, ETrackedDeviceProperty prop, ETrackedPropertyError *pError = 0L ) = 0; + + /** Returns a float property. If the device index is not valid or the property is not a float type this function will return 0. */ + virtual float GetFloatTrackedDeviceProperty( vr::TrackedDeviceIndex_t unDeviceIndex, ETrackedDeviceProperty prop, ETrackedPropertyError *pError = 0L ) = 0; + + /** Returns an int property. If the device index is not valid or the property is not a int type this function will return 0. */ + virtual int32_t GetInt32TrackedDeviceProperty( vr::TrackedDeviceIndex_t unDeviceIndex, ETrackedDeviceProperty prop, ETrackedPropertyError *pError = 0L ) = 0; + + /** Returns a uint64 property. If the device index is not valid or the property is not a uint64 type this function will return 0. */ + virtual uint64_t GetUint64TrackedDeviceProperty( vr::TrackedDeviceIndex_t unDeviceIndex, ETrackedDeviceProperty prop, ETrackedPropertyError *pError = 0L ) = 0; + + /** Returns a matrix property. If the device index is not valid or the property is not a matrix type, this function will return identity. */ + virtual HmdMatrix34_t GetMatrix34TrackedDeviceProperty( vr::TrackedDeviceIndex_t unDeviceIndex, ETrackedDeviceProperty prop, ETrackedPropertyError *pError = 0L ) = 0; + + /** Returns a string property. If the device index is not valid or the property is not a string type this function will + * return 0. Otherwise it returns the length of the number of bytes necessary to hold this string including the trailing + * null. Strings will generally fit in buffers of k_unTrackingStringSize characters. */ + virtual uint32_t GetStringTrackedDeviceProperty( vr::TrackedDeviceIndex_t unDeviceIndex, ETrackedDeviceProperty prop, VR_OUT_STRING() char *pchValue, uint32_t unBufferSize, ETrackedPropertyError *pError = 0L ) = 0; + + /** returns a string that corresponds with the specified property error. The string will be the name + * of the error enum value for all valid error codes */ + virtual const char *GetPropErrorNameFromEnum( ETrackedPropertyError error ) = 0; + + // ------------------------------------ + // Event methods + // ------------------------------------ + + /** Returns true and fills the event with the next event on the queue if there is one. If there are no events + * this method returns false. uncbVREvent should be the size in bytes of the VREvent_t struct */ + virtual bool PollNextEvent( VREvent_t *pEvent, uint32_t uncbVREvent ) = 0; + + /** Returns true and fills the event with the next event on the queue if there is one. If there are no events + * this method returns false. Fills in the pose of the associated tracked device in the provided pose struct. + * This pose will always be older than the call to this function and should not be used to render the device. + uncbVREvent should be the size in bytes of the VREvent_t struct */ + virtual bool PollNextEventWithPose( ETrackingUniverseOrigin eOrigin, VREvent_t *pEvent, uint32_t uncbVREvent, vr::TrackedDevicePose_t *pTrackedDevicePose ) = 0; + + /** returns the name of an EVREvent enum value */ + virtual const char *GetEventTypeNameFromEnum( EVREventType eType ) = 0; + + // ------------------------------------ + // Rendering helper methods + // ------------------------------------ + + /** Returns the stencil mesh information for the current HMD. If this HMD does not have a stencil mesh the vertex data and count will be + * NULL and 0 respectively. This mesh is meant to be rendered into the stencil buffer (or into the depth buffer setting nearz) before rendering + * each eye's view. The pixels covered by this mesh will never be seen by the user after the lens distortion is applied and based on visibility to the panels. + * This will improve perf by letting the GPU early-reject pixels the user will never see before running the pixel shader. + * NOTE: Render this mesh with backface culling disabled since the winding order of the vertices can be different per-HMD or per-eye. + */ + virtual HiddenAreaMesh_t GetHiddenAreaMesh( EVREye eEye ) = 0; + + + // ------------------------------------ + // Controller methods + // ------------------------------------ + + /** Fills the supplied struct with the current state of the controller. Returns false if the controller index + * is invalid. */ + virtual bool GetControllerState( vr::TrackedDeviceIndex_t unControllerDeviceIndex, vr::VRControllerState_t *pControllerState ) = 0; + + /** fills the supplied struct with the current state of the controller and the provided pose with the pose of + * the controller when the controller state was updated most recently. Use this form if you need a precise controller + * pose as input to your application when the user presses or releases a button. */ + virtual bool GetControllerStateWithPose( ETrackingUniverseOrigin eOrigin, vr::TrackedDeviceIndex_t unControllerDeviceIndex, vr::VRControllerState_t *pControllerState, TrackedDevicePose_t *pTrackedDevicePose ) = 0; + + /** Trigger a single haptic pulse on a controller. After this call the application may not trigger another haptic pulse on this controller + * and axis combination for 5ms. */ + virtual void TriggerHapticPulse( vr::TrackedDeviceIndex_t unControllerDeviceIndex, uint32_t unAxisId, unsigned short usDurationMicroSec ) = 0; + + /** returns the name of an EVRButtonId enum value */ + virtual const char *GetButtonIdNameFromEnum( EVRButtonId eButtonId ) = 0; + + /** returns the name of an EVRControllerAxisType enum value */ + virtual const char *GetControllerAxisTypeNameFromEnum( EVRControllerAxisType eAxisType ) = 0; + + /** Tells OpenVR that this process wants exclusive access to controller button states and button events. Other apps will be notified that + * they have lost input focus with a VREvent_InputFocusCaptured event. Returns false if input focus could not be captured for + * some reason. */ + virtual bool CaptureInputFocus() = 0; + + /** Tells OpenVR that this process no longer wants exclusive access to button states and button events. Other apps will be notified + * that input focus has been released with a VREvent_InputFocusReleased event. */ + virtual void ReleaseInputFocus() = 0; + + /** Returns true if input focus is captured by another process. */ + virtual bool IsInputFocusCapturedByAnotherProcess() = 0; + + // ------------------------------------ + // Debug Methods + // ------------------------------------ + + /** Sends a request to the driver for the specified device and returns the response. The maximum response size is 32k, + * but this method can be called with a smaller buffer. If the response exceeds the size of the buffer, it is truncated. + * The size of the response including its terminating null is returned. */ + virtual uint32_t DriverDebugRequest( vr::TrackedDeviceIndex_t unDeviceIndex, const char *pchRequest, char *pchResponseBuffer, uint32_t unResponseBufferSize ) = 0; + + + // ------------------------------------ + // Firmware methods + // ------------------------------------ + + /** Performs the actual firmware update if applicable. + * The following events will be sent, if VRFirmwareError_None was returned: VREvent_FirmwareUpdateStarted, VREvent_FirmwareUpdateFinished + * Use the properties Prop_Firmware_UpdateAvailable_Bool, Prop_Firmware_ManualUpdate_Bool, and Prop_Firmware_ManualUpdateURL_String + * to figure our whether a firmware update is available, and to figure out whether its a manual update + * Prop_Firmware_ManualUpdateURL_String should point to an URL describing the manual update process */ + virtual vr::EVRFirmwareError PerformFirmwareUpdate( vr::TrackedDeviceIndex_t unDeviceIndex ) = 0; + + + // ------------------------------------ + // Application life cycle methods + // ------------------------------------ + + /** Call this to acknowledge to the system that VREvent_Quit has been received and that the process is exiting. + * This extends the timeout until the process is killed. */ + virtual void AcknowledgeQuit_Exiting() = 0; + + /** Call this to tell the system that the user is being prompted to save data. This + * halts the timeout and dismisses the dashboard (if it was up). Applications should be sure to actually + * prompt the user to save and then exit afterward, otherwise the user will be left in a confusing state. */ + virtual void AcknowledgeQuit_UserPrompt() = 0; + +}; + +static const char * const IVRSystem_Version = "IVRSystem_012"; + +} + + +// ivrapplications.h +namespace vr +{ + + /** Used for all errors reported by the IVRApplications interface */ + enum EVRApplicationError + { + VRApplicationError_None = 0, + + VRApplicationError_AppKeyAlreadyExists = 100, // Only one application can use any given key + VRApplicationError_NoManifest = 101, // the running application does not have a manifest + VRApplicationError_NoApplication = 102, // No application is running + VRApplicationError_InvalidIndex = 103, + VRApplicationError_UnknownApplication = 104, // the application could not be found + VRApplicationError_IPCFailed = 105, // An IPC failure caused the request to fail + VRApplicationError_ApplicationAlreadyRunning = 106, + VRApplicationError_InvalidManifest = 107, + VRApplicationError_InvalidApplication = 108, + VRApplicationError_LaunchFailed = 109, // the process didn't start + VRApplicationError_ApplicationAlreadyStarting = 110, // the system was already starting the same application + VRApplicationError_LaunchInProgress = 111, // The system was already starting a different application + VRApplicationError_OldApplicationQuitting = 112, + VRApplicationError_TransitionAborted = 113, + VRApplicationError_IsTemplate = 114, // error when you try to call LaunchApplication() on a template type app (use LaunchTemplateApplication) + + VRApplicationError_BufferTooSmall = 200, // The provided buffer was too small to fit the requested data + VRApplicationError_PropertyNotSet = 201, // The requested property was not set + VRApplicationError_UnknownProperty = 202, + VRApplicationError_InvalidParameter = 203, + }; + + /** The maximum length of an application key */ + static const uint32_t k_unMaxApplicationKeyLength = 128; + + /** these are the properties available on applications. */ + enum EVRApplicationProperty + { + VRApplicationProperty_Name_String = 0, + + VRApplicationProperty_LaunchType_String = 11, + VRApplicationProperty_WorkingDirectory_String = 12, + VRApplicationProperty_BinaryPath_String = 13, + VRApplicationProperty_Arguments_String = 14, + VRApplicationProperty_URL_String = 15, + + VRApplicationProperty_Description_String = 50, + VRApplicationProperty_NewsURL_String = 51, + VRApplicationProperty_ImagePath_String = 52, + VRApplicationProperty_Source_String = 53, + + VRApplicationProperty_IsDashboardOverlay_Bool = 60, + VRApplicationProperty_IsTemplate_Bool = 61, + VRApplicationProperty_IsInstanced_Bool = 62, + + VRApplicationProperty_LastLaunchTime_Uint64 = 70, + }; + + /** These are states the scene application startup process will go through. */ + enum EVRApplicationTransitionState + { + VRApplicationTransition_None = 0, + + VRApplicationTransition_OldAppQuitSent = 10, + VRApplicationTransition_WaitingForExternalLaunch = 11, + + VRApplicationTransition_NewAppLaunched = 20, + }; + + struct AppOverrideKeys_t + { + const char *pchKey; + const char *pchValue; + }; + + class IVRApplications + { + public: + + // --------------- Application management --------------- // + + /** Adds an application manifest to the list to load when building the list of installed applications. + * Temporary manifests are not automatically loaded */ + virtual EVRApplicationError AddApplicationManifest( const char *pchApplicationManifestFullPath, bool bTemporary = false ) = 0; + + /** Removes an application manifest from the list to load when building the list of installed applications. */ + virtual EVRApplicationError RemoveApplicationManifest( const char *pchApplicationManifestFullPath ) = 0; + + /** Returns true if an application is installed */ + virtual bool IsApplicationInstalled( const char *pchAppKey ) = 0; + + /** Returns the number of applications available in the list */ + virtual uint32_t GetApplicationCount() = 0; + + /** Returns the key of the specified application. The index is at least 0 and is less than the return + * value of GetApplicationCount(). The buffer should be at least k_unMaxApplicationKeyLength in order to + * fit the key. */ + virtual EVRApplicationError GetApplicationKeyByIndex( uint32_t unApplicationIndex, char *pchAppKeyBuffer, uint32_t unAppKeyBufferLen ) = 0; + + /** Returns the key of the application for the specified Process Id. The buffer should be at least + * k_unMaxApplicationKeyLength in order to fit the key. */ + virtual EVRApplicationError GetApplicationKeyByProcessId( uint32_t unProcessId, char *pchAppKeyBuffer, uint32_t unAppKeyBufferLen ) = 0; + + /** Launches the application. The existing scene application will exit and then the new application will start. + * This call is not valid for dashboard overlay applications. */ + virtual EVRApplicationError LaunchApplication( const char *pchAppKey ) = 0; + + /** Launches an instance of an application of type template, with its app key being pchNewAppKey (which must be unique) and optionally override sections + * from the manifest file via AppOverrideKeys_t + */ + virtual EVRApplicationError LaunchTemplateApplication( const char *pchTemplateAppKey, const char *pchNewAppKey, VR_ARRAY_COUNT( unKeys ) const AppOverrideKeys_t *pKeys, uint32_t unKeys ) = 0; + + /** launches the application currently associated with this mime type and passes it the option args, typically the filename or object name of the item being launched */ + virtual vr::EVRApplicationError LaunchApplicationFromMimeType( const char *pchMimeType, const char *pchArgs ) = 0; + + /** Launches the dashboard overlay application if it is not already running. This call is only valid for + * dashboard overlay applications. */ + virtual EVRApplicationError LaunchDashboardOverlay( const char *pchAppKey ) = 0; + + /** Cancel a pending launch for an application */ + virtual bool CancelApplicationLaunch( const char *pchAppKey ) = 0; + + /** Identifies a running application. OpenVR can't always tell which process started in response + * to a URL. This function allows a URL handler (or the process itself) to identify the app key + * for the now running application. Passing a process ID of 0 identifies the calling process. + * The application must be one that's known to the system via a call to AddApplicationManifest. */ + virtual EVRApplicationError IdentifyApplication( uint32_t unProcessId, const char *pchAppKey ) = 0; + + /** Returns the process ID for an application. Return 0 if the application was not found or is not running. */ + virtual uint32_t GetApplicationProcessId( const char *pchAppKey ) = 0; + + /** Returns a string for an applications error */ + virtual const char *GetApplicationsErrorNameFromEnum( EVRApplicationError error ) = 0; + + // --------------- Application properties --------------- // + + /** Returns a value for an application property. The required buffer size to fit this value will be returned. */ + virtual uint32_t GetApplicationPropertyString( const char *pchAppKey, EVRApplicationProperty eProperty, char *pchPropertyValueBuffer, uint32_t unPropertyValueBufferLen, EVRApplicationError *peError = nullptr ) = 0; + + /** Returns a bool value for an application property. Returns false in all error cases. */ + virtual bool GetApplicationPropertyBool( const char *pchAppKey, EVRApplicationProperty eProperty, EVRApplicationError *peError = nullptr ) = 0; + + /** Returns a uint64 value for an application property. Returns 0 in all error cases. */ + virtual uint64_t GetApplicationPropertyUint64( const char *pchAppKey, EVRApplicationProperty eProperty, EVRApplicationError *peError = nullptr ) = 0; + + /** Sets the application auto-launch flag. This is only valid for applications which return true for VRApplicationProperty_IsDashboardOverlay_Bool. */ + virtual EVRApplicationError SetApplicationAutoLaunch( const char *pchAppKey, bool bAutoLaunch ) = 0; + + /** Gets the application auto-launch flag. This is only valid for applications which return true for VRApplicationProperty_IsDashboardOverlay_Bool. */ + virtual bool GetApplicationAutoLaunch( const char *pchAppKey ) = 0; + + /** Adds this mime-type to the list of supported mime types for this application*/ + virtual EVRApplicationError SetDefaultApplicationForMimeType( const char *pchAppKey, const char *pchMimeType ) = 0; + + /** return the app key that will open this mime type */ + virtual bool GetDefaultApplicationForMimeType( const char *pchMimeType, char *pchAppKeyBuffer, uint32_t unAppKeyBufferLen ) = 0; + + /** Get the list of supported mime types for this application, comma-delimited */ + virtual bool GetApplicationSupportedMimeTypes( const char *pchAppKey, char *pchMimeTypesBuffer, uint32_t unMimeTypesBuffer ) = 0; + + /** Get the list of app-keys that support this mime type, comma-delimited, the return value is number of bytes you need to return the full string */ + virtual uint32_t GetApplicationsThatSupportMimeType( const char *pchMimeType, char *pchAppKeysThatSupportBuffer, uint32_t unAppKeysThatSupportBuffer ) = 0; + + /** Get the args list from an app launch that had the process already running, you call this when you get a VREvent_ApplicationMimeTypeLoad */ + virtual uint32_t GetApplicationLaunchArguments( uint32_t unHandle, char *pchArgs, uint32_t unArgs ) = 0; + + // --------------- Transition methods --------------- // + + /** Returns the app key for the application that is starting up */ + virtual EVRApplicationError GetStartingApplication( char *pchAppKeyBuffer, uint32_t unAppKeyBufferLen ) = 0; + + /** Returns the application transition state */ + virtual EVRApplicationTransitionState GetTransitionState() = 0; + + /** Returns errors that would prevent the specified application from launching immediately. Calling this function will + * cause the current scene application to quit, so only call it when you are actually about to launch something else. + * What the caller should do about these failures depends on the failure: + * VRApplicationError_OldApplicationQuitting - An existing application has been told to quit. Wait for a VREvent_ProcessQuit + * and try again. + * VRApplicationError_ApplicationAlreadyStarting - This application is already starting. This is a permanent failure. + * VRApplicationError_LaunchInProgress - A different application is already starting. This is a permanent failure. + * VRApplicationError_None - Go ahead and launch. Everything is clear. + */ + virtual EVRApplicationError PerformApplicationPrelaunchCheck( const char *pchAppKey ) = 0; + + /** Returns a string for an application transition state */ + virtual const char *GetApplicationsTransitionStateNameFromEnum( EVRApplicationTransitionState state ) = 0; + + /** Returns true if the outgoing scene app has requested a save prompt before exiting */ + virtual bool IsQuitUserPromptRequested() = 0; + + /** Starts a subprocess within the calling application. This + * suppresses all application transition UI and automatically identifies the new executable + * as part of the same application. On success the calling process should exit immediately. + * If working directory is NULL or "" the directory portion of the binary path will be + * the working directory. */ + virtual EVRApplicationError LaunchInternalProcess( const char *pchBinaryPath, const char *pchArguments, const char *pchWorkingDirectory ) = 0; + }; + + static const char * const IVRApplications_Version = "IVRApplications_006"; + +} // namespace vr + +// ivrsettings.h +namespace vr +{ + enum EVRSettingsError + { + VRSettingsError_None = 0, + VRSettingsError_IPCFailed = 1, + VRSettingsError_WriteFailed = 2, + VRSettingsError_ReadFailed = 3, + }; + + // The maximum length of a settings key + static const uint32_t k_unMaxSettingsKeyLength = 128; + + class IVRSettings + { + public: + virtual const char *GetSettingsErrorNameFromEnum( EVRSettingsError eError ) = 0; + + // Returns true if file sync occurred (force or settings dirty) + virtual bool Sync( bool bForce = false, EVRSettingsError *peError = nullptr ) = 0; + + virtual bool GetBool( const char *pchSection, const char *pchSettingsKey, bool bDefaultValue, EVRSettingsError *peError = nullptr ) = 0; + virtual void SetBool( const char *pchSection, const char *pchSettingsKey, bool bValue, EVRSettingsError *peError = nullptr ) = 0; + virtual int32_t GetInt32( const char *pchSection, const char *pchSettingsKey, int32_t nDefaultValue, EVRSettingsError *peError = nullptr ) = 0; + virtual void SetInt32( const char *pchSection, const char *pchSettingsKey, int32_t nValue, EVRSettingsError *peError = nullptr ) = 0; + virtual float GetFloat( const char *pchSection, const char *pchSettingsKey, float flDefaultValue, EVRSettingsError *peError = nullptr ) = 0; + virtual void SetFloat( const char *pchSection, const char *pchSettingsKey, float flValue, EVRSettingsError *peError = nullptr ) = 0; + virtual void GetString( const char *pchSection, const char *pchSettingsKey, VR_OUT_STRING() char *pchValue, uint32_t unValueLen, const char *pchDefaultValue, EVRSettingsError *peError = nullptr ) = 0; + virtual void SetString( const char *pchSection, const char *pchSettingsKey, const char *pchValue, EVRSettingsError *peError = nullptr ) = 0; + + virtual void RemoveSection( const char *pchSection, EVRSettingsError *peError = nullptr ) = 0; + virtual void RemoveKeyInSection( const char *pchSection, const char *pchSettingsKey, EVRSettingsError *peError = nullptr ) = 0; + }; + + //----------------------------------------------------------------------------- + static const char * const IVRSettings_Version = "IVRSettings_001"; + + //----------------------------------------------------------------------------- + // steamvr keys + + static const char * const k_pch_SteamVR_Section = "steamvr"; + static const char * const k_pch_SteamVR_RequireHmd_String = "requireHmd"; + static const char * const k_pch_SteamVR_ForcedDriverKey_String = "forcedDriver"; + static const char * const k_pch_SteamVR_ForcedHmdKey_String = "forcedHmd"; + static const char * const k_pch_SteamVR_DisplayDebug_Bool = "displayDebug"; + static const char * const k_pch_SteamVR_DebugProcessPipe_String = "debugProcessPipe"; + static const char * const k_pch_SteamVR_EnableDistortion_Bool = "enableDistortion"; + static const char * const k_pch_SteamVR_DisplayDebugX_Int32 = "displayDebugX"; + static const char * const k_pch_SteamVR_DisplayDebugY_Int32 = "displayDebugY"; + static const char * const k_pch_SteamVR_SendSystemButtonToAllApps_Bool= "sendSystemButtonToAllApps"; + static const char * const k_pch_SteamVR_LogLevel_Int32 = "loglevel"; + static const char * const k_pch_SteamVR_IPD_Float = "ipd"; + static const char * const k_pch_SteamVR_Background_String = "background"; + static const char * const k_pch_SteamVR_BackgroundCameraHeight_Float = "backgroundCameraHeight"; + static const char * const k_pch_SteamVR_BackgroundDomeRadius_Float = "backgroundDomeRadius"; + static const char * const k_pch_SteamVR_Environment_String = "environment"; + static const char * const k_pch_SteamVR_GridColor_String = "gridColor"; + static const char * const k_pch_SteamVR_PlayAreaColor_String = "playAreaColor"; + static const char * const k_pch_SteamVR_ShowStage_Bool = "showStage"; + static const char * const k_pch_SteamVR_ActivateMultipleDrivers_Bool = "activateMultipleDrivers"; + static const char * const k_pch_SteamVR_PowerOffOnExit_Bool = "powerOffOnExit"; + static const char * const k_pch_SteamVR_StandbyAppRunningTimeout_Float = "standbyAppRunningTimeout"; + static const char * const k_pch_SteamVR_StandbyNoAppTimeout_Float = "standbyNoAppTimeout"; + static const char * const k_pch_SteamVR_DirectMode_Bool = "directMode"; + static const char * const k_pch_SteamVR_DirectModeEdidVid_Int32 = "directModeEdidVid"; + static const char * const k_pch_SteamVR_DirectModeEdidPid_Int32 = "directModeEdidPid"; + static const char * const k_pch_SteamVR_UsingSpeakers_Bool = "usingSpeakers"; + static const char * const k_pch_SteamVR_SpeakersForwardYawOffsetDegrees_Float = "speakersForwardYawOffsetDegrees"; + static const char * const k_pch_SteamVR_BaseStationPowerManagement_Bool = "basestationPowerManagement"; + static const char * const k_pch_SteamVR_NeverKillProcesses_Bool = "neverKillProcesses"; + static const char * const k_pch_SteamVR_RenderTargetMultiplier_Float = "renderTargetMultiplier"; + static const char * const k_pch_SteamVR_AllowReprojection_Bool = "allowReprojection"; + static const char * const k_pch_SteamVR_ForceReprojection_Bool = "forceReprojection"; + static const char * const k_pch_SteamVR_ForceFadeOnBadTracking_Bool = "forceFadeOnBadTracking"; + static const char * const k_pch_SteamVR_DefaultMirrorView_Int32 = "defaultMirrorView"; + static const char * const k_pch_SteamVR_ShowMirrorView_Bool = "showMirrorView"; + static const char * const k_pch_SteamVR_StartMonitorFromAppLaunch = "startMonitorFromAppLaunch"; + static const char * const k_pch_SteamVR_AutoLaunchSteamVROnButtonPress = "autoLaunchSteamVROnButtonPress"; + static const char * const k_pch_SteamVR_UseGenericGraphcisDevice_Bool = "useGenericGraphicsDevice"; + + + //----------------------------------------------------------------------------- + // lighthouse keys + + static const char * const k_pch_Lighthouse_Section = "driver_lighthouse"; + static const char * const k_pch_Lighthouse_DisableIMU_Bool = "disableimu"; + static const char * const k_pch_Lighthouse_UseDisambiguation_String = "usedisambiguation"; + static const char * const k_pch_Lighthouse_DisambiguationDebug_Int32 = "disambiguationdebug"; + + static const char * const k_pch_Lighthouse_PrimaryBasestation_Int32 = "primarybasestation"; + static const char * const k_pch_Lighthouse_LighthouseName_String = "lighthousename"; + static const char * const k_pch_Lighthouse_MaxIncidenceAngleDegrees_Float = "maxincidenceangledegrees"; + static const char * const k_pch_Lighthouse_UseLighthouseDirect_Bool = "uselighthousedirect"; + static const char * const k_pch_Lighthouse_DBHistory_Bool = "dbhistory"; + + //----------------------------------------------------------------------------- + // null keys + + static const char * const k_pch_Null_Section = "driver_null"; + static const char * const k_pch_Null_EnableNullDriver_Bool = "enable"; + static const char * const k_pch_Null_SerialNumber_String = "serialNumber"; + static const char * const k_pch_Null_ModelNumber_String = "modelNumber"; + static const char * const k_pch_Null_WindowX_Int32 = "windowX"; + static const char * const k_pch_Null_WindowY_Int32 = "windowY"; + static const char * const k_pch_Null_WindowWidth_Int32 = "windowWidth"; + static const char * const k_pch_Null_WindowHeight_Int32 = "windowHeight"; + static const char * const k_pch_Null_RenderWidth_Int32 = "renderWidth"; + static const char * const k_pch_Null_RenderHeight_Int32 = "renderHeight"; + static const char * const k_pch_Null_SecondsFromVsyncToPhotons_Float = "secondsFromVsyncToPhotons"; + static const char * const k_pch_Null_DisplayFrequency_Float = "displayFrequency"; + + //----------------------------------------------------------------------------- + // user interface keys + static const char * const k_pch_UserInterface_Section = "userinterface"; + static const char * const k_pch_UserInterface_StatusAlwaysOnTop_Bool = "StatusAlwaysOnTop"; + static const char * const k_pch_UserInterface_Screenshots_Bool = "screenshots"; + static const char * const k_pch_UserInterface_ScreenshotType_Int = "screenshotType"; + + //----------------------------------------------------------------------------- + // notification keys + static const char * const k_pch_Notifications_Section = "notifications"; + static const char * const k_pch_Notifications_DoNotDisturb_Bool = "DoNotDisturb"; + + //----------------------------------------------------------------------------- + // keyboard keys + static const char * const k_pch_Keyboard_Section = "keyboard"; + static const char * const k_pch_Keyboard_TutorialCompletions = "TutorialCompletions"; + static const char * const k_pch_Keyboard_ScaleX = "ScaleX"; + static const char * const k_pch_Keyboard_ScaleY = "ScaleY"; + static const char * const k_pch_Keyboard_OffsetLeftX = "OffsetLeftX"; + static const char * const k_pch_Keyboard_OffsetRightX = "OffsetRightX"; + static const char * const k_pch_Keyboard_OffsetY = "OffsetY"; + static const char * const k_pch_Keyboard_Smoothing = "Smoothing"; + + //----------------------------------------------------------------------------- + // perf keys + static const char * const k_pch_Perf_Section = "perfcheck"; + static const char * const k_pch_Perf_HeuristicActive_Bool = "heuristicActive"; + static const char * const k_pch_Perf_NotifyInHMD_Bool = "warnInHMD"; + static const char * const k_pch_Perf_NotifyOnlyOnce_Bool = "warnOnlyOnce"; + static const char * const k_pch_Perf_AllowTimingStore_Bool = "allowTimingStore"; + static const char * const k_pch_Perf_SaveTimingsOnExit_Bool = "saveTimingsOnExit"; + static const char * const k_pch_Perf_TestData_Float = "perfTestData"; + + //----------------------------------------------------------------------------- + // collision bounds keys + static const char * const k_pch_CollisionBounds_Section = "collisionBounds"; + static const char * const k_pch_CollisionBounds_Style_Int32 = "CollisionBoundsStyle"; + static const char * const k_pch_CollisionBounds_GroundPerimeterOn_Bool = "CollisionBoundsGroundPerimeterOn"; + static const char * const k_pch_CollisionBounds_CenterMarkerOn_Bool = "CollisionBoundsCenterMarkerOn"; + static const char * const k_pch_CollisionBounds_PlaySpaceOn_Bool = "CollisionBoundsPlaySpaceOn"; + static const char * const k_pch_CollisionBounds_FadeDistance_Float = "CollisionBoundsFadeDistance"; + static const char * const k_pch_CollisionBounds_ColorGammaR_Int32 = "CollisionBoundsColorGammaR"; + static const char * const k_pch_CollisionBounds_ColorGammaG_Int32 = "CollisionBoundsColorGammaG"; + static const char * const k_pch_CollisionBounds_ColorGammaB_Int32 = "CollisionBoundsColorGammaB"; + static const char * const k_pch_CollisionBounds_ColorGammaA_Int32 = "CollisionBoundsColorGammaA"; + + //----------------------------------------------------------------------------- + // camera keys + static const char * const k_pch_Camera_Section = "camera"; + static const char * const k_pch_Camera_EnableCamera_Bool = "enableCamera"; + static const char * const k_pch_Camera_EnableCameraInDashboard_Bool = "enableCameraInDashboard"; + static const char * const k_pch_Camera_EnableCameraForCollisionBounds_Bool = "enableCameraForCollisionBounds"; + static const char * const k_pch_Camera_EnableCameraForRoomView_Bool = "enableCameraForRoomView"; + static const char * const k_pch_Camera_BoundsColorGammaR_Int32 = "cameraBoundsColorGammaR"; + static const char * const k_pch_Camera_BoundsColorGammaG_Int32 = "cameraBoundsColorGammaG"; + static const char * const k_pch_Camera_BoundsColorGammaB_Int32 = "cameraBoundsColorGammaB"; + static const char * const k_pch_Camera_BoundsColorGammaA_Int32 = "cameraBoundsColorGammaA"; + + //----------------------------------------------------------------------------- + // audio keys + static const char * const k_pch_audio_Section = "audio"; + static const char * const k_pch_audio_OnPlaybackDevice_String = "onPlaybackDevice"; + static const char * const k_pch_audio_OnRecordDevice_String = "onRecordDevice"; + static const char * const k_pch_audio_OnPlaybackMirrorDevice_String = "onPlaybackMirrorDevice"; + static const char * const k_pch_audio_OffPlaybackDevice_String = "offPlaybackDevice"; + static const char * const k_pch_audio_OffRecordDevice_String = "offRecordDevice"; + static const char * const k_pch_audio_VIVEHDMIGain = "viveHDMIGain"; + + //----------------------------------------------------------------------------- + // model skin keys + static const char * const k_pch_modelskin_Section = "modelskins"; + +} // namespace vr + +// ivrchaperone.h +namespace vr +{ + +#if defined(__linux__) || defined(__APPLE__) + // The 32-bit version of gcc has the alignment requirement for uint64 and double set to + // 4 meaning that even with #pragma pack(8) these types will only be four-byte aligned. + // The 64-bit version of gcc has the alignment requirement for these types set to + // 8 meaning that unless we use #pragma pack(4) our structures will get bigger. + // The 64-bit structure packing has to match the 32-bit structure packing for each platform. + #pragma pack( push, 4 ) +#else + #pragma pack( push, 8 ) +#endif + +enum ChaperoneCalibrationState +{ + // OK! + ChaperoneCalibrationState_OK = 1, // Chaperone is fully calibrated and working correctly + + // Warnings + ChaperoneCalibrationState_Warning = 100, + ChaperoneCalibrationState_Warning_BaseStationMayHaveMoved = 101, // A base station thinks that it might have moved + ChaperoneCalibrationState_Warning_BaseStationRemoved = 102, // There are less base stations than when calibrated + ChaperoneCalibrationState_Warning_SeatedBoundsInvalid = 103, // Seated bounds haven't been calibrated for the current tracking center + + // Errors + ChaperoneCalibrationState_Error = 200, // The UniverseID is invalid + ChaperoneCalibrationState_Error_BaseStationUninitalized = 201, // Tracking center hasn't be calibrated for at least one of the base stations + ChaperoneCalibrationState_Error_BaseStationConflict = 202, // Tracking center is calibrated, but base stations disagree on the tracking space + ChaperoneCalibrationState_Error_PlayAreaInvalid = 203, // Play Area hasn't been calibrated for the current tracking center + ChaperoneCalibrationState_Error_CollisionBoundsInvalid = 204, // Collision Bounds haven't been calibrated for the current tracking center +}; + + +/** HIGH LEVEL TRACKING SPACE ASSUMPTIONS: +* 0,0,0 is the preferred standing area center. +* 0Y is the floor height. +* -Z is the preferred forward facing direction. */ +class IVRChaperone +{ +public: + + /** Get the current state of Chaperone calibration. This state can change at any time during a session due to physical base station changes. **/ + virtual ChaperoneCalibrationState GetCalibrationState() = 0; + + /** Returns the width and depth of the Play Area (formerly named Soft Bounds) in X and Z. + * Tracking space center (0,0,0) is the center of the Play Area. **/ + virtual bool GetPlayAreaSize( float *pSizeX, float *pSizeZ ) = 0; + + /** Returns the 4 corner positions of the Play Area (formerly named Soft Bounds). + * Corners are in counter-clockwise order. + * Standing center (0,0,0) is the center of the Play Area. + * It's a rectangle. + * 2 sides are parallel to the X axis and 2 sides are parallel to the Z axis. + * Height of every corner is 0Y (on the floor). **/ + virtual bool GetPlayAreaRect( HmdQuad_t *rect ) = 0; + + /** Reload Chaperone data from the .vrchap file on disk. */ + virtual void ReloadInfo( void ) = 0; + + /** Optionally give the chaperone system a hit about the color and brightness in the scene **/ + virtual void SetSceneColor( HmdColor_t color ) = 0; + + /** Get the current chaperone bounds draw color and brightness **/ + virtual void GetBoundsColor( HmdColor_t *pOutputColorArray, int nNumOutputColors, float flCollisionBoundsFadeDistance, HmdColor_t *pOutputCameraColor ) = 0; + + /** Determine whether the bounds are showing right now **/ + virtual bool AreBoundsVisible() = 0; + + /** Force the bounds to show, mostly for utilities **/ + virtual void ForceBoundsVisible( bool bForce ) = 0; +}; + +static const char * const IVRChaperone_Version = "IVRChaperone_003"; + +#pragma pack( pop ) + +} + +// ivrchaperonesetup.h +namespace vr +{ + +enum EChaperoneConfigFile +{ + EChaperoneConfigFile_Live = 1, // The live chaperone config, used by most applications and games + EChaperoneConfigFile_Temp = 2, // The temporary chaperone config, used to live-preview collision bounds in room setup +}; + +enum EChaperoneImportFlags +{ + EChaperoneImport_BoundsOnly = 0x0001, +}; + +/** Manages the working copy of the chaperone info. By default this will be the same as the +* live copy. Any changes made with this interface will stay in the working copy until +* CommitWorkingCopy() is called, at which point the working copy and the live copy will be +* the same again. */ +class IVRChaperoneSetup +{ +public: + + /** Saves the current working copy to disk */ + virtual bool CommitWorkingCopy( EChaperoneConfigFile configFile ) = 0; + + /** Reverts the working copy to match the live chaperone calibration. + * To modify existing data this MUST be do WHILE getting a non-error ChaperoneCalibrationStatus. + * Only after this should you do gets and sets on the existing data. */ + virtual void RevertWorkingCopy() = 0; + + /** Returns the width and depth of the Play Area (formerly named Soft Bounds) in X and Z from the working copy. + * Tracking space center (0,0,0) is the center of the Play Area. */ + virtual bool GetWorkingPlayAreaSize( float *pSizeX, float *pSizeZ ) = 0; + + /** Returns the 4 corner positions of the Play Area (formerly named Soft Bounds) from the working copy. + * Corners are in clockwise order. + * Tracking space center (0,0,0) is the center of the Play Area. + * It's a rectangle. + * 2 sides are parallel to the X axis and 2 sides are parallel to the Z axis. + * Height of every corner is 0Y (on the floor). **/ + virtual bool GetWorkingPlayAreaRect( HmdQuad_t *rect ) = 0; + + /** Returns the number of Quads if the buffer points to null. Otherwise it returns Quads + * into the buffer up to the max specified from the working copy. */ + virtual bool GetWorkingCollisionBoundsInfo( VR_OUT_ARRAY_COUNT(punQuadsCount) HmdQuad_t *pQuadsBuffer, uint32_t* punQuadsCount ) = 0; + + /** Returns the number of Quads if the buffer points to null. Otherwise it returns Quads + * into the buffer up to the max specified. */ + virtual bool GetLiveCollisionBoundsInfo( VR_OUT_ARRAY_COUNT(punQuadsCount) HmdQuad_t *pQuadsBuffer, uint32_t* punQuadsCount ) = 0; + + /** Returns the preferred seated position from the working copy. */ + virtual bool GetWorkingSeatedZeroPoseToRawTrackingPose( HmdMatrix34_t *pmatSeatedZeroPoseToRawTrackingPose ) = 0; + + /** Returns the standing origin from the working copy. */ + virtual bool GetWorkingStandingZeroPoseToRawTrackingPose( HmdMatrix34_t *pmatStandingZeroPoseToRawTrackingPose ) = 0; + + /** Sets the Play Area in the working copy. */ + virtual void SetWorkingPlayAreaSize( float sizeX, float sizeZ ) = 0; + + /** Sets the Collision Bounds in the working copy. */ + virtual void SetWorkingCollisionBoundsInfo( VR_ARRAY_COUNT(unQuadsCount) HmdQuad_t *pQuadsBuffer, uint32_t unQuadsCount ) = 0; + + /** Sets the preferred seated position in the working copy. */ + virtual void SetWorkingSeatedZeroPoseToRawTrackingPose( const HmdMatrix34_t *pMatSeatedZeroPoseToRawTrackingPose ) = 0; + + /** Sets the preferred standing position in the working copy. */ + virtual void SetWorkingStandingZeroPoseToRawTrackingPose( const HmdMatrix34_t *pMatStandingZeroPoseToRawTrackingPose ) = 0; + + /** Tear everything down and reload it from the file on disk */ + virtual void ReloadFromDisk( EChaperoneConfigFile configFile ) = 0; + + /** Returns the preferred seated position. */ + virtual bool GetLiveSeatedZeroPoseToRawTrackingPose( HmdMatrix34_t *pmatSeatedZeroPoseToRawTrackingPose ) = 0; + + virtual void SetWorkingCollisionBoundsTagsInfo( VR_ARRAY_COUNT(unTagCount) uint8_t *pTagsBuffer, uint32_t unTagCount ) = 0; + virtual bool GetLiveCollisionBoundsTagsInfo( VR_OUT_ARRAY_COUNT(punTagCount) uint8_t *pTagsBuffer, uint32_t *punTagCount ) = 0; + + virtual bool SetWorkingPhysicalBoundsInfo( VR_ARRAY_COUNT(unQuadsCount) HmdQuad_t *pQuadsBuffer, uint32_t unQuadsCount ) = 0; + virtual bool GetLivePhysicalBoundsInfo( VR_OUT_ARRAY_COUNT(punQuadsCount) HmdQuad_t *pQuadsBuffer, uint32_t* punQuadsCount ) = 0; + + virtual bool ExportLiveToBuffer( VR_OUT_STRING() char *pBuffer, uint32_t *pnBufferLength ) = 0; + virtual bool ImportFromBufferToWorking( const char *pBuffer, uint32_t nImportFlags ) = 0; +}; + +static const char * const IVRChaperoneSetup_Version = "IVRChaperoneSetup_005"; + + +} + +// ivrcompositor.h +namespace vr +{ + +#if defined(__linux__) || defined(__APPLE__) + // The 32-bit version of gcc has the alignment requirement for uint64 and double set to + // 4 meaning that even with #pragma pack(8) these types will only be four-byte aligned. + // The 64-bit version of gcc has the alignment requirement for these types set to + // 8 meaning that unless we use #pragma pack(4) our structures will get bigger. + // The 64-bit structure packing has to match the 32-bit structure packing for each platform. + #pragma pack( push, 4 ) +#else + #pragma pack( push, 8 ) +#endif + +/** Errors that can occur with the VR compositor */ +enum EVRCompositorError +{ + VRCompositorError_None = 0, + VRCompositorError_RequestFailed = 1, + VRCompositorError_IncompatibleVersion = 100, + VRCompositorError_DoNotHaveFocus = 101, + VRCompositorError_InvalidTexture = 102, + VRCompositorError_IsNotSceneApplication = 103, + VRCompositorError_TextureIsOnWrongDevice = 104, + VRCompositorError_TextureUsesUnsupportedFormat = 105, + VRCompositorError_SharedTexturesNotSupported = 106, + VRCompositorError_IndexOutOfRange = 107, +}; + +const uint32_t VRCompositor_ReprojectionReason_Cpu = 0x01; +const uint32_t VRCompositor_ReprojectionReason_Gpu = 0x02; + +/** Provides a single frame's timing information to the app */ +struct Compositor_FrameTiming +{ + uint32_t m_nSize; // Set to sizeof( Compositor_FrameTiming ) + uint32_t m_nFrameIndex; + uint32_t m_nNumFramePresents; // number of times this frame was presented + uint32_t m_nNumDroppedFrames; // number of additional times previous frame was scanned out + uint32_t m_nReprojectionFlags; + + /** Absolute time reference for comparing frames. This aligns with the vsync that running start is relative to. */ + double m_flSystemTimeInSeconds; + + /** These times may include work from other processes due to OS scheduling. + * The fewer packets of work these are broken up into, the less likely this will happen. + * GPU work can be broken up by calling Flush. This can sometimes be useful to get the GPU started + * processing that work earlier in the frame. */ + float m_flPreSubmitGpuMs; // time spent rendering the scene (gpu work submitted between WaitGetPoses and second Submit) + float m_flPostSubmitGpuMs; // additional time spent rendering by application (e.g. companion window) + float m_flTotalRenderGpuMs; // time between work submitted immediately after present (ideally vsync) until the end of compositor submitted work + float m_flCompositorRenderGpuMs; // time spend performing distortion correction, rendering chaperone, overlays, etc. + float m_flCompositorRenderCpuMs; // time spent on cpu submitting the above work for this frame + float m_flCompositorIdleCpuMs; // time spent waiting for running start (application could have used this much more time) + + /** Miscellaneous measured intervals. */ + float m_flClientFrameIntervalMs; // time between calls to WaitGetPoses + float m_flPresentCallCpuMs; // time blocked on call to present (usually 0.0, but can go long) + float m_flWaitForPresentCpuMs; // time spent spin-waiting for frame index to change (not near-zero indicates wait object failure) + float m_flSubmitFrameMs; // time spent in IVRCompositor::Submit (not near-zero indicates driver issue) + + /** The following are all relative to this frame's SystemTimeInSeconds */ + float m_flWaitGetPosesCalledMs; + float m_flNewPosesReadyMs; + float m_flNewFrameReadyMs; // second call to IVRCompositor::Submit + float m_flCompositorUpdateStartMs; + float m_flCompositorUpdateEndMs; + float m_flCompositorRenderStartMs; + + vr::TrackedDevicePose_t m_HmdPose; // pose used by app to render this frame +}; + +/** Cumulative stats for current application. These are not cleared until a new app connects, +* but they do stop accumulating once the associated app disconnects. */ +struct Compositor_CumulativeStats +{ + uint32_t m_nPid; // Process id associated with these stats (may no longer be running). + uint32_t m_nNumFramePresents; // total number of times we called present (includes reprojected frames) + uint32_t m_nNumDroppedFrames; // total number of times an old frame was re-scanned out (without reprojection) + uint32_t m_nNumReprojectedFrames; // total number of times a frame was scanned out a second time (with reprojection) + + /** Values recorded at startup before application has fully faded in the first time. */ + uint32_t m_nNumFramePresentsOnStartup; + uint32_t m_nNumDroppedFramesOnStartup; + uint32_t m_nNumReprojectedFramesOnStartup; + + /** Applications may explicitly fade to the compositor. This is usually to handle level transitions, and loading often causes + * system wide hitches. The following stats are collected during this period. Does not include values recorded during startup. */ + uint32_t m_nNumLoading; + uint32_t m_nNumFramePresentsLoading; + uint32_t m_nNumDroppedFramesLoading; + uint32_t m_nNumReprojectedFramesLoading; + + /** If we don't get a new frame from the app in less than 2.5 frames, then we assume the app has hung and start + * fading back to the compositor. The following stats are a result of this, and are a subset of those recorded above. + * Does not include values recorded during start up or loading. */ + uint32_t m_nNumTimedOut; + uint32_t m_nNumFramePresentsTimedOut; + uint32_t m_nNumDroppedFramesTimedOut; + uint32_t m_nNumReprojectedFramesTimedOut; +}; + +#pragma pack( pop ) + +/** Allows the application to interact with the compositor */ +class IVRCompositor +{ +public: + /** Sets tracking space returned by WaitGetPoses */ + virtual void SetTrackingSpace( ETrackingUniverseOrigin eOrigin ) = 0; + + /** Gets current tracking space returned by WaitGetPoses */ + virtual ETrackingUniverseOrigin GetTrackingSpace() = 0; + + /** Returns pose(s) to use to render scene (and optionally poses predicted two frames out for gameplay). */ + virtual EVRCompositorError WaitGetPoses( VR_ARRAY_COUNT(unRenderPoseArrayCount) TrackedDevicePose_t* pRenderPoseArray, uint32_t unRenderPoseArrayCount, + VR_ARRAY_COUNT(unGamePoseArrayCount) TrackedDevicePose_t* pGamePoseArray, uint32_t unGamePoseArrayCount ) = 0; + + /** Get the last set of poses returned by WaitGetPoses. */ + virtual EVRCompositorError GetLastPoses( VR_ARRAY_COUNT( unRenderPoseArrayCount ) TrackedDevicePose_t* pRenderPoseArray, uint32_t unRenderPoseArrayCount, + VR_ARRAY_COUNT( unGamePoseArrayCount ) TrackedDevicePose_t* pGamePoseArray, uint32_t unGamePoseArrayCount ) = 0; + + /** Interface for accessing last set of poses returned by WaitGetPoses one at a time. + * Returns VRCompositorError_IndexOutOfRange if unDeviceIndex not less than k_unMaxTrackedDeviceCount otherwise VRCompositorError_None. + * It is okay to pass NULL for either pose if you only want one of the values. */ + virtual EVRCompositorError GetLastPoseForTrackedDeviceIndex( TrackedDeviceIndex_t unDeviceIndex, TrackedDevicePose_t *pOutputPose, TrackedDevicePose_t *pOutputGamePose ) = 0; + + /** Updated scene texture to display. If pBounds is NULL the entire texture will be used. If called from an OpenGL app, consider adding a glFlush after + * Submitting both frames to signal the driver to start processing, otherwise it may wait until the command buffer fills up, causing the app to miss frames. + * + * OpenGL dirty state: + * glBindTexture + */ + virtual EVRCompositorError Submit( EVREye eEye, const Texture_t *pTexture, const VRTextureBounds_t* pBounds = 0, EVRSubmitFlags nSubmitFlags = Submit_Default ) = 0; + + /** Clears the frame that was sent with the last call to Submit. This will cause the + * compositor to show the grid until Submit is called again. */ + virtual void ClearLastSubmittedFrame() = 0; + + /** Call immediately after presenting your app's window (i.e. companion window) to unblock the compositor. + * This is an optional call, which only needs to be used if you can't instead call WaitGetPoses immediately after Present. + * For example, if your engine's render and game loop are not on separate threads, or blocking the render thread until 3ms before the next vsync would + * introduce a deadlock of some sort. This function tells the compositor that you have finished all rendering after having Submitted buffers for both + * eyes, and it is free to start its rendering work. This should only be called from the same thread you are rendering on. */ + virtual void PostPresentHandoff() = 0; + + /** Returns true if timing data is filled it. Sets oldest timing info if nFramesAgo is larger than the stored history. + * Be sure to set timing.size = sizeof(Compositor_FrameTiming) on struct passed in before calling this function. */ + virtual bool GetFrameTiming( Compositor_FrameTiming *pTiming, uint32_t unFramesAgo = 0 ) = 0; + + /** Returns the time in seconds left in the current (as identified by FrameTiming's frameIndex) frame. + * Due to "running start", this value may roll over to the next frame before ever reaching 0.0. */ + virtual float GetFrameTimeRemaining() = 0; + + /** Fills out stats accumulated for the last connected application. Pass in sizeof( Compositor_CumulativeStats ) as second parameter. */ + virtual void GetCumulativeStats( Compositor_CumulativeStats *pStats, uint32_t nStatsSizeInBytes ) = 0; + + /** Fades the view on the HMD to the specified color. The fade will take fSeconds, and the color values are between + * 0.0 and 1.0. This color is faded on top of the scene based on the alpha parameter. Removing the fade color instantly + * would be FadeToColor( 0.0, 0.0, 0.0, 0.0, 0.0 ). Values are in un-premultiplied alpha space. */ + virtual void FadeToColor( float fSeconds, float fRed, float fGreen, float fBlue, float fAlpha, bool bBackground = false ) = 0; + + /** Fading the Grid in or out in fSeconds */ + virtual void FadeGrid( float fSeconds, bool bFadeIn ) = 0; + + /** Override the skybox used in the compositor (e.g. for during level loads when the app can't feed scene images fast enough) + * Order is Front, Back, Left, Right, Top, Bottom. If only a single texture is passed, it is assumed in lat-long format. + * If two are passed, it is assumed a lat-long stereo pair. */ + virtual EVRCompositorError SetSkyboxOverride( VR_ARRAY_COUNT( unTextureCount ) const Texture_t *pTextures, uint32_t unTextureCount ) = 0; + + /** Resets compositor skybox back to defaults. */ + virtual void ClearSkyboxOverride() = 0; + + /** Brings the compositor window to the front. This is useful for covering any other window that may be on the HMD + * and is obscuring the compositor window. */ + virtual void CompositorBringToFront() = 0; + + /** Pushes the compositor window to the back. This is useful for allowing other applications to draw directly to the HMD. */ + virtual void CompositorGoToBack() = 0; + + /** Tells the compositor process to clean up and exit. You do not need to call this function at shutdown. Under normal + * circumstances the compositor will manage its own life cycle based on what applications are running. */ + virtual void CompositorQuit() = 0; + + /** Return whether the compositor is fullscreen */ + virtual bool IsFullscreen() = 0; + + /** Returns the process ID of the process that is currently rendering the scene */ + virtual uint32_t GetCurrentSceneFocusProcess() = 0; + + /** Returns the process ID of the process that rendered the last frame (or 0 if the compositor itself rendered the frame.) + * Returns 0 when fading out from an app and the app's process Id when fading into an app. */ + virtual uint32_t GetLastFrameRenderer() = 0; + + /** Returns true if the current process has the scene focus */ + virtual bool CanRenderScene() = 0; + + /** Creates a window on the primary monitor to display what is being shown in the headset. */ + virtual void ShowMirrorWindow() = 0; + + /** Closes the mirror window. */ + virtual void HideMirrorWindow() = 0; + + /** Returns true if the mirror window is shown. */ + virtual bool IsMirrorWindowVisible() = 0; + + /** Writes all images that the compositor knows about (including overlays) to a 'screenshots' folder in the SteamVR runtime root. */ + virtual void CompositorDumpImages() = 0; + + /** Let an app know it should be rendering with low resources. */ + virtual bool ShouldAppRenderWithLowResources() = 0; + + /** Override interleaved reprojection logic to force on. */ + virtual void ForceInterleavedReprojectionOn( bool bOverride ) = 0; + + /** Force reconnecting to the compositor process. */ + virtual void ForceReconnectProcess() = 0; + + /** Temporarily suspends rendering (useful for finer control over scene transitions). */ + virtual void SuspendRendering( bool bSuspend ) = 0; + + /** Opens a shared D3D11 texture with the undistorted composited image for each eye. */ + virtual vr::EVRCompositorError GetMirrorTextureD3D11( vr::EVREye eEye, void *pD3D11DeviceOrResource, void **ppD3D11ShaderResourceView ) = 0; + + /** Access to mirror textures from OpenGL. */ + virtual vr::EVRCompositorError GetMirrorTextureGL( vr::EVREye eEye, vr::glUInt_t *pglTextureId, vr::glSharedTextureHandle_t *pglSharedTextureHandle ) = 0; + virtual bool ReleaseSharedGLTexture( vr::glUInt_t glTextureId, vr::glSharedTextureHandle_t glSharedTextureHandle ) = 0; + virtual void LockGLSharedTextureForAccess( vr::glSharedTextureHandle_t glSharedTextureHandle ) = 0; + virtual void UnlockGLSharedTextureForAccess( vr::glSharedTextureHandle_t glSharedTextureHandle ) = 0; +}; + +static const char * const IVRCompositor_Version = "IVRCompositor_016"; + +} // namespace vr + + + +// ivrnotifications.h +namespace vr +{ + +#if defined(__linux__) || defined(__APPLE__) + // The 32-bit version of gcc has the alignment requirement for uint64 and double set to + // 4 meaning that even with #pragma pack(8) these types will only be four-byte aligned. + // The 64-bit version of gcc has the alignment requirement for these types set to + // 8 meaning that unless we use #pragma pack(4) our structures will get bigger. + // The 64-bit structure packing has to match the 32-bit structure packing for each platform. + #pragma pack( push, 4 ) +#else + #pragma pack( push, 8 ) +#endif + +// Used for passing graphic data +struct NotificationBitmap_t +{ + NotificationBitmap_t() + : m_pImageData( nullptr ) + , m_nWidth( 0 ) + , m_nHeight( 0 ) + , m_nBytesPerPixel( 0 ) + { + }; + + void *m_pImageData; + int32_t m_nWidth; + int32_t m_nHeight; + int32_t m_nBytesPerPixel; +}; + + +/** Be aware that the notification type is used as 'priority' to pick the next notification */ +enum EVRNotificationType +{ + /** Transient notifications are automatically hidden after a period of time set by the user. + * They are used for things like information and chat messages that do not require user interaction. */ + EVRNotificationType_Transient = 0, + + /** Persistent notifications are shown to the user until they are hidden by calling RemoveNotification(). + * They are used for things like phone calls and alarms that require user interaction. */ + EVRNotificationType_Persistent = 1, + + /** System notifications are shown no matter what. It is expected, that the ulUserValue is used as ID. + * If there is already a system notification in the queue with that ID it is not accepted into the queue + * to prevent spamming with system notification */ + EVRNotificationType_Transient_SystemWithUserValue = 2, +}; + +enum EVRNotificationStyle +{ + /** Creates a notification with minimal external styling. */ + EVRNotificationStyle_None = 0, + + /** Used for notifications about overlay-level status. In Steam this is used for events like downloads completing. */ + EVRNotificationStyle_Application = 100, + + /** Used for notifications about contacts that are unknown or not available. In Steam this is used for friend invitations and offline friends. */ + EVRNotificationStyle_Contact_Disabled = 200, + + /** Used for notifications about contacts that are available but inactive. In Steam this is used for friends that are online but not playing a game. */ + EVRNotificationStyle_Contact_Enabled = 201, + + /** Used for notifications about contacts that are available and active. In Steam this is used for friends that are online and currently running a game. */ + EVRNotificationStyle_Contact_Active = 202, +}; + +static const uint32_t k_unNotificationTextMaxSize = 256; + +typedef uint32_t VRNotificationId; + + + +#pragma pack( pop ) + +/** Allows notification sources to interact with the VR system + This current interface is not yet implemented. Do not use yet. */ +class IVRNotifications +{ +public: + /** Create a notification and enqueue it to be shown to the user. + * An overlay handle is required to create a notification, as otherwise it would be impossible for a user to act on it. + * To create a two-line notification, use a line break ('\n') to split the text into two lines. + * The pImage argument may be NULL, in which case the specified overlay's icon will be used instead. */ + virtual EVRNotificationError CreateNotification( VROverlayHandle_t ulOverlayHandle, uint64_t ulUserValue, EVRNotificationType type, const char *pchText, EVRNotificationStyle style, const NotificationBitmap_t *pImage, /* out */ VRNotificationId *pNotificationId ) = 0; + + /** Destroy a notification, hiding it first if it currently shown to the user. */ + virtual EVRNotificationError RemoveNotification( VRNotificationId notificationId ) = 0; + +}; + +static const char * const IVRNotifications_Version = "IVRNotifications_002"; + +} // namespace vr + + + +// ivroverlay.h +namespace vr +{ + + /** The maximum length of an overlay key in bytes, counting the terminating null character. */ + static const uint32_t k_unVROverlayMaxKeyLength = 128; + + /** The maximum length of an overlay name in bytes, counting the terminating null character. */ + static const uint32_t k_unVROverlayMaxNameLength = 128; + + /** The maximum number of overlays that can exist in the system at one time. */ + static const uint32_t k_unMaxOverlayCount = 64; + + /** Types of input supported by VR Overlays */ + enum VROverlayInputMethod + { + VROverlayInputMethod_None = 0, // No input events will be generated automatically for this overlay + VROverlayInputMethod_Mouse = 1, // Tracked controllers will get mouse events automatically + }; + + /** Allows the caller to figure out which overlay transform getter to call. */ + enum VROverlayTransformType + { + VROverlayTransform_Absolute = 0, + VROverlayTransform_TrackedDeviceRelative = 1, + VROverlayTransform_SystemOverlay = 2, + VROverlayTransform_TrackedComponent = 3, + }; + + /** Overlay control settings */ + enum VROverlayFlags + { + VROverlayFlags_None = 0, + + // The following only take effect when rendered using the high quality render path (see SetHighQualityOverlay). + VROverlayFlags_Curved = 1, + VROverlayFlags_RGSS4X = 2, + + // Set this flag on a dashboard overlay to prevent a tab from showing up for that overlay + VROverlayFlags_NoDashboardTab = 3, + + // Set this flag on a dashboard that is able to deal with gamepad focus events + VROverlayFlags_AcceptsGamepadEvents = 4, + + // Indicates that the overlay should dim/brighten to show gamepad focus + VROverlayFlags_ShowGamepadFocus = 5, + + // When in VROverlayInputMethod_Mouse you can optionally enable sending VRScroll_t + VROverlayFlags_SendVRScrollEvents = 6, + VROverlayFlags_SendVRTouchpadEvents = 7, + + // If set this will render a vertical scroll wheel on the primary controller, + // only needed if not using VROverlayFlags_SendVRScrollEvents but you still want to represent a scroll wheel + VROverlayFlags_ShowTouchPadScrollWheel = 8, + + // If this is set ownership and render access to the overlay are transferred + // to the new scene process on a call to IVRApplications::LaunchInternalProcess + VROverlayFlags_TransferOwnershipToInternalProcess = 9, + + // If set, renders 50% of the texture in each eye, side by side + VROverlayFlags_SideBySide_Parallel = 10, // Texture is left/right + VROverlayFlags_SideBySide_Crossed = 11, // Texture is crossed and right/left + + VROverlayFlags_Panorama = 12, // Texture is a panorama + VROverlayFlags_StereoPanorama = 13, // Texture is a stereo panorama + + // If this is set on an overlay owned by the scene application that overlay + // will be sorted with the "Other" overlays on top of all other scene overlays + VROverlayFlags_SortWithNonSceneOverlays = 14, + }; + + struct VROverlayIntersectionParams_t + { + HmdVector3_t vSource; + HmdVector3_t vDirection; + ETrackingUniverseOrigin eOrigin; + }; + + struct VROverlayIntersectionResults_t + { + HmdVector3_t vPoint; + HmdVector3_t vNormal; + HmdVector2_t vUVs; + float fDistance; + }; + + // Input modes for the Big Picture gamepad text entry + enum EGamepadTextInputMode + { + k_EGamepadTextInputModeNormal = 0, + k_EGamepadTextInputModePassword = 1, + k_EGamepadTextInputModeSubmit = 2, + }; + + // Controls number of allowed lines for the Big Picture gamepad text entry + enum EGamepadTextInputLineMode + { + k_EGamepadTextInputLineModeSingleLine = 0, + k_EGamepadTextInputLineModeMultipleLines = 1 + }; + + /** Directions for changing focus between overlays with the gamepad */ + enum EOverlayDirection + { + OverlayDirection_Up = 0, + OverlayDirection_Down = 1, + OverlayDirection_Left = 2, + OverlayDirection_Right = 3, + + OverlayDirection_Count = 4, + }; + + class IVROverlay + { + public: + + // --------------------------------------------- + // Overlay management methods + // --------------------------------------------- + + /** Finds an existing overlay with the specified key. */ + virtual EVROverlayError FindOverlay( const char *pchOverlayKey, VROverlayHandle_t * pOverlayHandle ) = 0; + + /** Creates a new named overlay. All overlays start hidden and with default settings. */ + virtual EVROverlayError CreateOverlay( const char *pchOverlayKey, const char *pchOverlayFriendlyName, VROverlayHandle_t * pOverlayHandle ) = 0; + + /** Destroys the specified overlay. When an application calls VR_Shutdown all overlays created by that app are + * automatically destroyed. */ + virtual EVROverlayError DestroyOverlay( VROverlayHandle_t ulOverlayHandle ) = 0; + + /** Specify which overlay to use the high quality render path. This overlay will be composited in during the distortion pass which + * results in it drawing on top of everything else, but also at a higher quality as it samples the source texture directly rather than + * rasterizing into each eye's render texture first. Because if this, only one of these is supported at any given time. It is most useful + * for overlays that are expected to take up most of the user's view (e.g. streaming video). + * This mode does not support mouse input to your overlay. */ + virtual EVROverlayError SetHighQualityOverlay( VROverlayHandle_t ulOverlayHandle ) = 0; + + /** Returns the overlay handle of the current overlay being rendered using the single high quality overlay render path. + * Otherwise it will return k_ulOverlayHandleInvalid. */ + virtual vr::VROverlayHandle_t GetHighQualityOverlay() = 0; + + /** Fills the provided buffer with the string key of the overlay. Returns the size of buffer required to store the key, including + * the terminating null character. k_unVROverlayMaxKeyLength will be enough bytes to fit the string. */ + virtual uint32_t GetOverlayKey( VROverlayHandle_t ulOverlayHandle, VR_OUT_STRING() char *pchValue, uint32_t unBufferSize, EVROverlayError *pError = 0L ) = 0; + + /** Fills the provided buffer with the friendly name of the overlay. Returns the size of buffer required to store the key, including + * the terminating null character. k_unVROverlayMaxNameLength will be enough bytes to fit the string. */ + virtual uint32_t GetOverlayName( VROverlayHandle_t ulOverlayHandle, VR_OUT_STRING() char *pchValue, uint32_t unBufferSize, EVROverlayError *pError = 0L ) = 0; + + /** Gets the raw image data from an overlay. Overlay image data is always returned as RGBA data, 4 bytes per pixel. If the buffer is not large enough, width and height + * will be set and VROverlayError_ArrayTooSmall is returned. */ + virtual EVROverlayError GetOverlayImageData( VROverlayHandle_t ulOverlayHandle, void *pvBuffer, uint32_t unBufferSize, uint32_t *punWidth, uint32_t *punHeight ) = 0; + + /** returns a string that corresponds with the specified overlay error. The string will be the name + * of the error enum value for all valid error codes */ + virtual const char *GetOverlayErrorNameFromEnum( EVROverlayError error ) = 0; + + + // --------------------------------------------- + // Overlay rendering methods + // --------------------------------------------- + + /** Sets the pid that is allowed to render to this overlay (the creator pid is always allow to render), + * by default this is the pid of the process that made the overlay */ + virtual EVROverlayError SetOverlayRenderingPid( VROverlayHandle_t ulOverlayHandle, uint32_t unPID ) = 0; + + /** Gets the pid that is allowed to render to this overlay */ + virtual uint32_t GetOverlayRenderingPid( VROverlayHandle_t ulOverlayHandle ) = 0; + + /** Specify flag setting for a given overlay */ + virtual EVROverlayError SetOverlayFlag( VROverlayHandle_t ulOverlayHandle, VROverlayFlags eOverlayFlag, bool bEnabled ) = 0; + + /** Sets flag setting for a given overlay */ + virtual EVROverlayError GetOverlayFlag( VROverlayHandle_t ulOverlayHandle, VROverlayFlags eOverlayFlag, bool *pbEnabled ) = 0; + + /** Sets the color tint of the overlay quad. Use 0.0 to 1.0 per channel. */ + virtual EVROverlayError SetOverlayColor( VROverlayHandle_t ulOverlayHandle, float fRed, float fGreen, float fBlue ) = 0; + + /** Gets the color tint of the overlay quad. */ + virtual EVROverlayError GetOverlayColor( VROverlayHandle_t ulOverlayHandle, float *pfRed, float *pfGreen, float *pfBlue ) = 0; + + /** Sets the alpha of the overlay quad. Use 1.0 for 100 percent opacity to 0.0 for 0 percent opacity. */ + virtual EVROverlayError SetOverlayAlpha( VROverlayHandle_t ulOverlayHandle, float fAlpha ) = 0; + + /** Gets the alpha of the overlay quad. By default overlays are rendering at 100 percent alpha (1.0). */ + virtual EVROverlayError GetOverlayAlpha( VROverlayHandle_t ulOverlayHandle, float *pfAlpha ) = 0; + + /** Sets the aspect ratio of the texels in the overlay. 1.0 means the texels are square. 2.0 means the texels + * are twice as wide as they are tall. Defaults to 1.0. */ + virtual EVROverlayError SetOverlayTexelAspect( VROverlayHandle_t ulOverlayHandle, float fTexelAspect ) = 0; + + /** Gets the aspect ratio of the texels in the overlay. Defaults to 1.0 */ + virtual EVROverlayError GetOverlayTexelAspect( VROverlayHandle_t ulOverlayHandle, float *pfTexelAspect ) = 0; + + /** Sets the rendering sort order for the overlay. Overlays are rendered this order: + * Overlays owned by the scene application + * Overlays owned by some other application + * + * Within a category overlays are rendered lowest sort order to highest sort order. Overlays with the same + * sort order are rendered back to front base on distance from the HMD. + * + * Sort order defaults to 0. */ + virtual EVROverlayError SetOverlaySortOrder( VROverlayHandle_t ulOverlayHandle, uint32_t unSortOrder ) = 0; + + /** Gets the sort order of the overlay. See SetOverlaySortOrder for how this works. */ + virtual EVROverlayError GetOverlaySortOrder( VROverlayHandle_t ulOverlayHandle, uint32_t *punSortOrder ) = 0; + + /** Sets the width of the overlay quad in meters. By default overlays are rendered on a quad that is 1 meter across */ + virtual EVROverlayError SetOverlayWidthInMeters( VROverlayHandle_t ulOverlayHandle, float fWidthInMeters ) = 0; + + /** Returns the width of the overlay quad in meters. By default overlays are rendered on a quad that is 1 meter across */ + virtual EVROverlayError GetOverlayWidthInMeters( VROverlayHandle_t ulOverlayHandle, float *pfWidthInMeters ) = 0; + + /** For high-quality curved overlays only, sets the distance range in meters from the overlay used to automatically curve + * the surface around the viewer. Min is distance is when the surface will be most curved. Max is when least curved. */ + virtual EVROverlayError SetOverlayAutoCurveDistanceRangeInMeters( VROverlayHandle_t ulOverlayHandle, float fMinDistanceInMeters, float fMaxDistanceInMeters ) = 0; + + /** For high-quality curved overlays only, gets the distance range in meters from the overlay used to automatically curve + * the surface around the viewer. Min is distance is when the surface will be most curved. Max is when least curved. */ + virtual EVROverlayError GetOverlayAutoCurveDistanceRangeInMeters( VROverlayHandle_t ulOverlayHandle, float *pfMinDistanceInMeters, float *pfMaxDistanceInMeters ) = 0; + + /** Sets the colorspace the overlay texture's data is in. Defaults to 'auto'. + * If the texture needs to be resolved, you should call SetOverlayTexture with the appropriate colorspace instead. */ + virtual EVROverlayError SetOverlayTextureColorSpace( VROverlayHandle_t ulOverlayHandle, EColorSpace eTextureColorSpace ) = 0; + + /** Gets the overlay's current colorspace setting. */ + virtual EVROverlayError GetOverlayTextureColorSpace( VROverlayHandle_t ulOverlayHandle, EColorSpace *peTextureColorSpace ) = 0; + + /** Sets the part of the texture to use for the overlay. UV Min is the upper left corner and UV Max is the lower right corner. */ + virtual EVROverlayError SetOverlayTextureBounds( VROverlayHandle_t ulOverlayHandle, const VRTextureBounds_t *pOverlayTextureBounds ) = 0; + + /** Gets the part of the texture to use for the overlay. UV Min is the upper left corner and UV Max is the lower right corner. */ + virtual EVROverlayError GetOverlayTextureBounds( VROverlayHandle_t ulOverlayHandle, VRTextureBounds_t *pOverlayTextureBounds ) = 0; + + /** Returns the transform type of this overlay. */ + virtual EVROverlayError GetOverlayTransformType( VROverlayHandle_t ulOverlayHandle, VROverlayTransformType *peTransformType ) = 0; + + /** Sets the transform to absolute tracking origin. */ + virtual EVROverlayError SetOverlayTransformAbsolute( VROverlayHandle_t ulOverlayHandle, ETrackingUniverseOrigin eTrackingOrigin, const HmdMatrix34_t *pmatTrackingOriginToOverlayTransform ) = 0; + + /** Gets the transform if it is absolute. Returns an error if the transform is some other type. */ + virtual EVROverlayError GetOverlayTransformAbsolute( VROverlayHandle_t ulOverlayHandle, ETrackingUniverseOrigin *peTrackingOrigin, HmdMatrix34_t *pmatTrackingOriginToOverlayTransform ) = 0; + + /** Sets the transform to relative to the transform of the specified tracked device. */ + virtual EVROverlayError SetOverlayTransformTrackedDeviceRelative( VROverlayHandle_t ulOverlayHandle, TrackedDeviceIndex_t unTrackedDevice, const HmdMatrix34_t *pmatTrackedDeviceToOverlayTransform ) = 0; + + /** Gets the transform if it is relative to a tracked device. Returns an error if the transform is some other type. */ + virtual EVROverlayError GetOverlayTransformTrackedDeviceRelative( VROverlayHandle_t ulOverlayHandle, TrackedDeviceIndex_t *punTrackedDevice, HmdMatrix34_t *pmatTrackedDeviceToOverlayTransform ) = 0; + + /** Sets the transform to draw the overlay on a rendermodel component mesh instead of a quad. This will only draw when the system is + * drawing the device. Overlays with this transform type cannot receive mouse events. */ + virtual EVROverlayError SetOverlayTransformTrackedDeviceComponent( VROverlayHandle_t ulOverlayHandle, TrackedDeviceIndex_t unDeviceIndex, const char *pchComponentName ) = 0; + + /** Gets the transform information when the overlay is rendering on a component. */ + virtual EVROverlayError GetOverlayTransformTrackedDeviceComponent( VROverlayHandle_t ulOverlayHandle, TrackedDeviceIndex_t *punDeviceIndex, char *pchComponentName, uint32_t unComponentNameSize ) = 0; + + /** Shows the VR overlay. For dashboard overlays, only the Dashboard Manager is allowed to call this. */ + virtual EVROverlayError ShowOverlay( VROverlayHandle_t ulOverlayHandle ) = 0; + + /** Hides the VR overlay. For dashboard overlays, only the Dashboard Manager is allowed to call this. */ + virtual EVROverlayError HideOverlay( VROverlayHandle_t ulOverlayHandle ) = 0; + + /** Returns true if the overlay is visible. */ + virtual bool IsOverlayVisible( VROverlayHandle_t ulOverlayHandle ) = 0; + + /** Get the transform in 3d space associated with a specific 2d point in the overlay's coordinate space (where 0,0 is the lower left). -Z points out of the overlay */ + virtual EVROverlayError GetTransformForOverlayCoordinates( VROverlayHandle_t ulOverlayHandle, ETrackingUniverseOrigin eTrackingOrigin, HmdVector2_t coordinatesInOverlay, HmdMatrix34_t *pmatTransform ) = 0; + + // --------------------------------------------- + // Overlay input methods + // --------------------------------------------- + + /** Returns true and fills the event with the next event on the overlay's event queue, if there is one. + * If there are no events this method returns false. uncbVREvent should be the size in bytes of the VREvent_t struct */ + virtual bool PollNextOverlayEvent( VROverlayHandle_t ulOverlayHandle, VREvent_t *pEvent, uint32_t uncbVREvent ) = 0; + + /** Returns the current input settings for the specified overlay. */ + virtual EVROverlayError GetOverlayInputMethod( VROverlayHandle_t ulOverlayHandle, VROverlayInputMethod *peInputMethod ) = 0; + + /** Sets the input settings for the specified overlay. */ + virtual EVROverlayError SetOverlayInputMethod( VROverlayHandle_t ulOverlayHandle, VROverlayInputMethod eInputMethod ) = 0; + + /** Gets the mouse scaling factor that is used for mouse events. The actual texture may be a different size, but this is + * typically the size of the underlying UI in pixels. */ + virtual EVROverlayError GetOverlayMouseScale( VROverlayHandle_t ulOverlayHandle, HmdVector2_t *pvecMouseScale ) = 0; + + /** Sets the mouse scaling factor that is used for mouse events. The actual texture may be a different size, but this is + * typically the size of the underlying UI in pixels (not in world space). */ + virtual EVROverlayError SetOverlayMouseScale( VROverlayHandle_t ulOverlayHandle, const HmdVector2_t *pvecMouseScale ) = 0; + + /** Computes the overlay-space pixel coordinates of where the ray intersects the overlay with the + * specified settings. Returns false if there is no intersection. */ + virtual bool ComputeOverlayIntersection( VROverlayHandle_t ulOverlayHandle, const VROverlayIntersectionParams_t *pParams, VROverlayIntersectionResults_t *pResults ) = 0; + + /** Processes mouse input from the specified controller as though it were a mouse pointed at a compositor overlay with the + * specified settings. The controller is treated like a laser pointer on the -z axis. The point where the laser pointer would + * intersect with the overlay is the mouse position, the trigger is left mouse, and the track pad is right mouse. + * + * Return true if the controller is pointed at the overlay and an event was generated. */ + virtual bool HandleControllerOverlayInteractionAsMouse( VROverlayHandle_t ulOverlayHandle, TrackedDeviceIndex_t unControllerDeviceIndex ) = 0; + + /** Returns true if the specified overlay is the hover target. An overlay is the hover target when it is the last overlay "moused over" + * by the virtual mouse pointer */ + virtual bool IsHoverTargetOverlay( VROverlayHandle_t ulOverlayHandle ) = 0; + + /** Returns the current Gamepad focus overlay */ + virtual vr::VROverlayHandle_t GetGamepadFocusOverlay() = 0; + + /** Sets the current Gamepad focus overlay */ + virtual EVROverlayError SetGamepadFocusOverlay( VROverlayHandle_t ulNewFocusOverlay ) = 0; + + /** Sets an overlay's neighbor. This will also set the neighbor of the "to" overlay + * to point back to the "from" overlay. If an overlay's neighbor is set to invalid both + * ends will be cleared */ + virtual EVROverlayError SetOverlayNeighbor( EOverlayDirection eDirection, VROverlayHandle_t ulFrom, VROverlayHandle_t ulTo ) = 0; + + /** Changes the Gamepad focus from one overlay to one of its neighbors. Returns VROverlayError_NoNeighbor if there is no + * neighbor in that direction */ + virtual EVROverlayError MoveGamepadFocusToNeighbor( EOverlayDirection eDirection, VROverlayHandle_t ulFrom ) = 0; + + // --------------------------------------------- + // Overlay texture methods + // --------------------------------------------- + + /** Texture to draw for the overlay. This function can only be called by the overlay's creator or renderer process (see SetOverlayRenderingPid) . + * + * OpenGL dirty state: + * glBindTexture + */ + virtual EVROverlayError SetOverlayTexture( VROverlayHandle_t ulOverlayHandle, const Texture_t *pTexture ) = 0; + + /** Use this to tell the overlay system to release the texture set for this overlay. */ + virtual EVROverlayError ClearOverlayTexture( VROverlayHandle_t ulOverlayHandle ) = 0; + + /** Separate interface for providing the data as a stream of bytes, but there is an upper bound on data + * that can be sent. This function can only be called by the overlay's renderer process. */ + virtual EVROverlayError SetOverlayRaw( VROverlayHandle_t ulOverlayHandle, void *pvBuffer, uint32_t unWidth, uint32_t unHeight, uint32_t unDepth ) = 0; + + /** Separate interface for providing the image through a filename: can be png or jpg, and should not be bigger than 1920x1080. + * This function can only be called by the overlay's renderer process */ + virtual EVROverlayError SetOverlayFromFile( VROverlayHandle_t ulOverlayHandle, const char *pchFilePath ) = 0; + + /** Get the native texture handle/device for an overlay you have created. + * On windows this handle will be a ID3D11ShaderResourceView with a ID3D11Texture2D bound. + * + * The texture will always be sized to match the backing texture you supplied in SetOverlayTexture above. + * + * You MUST call ReleaseNativeOverlayHandle() with pNativeTextureHandle once you are done with this texture. + * + * pNativeTextureHandle is an OUTPUT, it will be a pointer to a ID3D11ShaderResourceView *. + * pNativeTextureRef is an INPUT and should be a ID3D11Resource *. The device used by pNativeTextureRef will be used to bind pNativeTextureHandle. + */ + virtual EVROverlayError GetOverlayTexture( VROverlayHandle_t ulOverlayHandle, void **pNativeTextureHandle, void *pNativeTextureRef, uint32_t *pWidth, uint32_t *pHeight, uint32_t *pNativeFormat, EGraphicsAPIConvention *pAPI, EColorSpace *pColorSpace ) = 0; + + /** Release the pNativeTextureHandle provided from the GetOverlayTexture call, this allows the system to free the underlying GPU resources for this object, + * so only do it once you stop rendering this texture. + */ + virtual EVROverlayError ReleaseNativeOverlayHandle( VROverlayHandle_t ulOverlayHandle, void *pNativeTextureHandle ) = 0; + + /** Get the size of the overlay texture */ + virtual EVROverlayError GetOverlayTextureSize( VROverlayHandle_t ulOverlayHandle, uint32_t *pWidth, uint32_t *pHeight ) = 0; + + // ---------------------------------------------- + // Dashboard Overlay Methods + // ---------------------------------------------- + + /** Creates a dashboard overlay and returns its handle */ + virtual EVROverlayError CreateDashboardOverlay( const char *pchOverlayKey, const char *pchOverlayFriendlyName, VROverlayHandle_t * pMainHandle, VROverlayHandle_t *pThumbnailHandle ) = 0; + + /** Returns true if the dashboard is visible */ + virtual bool IsDashboardVisible() = 0; + + /** returns true if the dashboard is visible and the specified overlay is the active system Overlay */ + virtual bool IsActiveDashboardOverlay( VROverlayHandle_t ulOverlayHandle ) = 0; + + /** Sets the dashboard overlay to only appear when the specified process ID has scene focus */ + virtual EVROverlayError SetDashboardOverlaySceneProcess( VROverlayHandle_t ulOverlayHandle, uint32_t unProcessId ) = 0; + + /** Gets the process ID that this dashboard overlay requires to have scene focus */ + virtual EVROverlayError GetDashboardOverlaySceneProcess( VROverlayHandle_t ulOverlayHandle, uint32_t *punProcessId ) = 0; + + /** Shows the dashboard. */ + virtual void ShowDashboard( const char *pchOverlayToShow ) = 0; + + /** Returns the tracked device that has the laser pointer in the dashboard */ + virtual vr::TrackedDeviceIndex_t GetPrimaryDashboardDevice() = 0; + + // --------------------------------------------- + // Keyboard methods + // --------------------------------------------- + + /** Show the virtual keyboard to accept input **/ + virtual EVROverlayError ShowKeyboard( EGamepadTextInputMode eInputMode, EGamepadTextInputLineMode eLineInputMode, const char *pchDescription, uint32_t unCharMax, const char *pchExistingText, bool bUseMinimalMode, uint64_t uUserValue ) = 0; + + virtual EVROverlayError ShowKeyboardForOverlay( VROverlayHandle_t ulOverlayHandle, EGamepadTextInputMode eInputMode, EGamepadTextInputLineMode eLineInputMode, const char *pchDescription, uint32_t unCharMax, const char *pchExistingText, bool bUseMinimalMode, uint64_t uUserValue ) = 0; + + /** Get the text that was entered into the text input **/ + virtual uint32_t GetKeyboardText( VR_OUT_STRING() char *pchText, uint32_t cchText ) = 0; + + /** Hide the virtual keyboard **/ + virtual void HideKeyboard() = 0; + + /** Set the position of the keyboard in world space **/ + virtual void SetKeyboardTransformAbsolute( ETrackingUniverseOrigin eTrackingOrigin, const HmdMatrix34_t *pmatTrackingOriginToKeyboardTransform ) = 0; + + /** Set the position of the keyboard in overlay space by telling it to avoid a rectangle in the overlay. Rectangle coords have (0,0) in the bottom left **/ + virtual void SetKeyboardPositionForOverlay( VROverlayHandle_t ulOverlayHandle, HmdRect2_t avoidRect ) = 0; + + }; + + static const char * const IVROverlay_Version = "IVROverlay_013"; + +} // namespace vr + +// ivrrendermodels.h +namespace vr +{ + +static const char * const k_pch_Controller_Component_GDC2015 = "gdc2015"; // Canonical coordinate system of the gdc 2015 wired controller, provided for backwards compatibility +static const char * const k_pch_Controller_Component_Base = "base"; // For controllers with an unambiguous 'base'. +static const char * const k_pch_Controller_Component_Tip = "tip"; // For controllers with an unambiguous 'tip' (used for 'laser-pointing') +static const char * const k_pch_Controller_Component_HandGrip = "handgrip"; // Neutral, ambidextrous hand-pose when holding controller. On plane between neutrally posed index finger and thumb +static const char * const k_pch_Controller_Component_Status = "status"; // 1:1 aspect ratio status area, with canonical [0,1] uv mapping + +#if defined(__linux__) || defined(__APPLE__) +// The 32-bit version of gcc has the alignment requirement for uint64 and double set to +// 4 meaning that even with #pragma pack(8) these types will only be four-byte aligned. +// The 64-bit version of gcc has the alignment requirement for these types set to +// 8 meaning that unless we use #pragma pack(4) our structures will get bigger. +// The 64-bit structure packing has to match the 32-bit structure packing for each platform. +#pragma pack( push, 4 ) +#else +#pragma pack( push, 8 ) +#endif + +/** Errors that can occur with the VR compositor */ +enum EVRRenderModelError +{ + VRRenderModelError_None = 0, + VRRenderModelError_Loading = 100, + VRRenderModelError_NotSupported = 200, + VRRenderModelError_InvalidArg = 300, + VRRenderModelError_InvalidModel = 301, + VRRenderModelError_NoShapes = 302, + VRRenderModelError_MultipleShapes = 303, + VRRenderModelError_TooManyVertices = 304, + VRRenderModelError_MultipleTextures = 305, + VRRenderModelError_BufferTooSmall = 306, + VRRenderModelError_NotEnoughNormals = 307, + VRRenderModelError_NotEnoughTexCoords = 308, + + VRRenderModelError_InvalidTexture = 400, +}; + +typedef uint32_t VRComponentProperties; + +enum EVRComponentProperty +{ + VRComponentProperty_IsStatic = (1 << 0), + VRComponentProperty_IsVisible = (1 << 1), + VRComponentProperty_IsTouched = (1 << 2), + VRComponentProperty_IsPressed = (1 << 3), + VRComponentProperty_IsScrolled = (1 << 4), +}; + +/** Describes state information about a render-model component, including transforms and other dynamic properties */ +struct RenderModel_ComponentState_t +{ + HmdMatrix34_t mTrackingToComponentRenderModel; // Transform required when drawing the component render model + HmdMatrix34_t mTrackingToComponentLocal; // Transform available for attaching to a local component coordinate system (-Z out from surface ) + VRComponentProperties uProperties; +}; + +/** A single vertex in a render model */ +struct RenderModel_Vertex_t +{ + HmdVector3_t vPosition; // position in meters in device space + HmdVector3_t vNormal; + float rfTextureCoord[2]; +}; + +/** A texture map for use on a render model */ +struct RenderModel_TextureMap_t +{ + uint16_t unWidth, unHeight; // width and height of the texture map in pixels + const uint8_t *rubTextureMapData; // Map texture data. All textures are RGBA with 8 bits per channel per pixel. Data size is width * height * 4ub +}; + +/** Session unique texture identifier. Rendermodels which share the same texture will have the same id. +IDs <0 denote the texture is not present */ + +typedef int32_t TextureID_t; + +const TextureID_t INVALID_TEXTURE_ID = -1; + +struct RenderModel_t +{ + const RenderModel_Vertex_t *rVertexData; // Vertex data for the mesh + uint32_t unVertexCount; // Number of vertices in the vertex data + const uint16_t *rIndexData; // Indices into the vertex data for each triangle + uint32_t unTriangleCount; // Number of triangles in the mesh. Index count is 3 * TriangleCount + TextureID_t diffuseTextureId; // Session unique texture identifier. Rendermodels which share the same texture will have the same id. <0 == texture not present +}; + +struct RenderModel_ControllerMode_State_t +{ + bool bScrollWheelVisible; // is this controller currently set to be in a scroll wheel mode +}; + +#pragma pack( pop ) + +class IVRRenderModels +{ +public: + + /** Loads and returns a render model for use in the application. pchRenderModelName should be a render model name + * from the Prop_RenderModelName_String property or an absolute path name to a render model on disk. + * + * The resulting render model is valid until VR_Shutdown() is called or until FreeRenderModel() is called. When the + * application is finished with the render model it should call FreeRenderModel() to free the memory associated + * with the model. + * + * The method returns VRRenderModelError_Loading while the render model is still being loaded. + * The method returns VRRenderModelError_None once loaded successfully, otherwise will return an error. */ + virtual EVRRenderModelError LoadRenderModel_Async( const char *pchRenderModelName, RenderModel_t **ppRenderModel ) = 0; + + /** Frees a previously returned render model + * It is safe to call this on a null ptr. */ + virtual void FreeRenderModel( RenderModel_t *pRenderModel ) = 0; + + /** Loads and returns a texture for use in the application. */ + virtual EVRRenderModelError LoadTexture_Async( TextureID_t textureId, RenderModel_TextureMap_t **ppTexture ) = 0; + + /** Frees a previously returned texture + * It is safe to call this on a null ptr. */ + virtual void FreeTexture( RenderModel_TextureMap_t *pTexture ) = 0; + + /** Creates a D3D11 texture and loads data into it. */ + virtual EVRRenderModelError LoadTextureD3D11_Async( TextureID_t textureId, void *pD3D11Device, void **ppD3D11Texture2D ) = 0; + + /** Helper function to copy the bits into an existing texture. */ + virtual EVRRenderModelError LoadIntoTextureD3D11_Async( TextureID_t textureId, void *pDstTexture ) = 0; + + /** Use this to free textures created with LoadTextureD3D11_Async instead of calling Release on them. */ + virtual void FreeTextureD3D11( void *pD3D11Texture2D ) = 0; + + /** Use this to get the names of available render models. Index does not correlate to a tracked device index, but + * is only used for iterating over all available render models. If the index is out of range, this function will return 0. + * Otherwise, it will return the size of the buffer required for the name. */ + virtual uint32_t GetRenderModelName( uint32_t unRenderModelIndex, VR_OUT_STRING() char *pchRenderModelName, uint32_t unRenderModelNameLen ) = 0; + + /** Returns the number of available render models. */ + virtual uint32_t GetRenderModelCount() = 0; + + + /** Returns the number of components of the specified render model. + * Components are useful when client application wish to draw, label, or otherwise interact with components of tracked objects. + * Examples controller components: + * renderable things such as triggers, buttons + * non-renderable things which include coordinate systems such as 'tip', 'base', a neutral controller agnostic hand-pose + * If all controller components are enumerated and rendered, it will be equivalent to drawing the traditional render model + * Returns 0 if components not supported, >0 otherwise */ + virtual uint32_t GetComponentCount( const char *pchRenderModelName ) = 0; + + /** Use this to get the names of available components. Index does not correlate to a tracked device index, but + * is only used for iterating over all available components. If the index is out of range, this function will return 0. + * Otherwise, it will return the size of the buffer required for the name. */ + virtual uint32_t GetComponentName( const char *pchRenderModelName, uint32_t unComponentIndex, VR_OUT_STRING( ) char *pchComponentName, uint32_t unComponentNameLen ) = 0; + + /** Get the button mask for all buttons associated with this component + * If no buttons (or axes) are associated with this component, return 0 + * Note: multiple components may be associated with the same button. Ex: two grip buttons on a single controller. + * Note: A single component may be associated with multiple buttons. Ex: A trackpad which also provides "D-pad" functionality */ + virtual uint64_t GetComponentButtonMask( const char *pchRenderModelName, const char *pchComponentName ) = 0; + + /** Use this to get the render model name for the specified rendermode/component combination, to be passed to LoadRenderModel. + * If the component name is out of range, this function will return 0. + * Otherwise, it will return the size of the buffer required for the name. */ + virtual uint32_t GetComponentRenderModelName( const char *pchRenderModelName, const char *pchComponentName, VR_OUT_STRING( ) char *pchComponentRenderModelName, uint32_t unComponentRenderModelNameLen ) = 0; + + /** Use this to query information about the component, as a function of the controller state. + * + * For dynamic controller components (ex: trigger) values will reflect component motions + * For static components this will return a consistent value independent of the VRControllerState_t + * + * If the pchRenderModelName or pchComponentName is invalid, this will return false (and transforms will be set to identity). + * Otherwise, return true + * Note: For dynamic objects, visibility may be dynamic. (I.e., true/false will be returned based on controller state and controller mode state ) */ + virtual bool GetComponentState( const char *pchRenderModelName, const char *pchComponentName, const vr::VRControllerState_t *pControllerState, const RenderModel_ControllerMode_State_t *pState, RenderModel_ComponentState_t *pComponentState ) = 0; + + /** Returns true if the render model has a component with the specified name */ + virtual bool RenderModelHasComponent( const char *pchRenderModelName, const char *pchComponentName ) = 0; + + /** Returns the URL of the thumbnail image for this rendermodel */ + virtual uint32_t GetRenderModelThumbnailURL( const char *pchRenderModelName, VR_OUT_STRING() char *pchThumbnailURL, uint32_t unThumbnailURLLen, vr::EVRRenderModelError *peError ) = 0; + + /** Provides a render model path that will load the unskinned model if the model name provided has been replace by the user. If the model + * hasn't been replaced the path value will still be a valid path to load the model. Pass this to LoadRenderModel_Async, etc. to load the + * model. */ + virtual uint32_t GetRenderModelOriginalPath( const char *pchRenderModelName, VR_OUT_STRING() char *pchOriginalPath, uint32_t unOriginalPathLen, vr::EVRRenderModelError *peError ) = 0; + + /** Returns a string for a render model error */ + virtual const char *GetRenderModelErrorNameFromEnum( vr::EVRRenderModelError error ) = 0; +}; + +static const char * const IVRRenderModels_Version = "IVRRenderModels_005"; + +} + + +// ivrextendeddisplay.h +namespace vr +{ + + /** NOTE: Use of this interface is not recommended in production applications. It will not work for displays which use + * direct-to-display mode. Creating our own window is also incompatible with the VR compositor and is not available when the compositor is running. */ + class IVRExtendedDisplay + { + public: + + /** Size and position that the window needs to be on the VR display. */ + virtual void GetWindowBounds( int32_t *pnX, int32_t *pnY, uint32_t *pnWidth, uint32_t *pnHeight ) = 0; + + /** Gets the viewport in the frame buffer to draw the output of the distortion into */ + virtual void GetEyeOutputViewport( EVREye eEye, uint32_t *pnX, uint32_t *pnY, uint32_t *pnWidth, uint32_t *pnHeight ) = 0; + + /** [D3D10/11 Only] + * Returns the adapter index and output index that the user should pass into EnumAdapters and EnumOutputs + * to create the device and swap chain in DX10 and DX11. If an error occurs both indices will be set to -1. + */ + virtual void GetDXGIOutputInfo( int32_t *pnAdapterIndex, int32_t *pnAdapterOutputIndex ) = 0; + + }; + + static const char * const IVRExtendedDisplay_Version = "IVRExtendedDisplay_001"; + +} + + +// ivrtrackedcamera.h +namespace vr +{ + +class IVRTrackedCamera +{ +public: + /** Returns a string for an error */ + virtual const char *GetCameraErrorNameFromEnum( vr::EVRTrackedCameraError eCameraError ) = 0; + + /** For convenience, same as tracked property request Prop_HasCamera_Bool */ + virtual vr::EVRTrackedCameraError HasCamera( vr::TrackedDeviceIndex_t nDeviceIndex, bool *pHasCamera ) = 0; + + /** Gets size of the image frame. */ + virtual vr::EVRTrackedCameraError GetCameraFrameSize( vr::TrackedDeviceIndex_t nDeviceIndex, vr::EVRTrackedCameraFrameType eFrameType, uint32_t *pnWidth, uint32_t *pnHeight, uint32_t *pnFrameBufferSize ) = 0; + + virtual vr::EVRTrackedCameraError GetCameraIntrinisics( vr::TrackedDeviceIndex_t nDeviceIndex, vr::EVRTrackedCameraFrameType eFrameType, vr::HmdVector2_t *pFocalLength, vr::HmdVector2_t *pCenter ) = 0; + + virtual vr::EVRTrackedCameraError GetCameraProjection( vr::TrackedDeviceIndex_t nDeviceIndex, vr::EVRTrackedCameraFrameType eFrameType, float flZNear, float flZFar, vr::HmdMatrix44_t *pProjection ) = 0; + + /** Acquiring streaming service permits video streaming for the caller. Releasing hints the system that video services do not need to be maintained for this client. + * If the camera has not already been activated, a one time spin up may incur some auto exposure as well as initial streaming frame delays. + * The camera should be considered a global resource accessible for shared consumption but not exclusive to any caller. + * The camera may go inactive due to lack of active consumers or headset idleness. */ + virtual vr::EVRTrackedCameraError AcquireVideoStreamingService( vr::TrackedDeviceIndex_t nDeviceIndex, vr::TrackedCameraHandle_t *pHandle ) = 0; + virtual vr::EVRTrackedCameraError ReleaseVideoStreamingService( vr::TrackedCameraHandle_t hTrackedCamera ) = 0; + + /** Copies the image frame into a caller's provided buffer. The image data is currently provided as RGBA data, 4 bytes per pixel. + * A caller can provide null for the framebuffer or frameheader if not desired. Requesting the frame header first, followed by the frame buffer allows + * the caller to determine if the frame as advanced per the frame header sequence. + * If there is no frame available yet, due to initial camera spinup or re-activation, the error will be VRTrackedCameraError_NoFrameAvailable. + * Ideally a caller should be polling at ~16ms intervals */ + virtual vr::EVRTrackedCameraError GetVideoStreamFrameBuffer( vr::TrackedCameraHandle_t hTrackedCamera, vr::EVRTrackedCameraFrameType eFrameType, void *pFrameBuffer, uint32_t nFrameBufferSize, vr::CameraVideoStreamFrameHeader_t *pFrameHeader, uint32_t nFrameHeaderSize ) = 0; + + /** Gets size of the image frame. */ + virtual vr::EVRTrackedCameraError GetVideoStreamTextureSize( vr::TrackedDeviceIndex_t nDeviceIndex, vr::EVRTrackedCameraFrameType eFrameType, vr::VRTextureBounds_t *pTextureBounds, uint32_t *pnWidth, uint32_t *pnHeight ) = 0; + + /** Access a shared D3D11 texture for the specified tracked camera stream */ + virtual vr::EVRTrackedCameraError GetVideoStreamTextureD3D11( vr::TrackedCameraHandle_t hTrackedCamera, vr::EVRTrackedCameraFrameType eFrameType, void *pD3D11DeviceOrResource, void **ppD3D11ShaderResourceView, vr::CameraVideoStreamFrameHeader_t *pFrameHeader, uint32_t nFrameHeaderSize ) = 0; + + /** Access a shared GL texture for the specified tracked camera stream */ + virtual vr::EVRTrackedCameraError GetVideoStreamTextureGL( vr::TrackedCameraHandle_t hTrackedCamera, vr::EVRTrackedCameraFrameType eFrameType, vr::glUInt_t *pglTextureId, vr::CameraVideoStreamFrameHeader_t *pFrameHeader, uint32_t nFrameHeaderSize ) = 0; + virtual vr::EVRTrackedCameraError ReleaseVideoStreamTextureGL( vr::TrackedCameraHandle_t hTrackedCamera, vr::glUInt_t glTextureId ) = 0; +}; + +static const char * const IVRTrackedCamera_Version = "IVRTrackedCamera_003"; + +} // namespace vr + + +// ivrscreenshots.h +namespace vr +{ + +/** Errors that can occur with the VR compositor */ +enum EVRScreenshotError +{ + VRScreenshotError_None = 0, + VRScreenshotError_RequestFailed = 1, + VRScreenshotError_IncompatibleVersion = 100, + VRScreenshotError_NotFound = 101, + VRScreenshotError_BufferTooSmall = 102, + VRScreenshotError_ScreenshotAlreadyInProgress = 108, +}; + +/** Allows the application to generate screenshots */ +class IVRScreenshots +{ +public: + /** Request a screenshot of the requested type. + * A request of the VRScreenshotType_Stereo type will always + * work. Other types will depend on the underlying application + * support. + * The first file name is for the preview image and should be a + * regular screenshot (ideally from the left eye). The second + * is the VR screenshot in the correct format. They should be + * in the same aspect ratio. Formats per type: + * VRScreenshotType_Mono: the VR filename is ignored (can be + * nullptr), this is a normal flat single shot. + * VRScreenshotType_Stereo: The VR image should be a + * side-by-side with the left eye image on the left. + * VRScreenshotType_Cubemap: The VR image should be six square + * images composited horizontally. + * VRScreenshotType_StereoPanorama: above/below with left eye + * panorama being the above image. Image is typically square + * with the panorama being 2x horizontal. + * + * Note that the VR dashboard will call this function when + * the user presses the screenshot binding (currently System + * Button + Trigger). If Steam is running, the destination + * file names will be in %TEMP% and will be copied into + * Steam's screenshot library for the running application + * once SubmitScreenshot() is called. + * If Steam is not running, the paths will be in the user's + * documents folder under Documents\SteamVR\Screenshots. + * Other VR applications can call this to initate a + * screenshot outside of user control. + * The destination file names do not need an extension, + * will be replaced with the correct one for the format + * which is currently .png. */ + virtual vr::EVRScreenshotError RequestScreenshot( vr::ScreenshotHandle_t *pOutScreenshotHandle, vr::EVRScreenshotType type, const char *pchPreviewFilename, const char *pchVRFilename ) = 0; + + /** Called by the running VR application to indicate that it + * wishes to be in charge of screenshots. If the + * application does not call this, the Compositor will only + * support VRScreenshotType_Stereo screenshots that will be + * captured without notification to the running app. + * Once hooked your application will receive a + * VREvent_RequestScreenshot event when the user presses the + * buttons to take a screenshot. */ + virtual vr::EVRScreenshotError HookScreenshot( VR_ARRAY_COUNT( numTypes ) const vr::EVRScreenshotType *pSupportedTypes, int numTypes ) = 0; + + /** When your application receives a + * VREvent_RequestScreenshot event, call these functions to get + * the details of the screenshot request. */ + virtual vr::EVRScreenshotType GetScreenshotPropertyType( vr::ScreenshotHandle_t screenshotHandle, vr::EVRScreenshotError *pError ) = 0; + + /** Get the filename for the preview or vr image (see + * vr::EScreenshotPropertyFilenames). The return value is + * the size of the string. */ + virtual uint32_t GetScreenshotPropertyFilename( vr::ScreenshotHandle_t screenshotHandle, vr::EVRScreenshotPropertyFilenames filenameType, VR_OUT_STRING() char *pchFilename, uint32_t cchFilename, vr::EVRScreenshotError *pError ) = 0; + + /** Call this if the application is taking the screen shot + * will take more than a few ms processing. This will result + * in an overlay being presented that shows a completion + * bar. */ + virtual vr::EVRScreenshotError UpdateScreenshotProgress( vr::ScreenshotHandle_t screenshotHandle, float flProgress ) = 0; + + /** Tells the compositor to take an internal screenshot of + * type VRScreenshotType_Stereo. It will take the current + * submitted scene textures of the running application and + * write them into the preview image and a side-by-side file + * for the VR image. + * This is similiar to request screenshot, but doesn't ever + * talk to the application, just takes the shot and submits. */ + virtual vr::EVRScreenshotError TakeStereoScreenshot( vr::ScreenshotHandle_t *pOutScreenshotHandle, const char *pchPreviewFilename, const char *pchVRFilename ) = 0; + + /** Submit the completed screenshot. If Steam is running + * this will call into the Steam client and upload the + * screenshot to the screenshots section of the library for + * the running application. If Steam is not running, this + * function will display a notification to the user that the + * screenshot was taken. The paths should be full paths with + * extensions. + * File paths should be absolute including + * exntensions. + * screenshotHandle can be k_unScreenshotHandleInvalid if this + * was a new shot taking by the app to be saved and not + * initiated by a user (achievement earned or something) */ + virtual vr::EVRScreenshotError SubmitScreenshot( vr::ScreenshotHandle_t screenshotHandle, vr::EVRScreenshotType type, const char *pchSourcePreviewFilename, const char *pchSourceVRFilename ) = 0; +}; + +static const char * const IVRScreenshots_Version = "IVRScreenshots_001"; + +} // namespace vr + + + +// ivrresources.h +namespace vr +{ + +class IVRResources +{ +public: + + // ------------------------------------ + // Shared Resource Methods + // ------------------------------------ + + /** Loads the specified resource into the provided buffer if large enough. + * Returns the size in bytes of the buffer required to hold the specified resource. */ + virtual uint32_t LoadSharedResource( const char *pchResourceName, char *pchBuffer, uint32_t unBufferLen ) = 0; + + /** Provides the full path to the specified resource. Resource names can include named directories for + * drivers and other things, and this resolves all of those and returns the actual physical path. + * pchResourceTypeDirectory is the subdirectory of resources to look in. */ + virtual uint32_t GetResourceFullPath( const char *pchResourceName, const char *pchResourceTypeDirectory, char *pchPathBuffer, uint32_t unBufferLen ) = 0; +}; + +static const char * const IVRResources_Version = "IVRResources_001"; + + +}// End + +#endif // _OPENVR_API + + +namespace vr +{ + /** Finds the active installation of the VR API and initializes it. The provided path must be absolute + * or relative to the current working directory. These are the local install versions of the equivalent + * functions in steamvr.h and will work without a local Steam install. + * + * This path is to the "root" of the VR API install. That's the directory with + * the "drivers" directory and a platform (i.e. "win32") directory in it, not the directory with the DLL itself. + */ + inline IVRSystem *VR_Init( EVRInitError *peError, EVRApplicationType eApplicationType ); + + /** unloads vrclient.dll. Any interface pointers from the interface are + * invalid after this point */ + inline void VR_Shutdown(); + + /** Returns true if there is an HMD attached. This check is as lightweight as possible and + * can be called outside of VR_Init/VR_Shutdown. It should be used when an application wants + * to know if initializing VR is a possibility but isn't ready to take that step yet. + */ + VR_INTERFACE bool VR_CALLTYPE VR_IsHmdPresent(); + + /** Returns true if the OpenVR runtime is installed. */ + VR_INTERFACE bool VR_CALLTYPE VR_IsRuntimeInstalled(); + + /** Returns where the OpenVR runtime is installed. */ + VR_INTERFACE const char *VR_CALLTYPE VR_RuntimePath(); + + /** Returns the name of the enum value for an EVRInitError. This function may be called outside of VR_Init()/VR_Shutdown(). */ + VR_INTERFACE const char *VR_CALLTYPE VR_GetVRInitErrorAsSymbol( EVRInitError error ); + + /** Returns an english string for an EVRInitError. Applications should call VR_GetVRInitErrorAsSymbol instead and + * use that as a key to look up their own localized error message. This function may be called outside of VR_Init()/VR_Shutdown(). */ + VR_INTERFACE const char *VR_CALLTYPE VR_GetVRInitErrorAsEnglishDescription( EVRInitError error ); + + /** Returns the interface of the specified version. This method must be called after VR_Init. The + * pointer returned is valid until VR_Shutdown is called. + */ + VR_INTERFACE void *VR_CALLTYPE VR_GetGenericInterface( const char *pchInterfaceVersion, EVRInitError *peError ); + + /** Returns whether the interface of the specified version exists. + */ + VR_INTERFACE bool VR_CALLTYPE VR_IsInterfaceVersionValid( const char *pchInterfaceVersion ); + + /** Returns a token that represents whether the VR interface handles need to be reloaded */ + VR_INTERFACE uint32_t VR_CALLTYPE VR_GetInitToken(); + + // These typedefs allow old enum names from SDK 0.9.11 to be used in applications. + // They will go away in the future. + typedef EVRInitError HmdError; + typedef EVREye Hmd_Eye; + typedef EGraphicsAPIConvention GraphicsAPIConvention; + typedef EColorSpace ColorSpace; + typedef ETrackingResult HmdTrackingResult; + typedef ETrackedDeviceClass TrackedDeviceClass; + typedef ETrackingUniverseOrigin TrackingUniverseOrigin; + typedef ETrackedDeviceProperty TrackedDeviceProperty; + typedef ETrackedPropertyError TrackedPropertyError; + typedef EVRSubmitFlags VRSubmitFlags_t; + typedef EVRState VRState_t; + typedef ECollisionBoundsStyle CollisionBoundsStyle_t; + typedef EVROverlayError VROverlayError; + typedef EVRFirmwareError VRFirmwareError; + typedef EVRCompositorError VRCompositorError; + typedef EVRScreenshotError VRScreenshotsError; + + inline uint32_t &VRToken() + { + static uint32_t token; + return token; + } + + class COpenVRContext + { + public: + COpenVRContext() { Clear(); } + void Clear(); + + inline void CheckClear() + { + if ( VRToken() != VR_GetInitToken() ) + { + Clear(); + VRToken() = VR_GetInitToken(); + } + } + + IVRSystem *VRSystem() + { + CheckClear(); + if ( m_pVRSystem == nullptr ) + { + EVRInitError eError; + m_pVRSystem = ( IVRSystem * )VR_GetGenericInterface( IVRSystem_Version, &eError ); + } + return m_pVRSystem; + } + IVRChaperone *VRChaperone() + { + CheckClear(); + if ( m_pVRChaperone == nullptr ) + { + EVRInitError eError; + m_pVRChaperone = ( IVRChaperone * )VR_GetGenericInterface( IVRChaperone_Version, &eError ); + } + return m_pVRChaperone; + } + + IVRChaperoneSetup *VRChaperoneSetup() + { + CheckClear(); + if ( m_pVRChaperoneSetup == nullptr ) + { + EVRInitError eError; + m_pVRChaperoneSetup = ( IVRChaperoneSetup * )VR_GetGenericInterface( IVRChaperoneSetup_Version, &eError ); + } + return m_pVRChaperoneSetup; + } + + IVRCompositor *VRCompositor() + { + CheckClear(); + if ( m_pVRCompositor == nullptr ) + { + EVRInitError eError; + m_pVRCompositor = ( IVRCompositor * )VR_GetGenericInterface( IVRCompositor_Version, &eError ); + } + return m_pVRCompositor; + } + + IVROverlay *VROverlay() + { + CheckClear(); + if ( m_pVROverlay == nullptr ) + { + EVRInitError eError; + m_pVROverlay = ( IVROverlay * )VR_GetGenericInterface( IVROverlay_Version, &eError ); + } + return m_pVROverlay; + } + + IVRResources *VRResources() + { + CheckClear(); + if ( m_pVRResources == nullptr ) + { + EVRInitError eError; + m_pVRResources = (IVRResources *)VR_GetGenericInterface( IVRResources_Version, &eError ); + } + return m_pVRResources; + } + + IVRScreenshots *VRScreenshots() + { + CheckClear(); + if ( m_pVRScreenshots == nullptr ) + { + EVRInitError eError; + m_pVRScreenshots = ( IVRScreenshots * )VR_GetGenericInterface( IVRScreenshots_Version, &eError ); + } + return m_pVRScreenshots; + } + + IVRRenderModels *VRRenderModels() + { + CheckClear(); + if ( m_pVRRenderModels == nullptr ) + { + EVRInitError eError; + m_pVRRenderModels = ( IVRRenderModels * )VR_GetGenericInterface( IVRRenderModels_Version, &eError ); + } + return m_pVRRenderModels; + } + + IVRExtendedDisplay *VRExtendedDisplay() + { + CheckClear(); + if ( m_pVRExtendedDisplay == nullptr ) + { + EVRInitError eError; + m_pVRExtendedDisplay = ( IVRExtendedDisplay * )VR_GetGenericInterface( IVRExtendedDisplay_Version, &eError ); + } + return m_pVRExtendedDisplay; + } + + IVRSettings *VRSettings() + { + CheckClear(); + if ( m_pVRSettings == nullptr ) + { + EVRInitError eError; + m_pVRSettings = ( IVRSettings * )VR_GetGenericInterface( IVRSettings_Version, &eError ); + } + return m_pVRSettings; + } + + IVRApplications *VRApplications() + { + CheckClear(); + if ( m_pVRApplications == nullptr ) + { + EVRInitError eError; + m_pVRApplications = ( IVRApplications * )VR_GetGenericInterface( IVRApplications_Version, &eError ); + } + return m_pVRApplications; + } + + IVRTrackedCamera *VRTrackedCamera() + { + CheckClear(); + if ( m_pVRTrackedCamera == nullptr ) + { + EVRInitError eError; + m_pVRTrackedCamera = ( IVRTrackedCamera * )VR_GetGenericInterface( IVRTrackedCamera_Version, &eError ); + } + return m_pVRTrackedCamera; + } + + private: + IVRSystem *m_pVRSystem; + IVRChaperone *m_pVRChaperone; + IVRChaperoneSetup *m_pVRChaperoneSetup; + IVRCompositor *m_pVRCompositor; + IVROverlay *m_pVROverlay; + IVRResources *m_pVRResources; + IVRRenderModels *m_pVRRenderModels; + IVRExtendedDisplay *m_pVRExtendedDisplay; + IVRSettings *m_pVRSettings; + IVRApplications *m_pVRApplications; + IVRTrackedCamera *m_pVRTrackedCamera; + IVRScreenshots *m_pVRScreenshots; + }; + + inline COpenVRContext &OpenVRInternal_ModuleContext() + { + static void *ctx[ sizeof( COpenVRContext ) / sizeof( void * ) ]; + return *( COpenVRContext * )ctx; // bypass zero-init constructor + } + + inline IVRSystem *VR_CALLTYPE VRSystem() { return OpenVRInternal_ModuleContext().VRSystem(); } + inline IVRChaperone *VR_CALLTYPE VRChaperone() { return OpenVRInternal_ModuleContext().VRChaperone(); } + inline IVRChaperoneSetup *VR_CALLTYPE VRChaperoneSetup() { return OpenVRInternal_ModuleContext().VRChaperoneSetup(); } + inline IVRCompositor *VR_CALLTYPE VRCompositor() { return OpenVRInternal_ModuleContext().VRCompositor(); } + inline IVROverlay *VR_CALLTYPE VROverlay() { return OpenVRInternal_ModuleContext().VROverlay(); } + inline IVRScreenshots *VR_CALLTYPE VRScreenshots() { return OpenVRInternal_ModuleContext().VRScreenshots(); } + inline IVRRenderModels *VR_CALLTYPE VRRenderModels() { return OpenVRInternal_ModuleContext().VRRenderModels(); } + inline IVRApplications *VR_CALLTYPE VRApplications() { return OpenVRInternal_ModuleContext().VRApplications(); } + inline IVRSettings *VR_CALLTYPE VRSettings() { return OpenVRInternal_ModuleContext().VRSettings(); } + inline IVRResources *VR_CALLTYPE VRResources() { return OpenVRInternal_ModuleContext().VRResources(); } + inline IVRExtendedDisplay *VR_CALLTYPE VRExtendedDisplay() { return OpenVRInternal_ModuleContext().VRExtendedDisplay(); } + inline IVRTrackedCamera *VR_CALLTYPE VRTrackedCamera() { return OpenVRInternal_ModuleContext().VRTrackedCamera(); } + + inline void COpenVRContext::Clear() + { + m_pVRSystem = nullptr; + m_pVRChaperone = nullptr; + m_pVRChaperoneSetup = nullptr; + m_pVRCompositor = nullptr; + m_pVROverlay = nullptr; + m_pVRRenderModels = nullptr; + m_pVRExtendedDisplay = nullptr; + m_pVRSettings = nullptr; + m_pVRApplications = nullptr; + m_pVRTrackedCamera = nullptr; + m_pVRResources = nullptr; + m_pVRScreenshots = nullptr; + } + + VR_INTERFACE uint32_t VR_CALLTYPE VR_InitInternal( EVRInitError *peError, EVRApplicationType eApplicationType ); + VR_INTERFACE void VR_CALLTYPE VR_ShutdownInternal(); + + /** Finds the active installation of vrclient.dll and initializes it */ + inline IVRSystem *VR_Init( EVRInitError *peError, EVRApplicationType eApplicationType ) + { + IVRSystem *pVRSystem = nullptr; + + EVRInitError eError; + VRToken() = VR_InitInternal( &eError, eApplicationType ); + COpenVRContext &ctx = OpenVRInternal_ModuleContext(); + ctx.Clear(); + + if ( eError == VRInitError_None ) + { + if ( VR_IsInterfaceVersionValid( IVRSystem_Version ) ) + { + pVRSystem = VRSystem(); + } + else + { + VR_ShutdownInternal(); + eError = VRInitError_Init_InterfaceNotFound; + } + } + + if ( peError ) + *peError = eError; + return pVRSystem; + } + + /** unloads vrclient.dll. Any interface pointers from the interface are + * invalid after this point */ + inline void VR_Shutdown() + { + VR_ShutdownInternal(); + } +} diff --git a/modules/libpref/init/all.js b/modules/libpref/init/all.js index 98a3cfc5b69e..b492f1929a65 100644 --- a/modules/libpref/init/all.js +++ b/modules/libpref/init/all.js @@ -4937,11 +4937,15 @@ pref("dom.vr.enabled", true); pref("dom.vr.oculus.enabled", true); // OSVR device pref("dom.vr.osvr.enabled", false); +// OpenVR device +pref("dom.vr.openvr.enabled", false); // Pose prediction reduces latency effects by returning future predicted HMD // poses to callers of the WebVR API. This currently only has an effect for // Oculus Rift on SDK 0.8 or greater. It is disabled by default for now due to // frame uniformity issues with e10s. pref("dom.vr.poseprediction.enabled", false); +// path to openvr DLL +pref("gfx.vr.openvr-runtime", ""); // path to OSVR DLLs pref("gfx.vr.osvr.utilLibPath", ""); pref("gfx.vr.osvr.commonLibPath", ""); From 2dd132524059d6fb317d5f369b46e3a30da15ebc Mon Sep 17 00:00:00 2001 From: Matt Howell Date: Tue, 23 Aug 2016 14:11:23 -0700 Subject: [PATCH 007/105] Bug 1246972 - Always require the update working directory to be within the installation path; r=rstrong This required fixing a few chrome tests which broke on Mac because they were assuming updater-settings.ini would be at the same location as the executables. Also, this patch removes many dependencies on the current working directory from updater.cpp by changing it to use absolute paths instead. Otherwise this patch would have required adding yet more chdir() calls to avoid invalidating existing assumptions about what the current directory is. MozReview-Commit-ID: ASxfV4uVpmD --HG-- extra : rebase_source : e9f7c5614ab7a90a290b3586dedde410ac21d5ac extra : amend_source : 5c80ab53f2db066f6859b4f29479778d32734f3e --- toolkit/mozapps/update/common/errors.h | 3 +- toolkit/mozapps/update/tests/chrome/utils.js | 4 +- .../update/tests/data/sharedUpdateXML.js | 18 +- .../update/tests/data/xpcshellUtilsAUS.js | 20 +- .../marWrongApplyToDirFailure_win.js | 39 ++ .../tests/unit_base_updater/xpcshell.ini | 2 + toolkit/mozapps/update/updater/updater.cpp | 445 ++++++++++-------- 7 files changed, 331 insertions(+), 200 deletions(-) create mode 100644 toolkit/mozapps/update/tests/unit_base_updater/marWrongApplyToDirFailure_win.js diff --git a/toolkit/mozapps/update/common/errors.h b/toolkit/mozapps/update/common/errors.h index 33ee98c56af5..fa83c21d4ab1 100644 --- a/toolkit/mozapps/update/common/errors.h +++ b/toolkit/mozapps/update/common/errors.h @@ -83,8 +83,9 @@ #define WRITE_ERROR_DELETE_BACKUP 69 #define WRITE_ERROR_EXTRACT 70 #define REMOVE_FILE_SPEC_ERROR 71 -#define INVALID_STAGED_PARENT_ERROR 72 +#define INVALID_APPLYTO_DIR_STAGED_ERROR 72 #define LOCK_ERROR_PATCH_FILE 73 +#define INVALID_APPLYTO_DIR_ERROR 74 // Error codes 80 through 99 are reserved for nsUpdateService.js diff --git a/toolkit/mozapps/update/tests/chrome/utils.js b/toolkit/mozapps/update/tests/chrome/utils.js index 64f32d5cb350..e49f2ec22831 100644 --- a/toolkit/mozapps/update/tests/chrome/utils.js +++ b/toolkit/mozapps/update/tests/chrome/utils.js @@ -747,7 +747,7 @@ function verifyTestsRan() { */ function setupFiles() { // Backup the updater-settings.ini file if it exists by moving it. - let baseAppDir = getAppBaseDir(); + let baseAppDir = getGREDir(); let updateSettingsIni = baseAppDir.clone(); updateSettingsIni.append(FILE_UPDATE_SETTINGS_INI); if (updateSettingsIni.exists()) { @@ -902,7 +902,7 @@ function setupPrefs() { */ function resetFiles() { // Restore the backed up updater-settings.ini if it exists. - let baseAppDir = getAppBaseDir(); + let baseAppDir = getGREDir(); let updateSettingsIni = baseAppDir.clone(); updateSettingsIni.append(FILE_UPDATE_SETTINGS_INI_BAK); if (updateSettingsIni.exists()) { diff --git a/toolkit/mozapps/update/tests/data/sharedUpdateXML.js b/toolkit/mozapps/update/tests/data/sharedUpdateXML.js index c6da47909aa6..14c2c6ca53ea 100644 --- a/toolkit/mozapps/update/tests/data/sharedUpdateXML.js +++ b/toolkit/mozapps/update/tests/data/sharedUpdateXML.js @@ -35,12 +35,14 @@ const STATE_SUCCEEDED = "succeeded"; const STATE_DOWNLOAD_FAILED = "download-failed"; const STATE_FAILED = "failed"; -const LOADSOURCE_ERROR_WRONG_SIZE = 2; -const CRC_ERROR = 4; -const READ_ERROR = 6; -const WRITE_ERROR = 7; -const MAR_CHANNEL_MISMATCH_ERROR = 22; -const VERSION_DOWNGRADE_ERROR = 23; +const LOADSOURCE_ERROR_WRONG_SIZE = 2; +const CRC_ERROR = 4; +const READ_ERROR = 6; +const WRITE_ERROR = 7; +const MAR_CHANNEL_MISMATCH_ERROR = 22; +const VERSION_DOWNGRADE_ERROR = 23; +const INVALID_APPLYTO_DIR_STAGED_ERROR = 72; +const INVALID_APPLYTO_DIR_ERROR = 74; const STATE_FAILED_DELIMETER = ": "; @@ -56,6 +58,10 @@ const STATE_FAILED_MAR_CHANNEL_MISMATCH_ERROR = STATE_FAILED + STATE_FAILED_DELIMETER + MAR_CHANNEL_MISMATCH_ERROR; const STATE_FAILED_VERSION_DOWNGRADE_ERROR = STATE_FAILED + STATE_FAILED_DELIMETER + VERSION_DOWNGRADE_ERROR; +const STATE_FAILED_INVALID_APPLYTO_DIR_STAGED_ERROR = + STATE_FAILED + STATE_FAILED_DELIMETER + INVALID_APPLYTO_DIR_STAGED_ERROR; +const STATE_FAILED_INVALID_APPLYTO_DIR_ERROR = + STATE_FAILED + STATE_FAILED_DELIMETER + INVALID_APPLYTO_DIR_ERROR; /** * Constructs a string representing a remote update xml file. diff --git a/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js b/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js index 5c46960ef450..89a0e1c96b3e 100644 --- a/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js +++ b/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js @@ -155,6 +155,8 @@ var gGREDirOrig; var gGREBinDirOrig; var gAppDirOrig; +var gApplyToDirOverride; + var gServiceLaunchedCallbackLog = null; var gServiceLaunchedCallbackArgs = null; @@ -1137,6 +1139,18 @@ function getAppVersion() { return iniParser.getString("App", "Version"); } +/** + * Override the apply-to directory parameter to be passed to the updater. + * This ought to cause the updater to fail when using any value that isn't the + * default, automatically computed one. + * + * @param dir + * Complete string to use as the apply-to directory parameter. + */ +function overrideApplyToDir(dir) { + gApplyToDirOverride = dir; +} + /** * Helper function for getting the relative path to the directory where the * application binary is located (e.g. /dir.app/). @@ -1703,13 +1717,13 @@ function runUpdateUsingUpdater(aExpectedStatus, aSwitchApp, aExpectedExitValue) callbackApp.permissions = PERMS_DIRECTORY; setAppBundleModTime(); - + let args = [updatesDirPath, applyToDirPath]; if (aSwitchApp) { - args[2] = stageDirPath; + args[2] = gApplyToDirOverride || stageDirPath; args[3] = "0/replace"; } else { - args[2] = applyToDirPath; + args[2] = gApplyToDirOverride || applyToDirPath; args[3] = "0"; } args = args.concat([callbackApp.parent.path, callbackApp.path]); diff --git a/toolkit/mozapps/update/tests/unit_base_updater/marWrongApplyToDirFailure_win.js b/toolkit/mozapps/update/tests/unit_base_updater/marWrongApplyToDirFailure_win.js new file mode 100644 index 000000000000..86ca3feedd7e --- /dev/null +++ b/toolkit/mozapps/update/tests/unit_base_updater/marWrongApplyToDirFailure_win.js @@ -0,0 +1,39 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +/* Test trying to use an apply-to directory different from the install + * directory, which should fail. + */ + +function run_test() { + if (!setupTestCommon()) { + return; + } + gTestFiles = gTestFilesCompleteSuccess; + gTestDirs = gTestDirsCompleteSuccess; + setTestFilesAndDirsForFailure(); + setupUpdaterTest(FILE_COMPLETE_MAR, false); +} + +/** + * Called after the call to setupUpdaterTest finishes. + */ +function setupUpdaterTestFinished() { + overrideApplyToDir(getApplyDirPath() + "/../NoSuchDir"); + // If execv is used the updater process will turn into the callback process + // and the updater's return code will be that of the callback process. + runUpdateUsingUpdater(STATE_FAILED_INVALID_APPLYTO_DIR_ERROR, false, + (USE_EXECV ? 0 : 1)); +} + +/** + * Called after the call to runUpdateUsingUpdater finishes. + */ +function runUpdateFinished() { + standardInit(); + checkPostUpdateRunningFile(false); + checkFilesAfterUpdateFailure(getApplyDirFile); + waitForFilesInUse(); +} diff --git a/toolkit/mozapps/update/tests/unit_base_updater/xpcshell.ini b/toolkit/mozapps/update/tests/unit_base_updater/xpcshell.ini index 81ef7053dd30..40206798b8f8 100644 --- a/toolkit/mozapps/update/tests/unit_base_updater/xpcshell.ini +++ b/toolkit/mozapps/update/tests/unit_base_updater/xpcshell.ini @@ -77,3 +77,5 @@ reason = bug 1164150 [marAppApplyUpdateStageSuccess.js] skip-if = toolkit == 'gonk' reason = bug 1164150 +[marWrongApplyToDirFailure_win.js] +skip-if = os != 'win' diff --git a/toolkit/mozapps/update/updater/updater.cpp b/toolkit/mozapps/update/updater/updater.cpp index 550c29914b28..1cf901f0ae0e 100644 --- a/toolkit/mozapps/update/updater/updater.cpp +++ b/toolkit/mozapps/update/updater/updater.cpp @@ -59,6 +59,7 @@ #include "mozilla/Compiler.h" #include "mozilla/Types.h" +#include "mozilla/UniquePtr.h" // Amount of the progress bar to use in each of the 3 update stages, // should total 100.0. @@ -320,6 +321,7 @@ static bool sIsOSUpdate = false; static NS_tchar* gDestPath; static NS_tchar gCallbackRelPath[MAXPATHLEN]; static NS_tchar gCallbackBackupPath[MAXPATHLEN]; +static NS_tchar gDeleteDirPath[MAXPATHLEN]; #endif static const NS_tchar kWhitespace[] = NS_T(" \t"); @@ -380,9 +382,8 @@ EnvHasValue(const char *name) return (val && *val); } -#ifdef XP_WIN /** - * Coverts a relative update path to a full path for Windows. + * Coverts a relative update path to a full path. * * @param relpath * The relative path to convert to a full path. @@ -391,23 +392,56 @@ EnvHasValue(const char *name) static NS_tchar* get_full_path(const NS_tchar *relpath) { - size_t lendestpath = NS_tstrlen(gDestPath); + NS_tchar *destpath = sStagedUpdate ? gWorkingDirPath : gInstallDirPath; + size_t lendestpath = NS_tstrlen(destpath); size_t lenrelpath = NS_tstrlen(relpath); - NS_tchar *s = (NS_tchar *) malloc((lendestpath + lenrelpath + 1) * sizeof(NS_tchar)); - if (!s) + NS_tchar *s = new NS_tchar[lendestpath + lenrelpath + 2]; + if (!s) { return nullptr; + } NS_tchar *c = s; - NS_tstrcpy(c, gDestPath); + NS_tstrcpy(c, destpath); c += lendestpath; + NS_tstrcat(c, NS_T("/")); + c++; + NS_tstrcat(c, relpath); c += lenrelpath; *c = NS_T('\0'); - c++; return s; } + +/** + * Converts a full update path into a relative path; reverses get_full_path. + * + * @param fullpath + * The absolute path to convert into a relative path. + * return pointer to the location within fullpath where the relative path starts + * or fullpath itself if it already looks relative. + */ +static const NS_tchar* +get_relative_path(const NS_tchar *fullpath) +{ + // If the path isn't absolute, just return it as-is. +#ifdef XP_WIN + if (fullpath[1] != ':' && fullpath[2] != '\\') { +#else + if (fullpath[0] != '/') { #endif + return fullpath; + } + + NS_tchar *prefix = sStagedUpdate ? gWorkingDirPath : gInstallDirPath; + + // If the path isn't long enough to be absolute, return it as-is. + if (NS_tstrlen(fullpath) <= NS_tstrlen(prefix)) { + return fullpath; + } + + return fullpath + NS_tstrlen(prefix) + 1; +} /** * Gets the platform specific path and performs simple checks to the path. If @@ -968,14 +1002,18 @@ static int backup_create(const NS_tchar *path) // Rename the backup of the specified file that was created by renaming it back // to the original file. -static int backup_restore(const NS_tchar *path) +static int backup_restore(const NS_tchar *path, const NS_tchar *relPath) { NS_tchar backup[MAXPATHLEN]; NS_tsnprintf(backup, sizeof(backup)/sizeof(backup[0]), NS_T("%s") BACKUP_EXT, path); + NS_tchar relBackup[MAXPATHLEN]; + NS_tsnprintf(relBackup, sizeof(relBackup) / sizeof(relBackup[0]), + NS_T("%s") BACKUP_EXT, relPath); + if (NS_taccess(backup, F_OK)) { - LOG(("backup_restore: backup file doesn't exist: " LOG_S, backup)); + LOG(("backup_restore: backup file doesn't exist: " LOG_S, relBackup)); return OK; } @@ -983,12 +1021,16 @@ static int backup_restore(const NS_tchar *path) } // Discard the backup of the specified file that was created by renaming it. -static int backup_discard(const NS_tchar *path) +static int backup_discard(const NS_tchar *path, const NS_tchar *relPath) { NS_tchar backup[MAXPATHLEN]; NS_tsnprintf(backup, sizeof(backup)/sizeof(backup[0]), NS_T("%s") BACKUP_EXT, path); + NS_tchar relBackup[MAXPATHLEN]; + NS_tsnprintf(relBackup, sizeof(relBackup) / sizeof(relBackup[0]), + NS_T("%s") BACKUP_EXT, relPath); + // Nothing to discard if (NS_taccess(backup, F_OK)) { return OK; @@ -997,12 +1039,12 @@ static int backup_discard(const NS_tchar *path) int rv = ensure_remove(backup); #if defined(XP_WIN) if (rv && !sStagedUpdate && !sReplaceRequest) { - LOG(("backup_discard: unable to remove: " LOG_S, backup)); + LOG(("backup_discard: unable to remove: " LOG_S, relBackup)); NS_tchar path[MAXPATHLEN]; - GetTempFileNameW(DELETE_DIR, L"moz", 0, path); + GetTempFileNameW(gDeleteDirPath, L"moz", 0, path); if (rename_file(backup, path)) { LOG(("backup_discard: failed to rename file:" LOG_S ", dst:" LOG_S, - backup, path)); + relBackup, relPath)); return WRITE_ERROR_DELETE_BACKUP; } // The MoveFileEx call to remove the file on OS reboot will fail if the @@ -1012,10 +1054,10 @@ static int backup_discard(const NS_tchar *path) // applied, on reinstall, and on uninstall. if (MoveFileEx(path, nullptr, MOVEFILE_DELAY_UNTIL_REBOOT)) { LOG(("backup_discard: file renamed and will be removed on OS " \ - "reboot: " LOG_S, path)); + "reboot: " LOG_S, relPath)); } else { LOG(("backup_discard: failed to schedule OS reboot removal of " \ - "file: " LOG_S, path)); + "file: " LOG_S, relPath)); } } #else @@ -1027,12 +1069,13 @@ static int backup_discard(const NS_tchar *path) } // Helper function for post-processing a temporary backup. -static void backup_finish(const NS_tchar *path, int status) +static void backup_finish(const NS_tchar *path, const NS_tchar *relPath, + int status) { if (status == OK) - backup_discard(path); + backup_discard(path, relPath); else - backup_restore(path); + backup_restore(path, relPath); } //----------------------------------------------------------------------------- @@ -1070,7 +1113,7 @@ private: class RemoveFile : public Action { public: - RemoveFile() : mFile(nullptr), mSkip(0) { } + RemoveFile() : mSkip(0) { } int Parse(NS_tchar *line); int Prepare(); @@ -1078,7 +1121,8 @@ public: void Finish(int status); private: - const NS_tchar *mFile; + mozilla::UniquePtr mFile; + mozilla::UniquePtr mRelPath; int mSkip; }; @@ -1087,9 +1131,18 @@ RemoveFile::Parse(NS_tchar *line) { // format "" - mFile = get_valid_path(&line); - if (!mFile) + NS_tchar * validPath = get_valid_path(&line); + if (!validPath) { return PARSE_ERROR; + } + + mRelPath = mozilla::MakeUnique(MAXPATHLEN); + NS_tstrcpy(mRelPath.get(), validPath); + + mFile.reset(get_full_path(validPath)); + if (!mFile) { + return PARSE_ERROR; + } return OK; } @@ -1098,33 +1151,33 @@ int RemoveFile::Prepare() { // Skip the file if it already doesn't exist. - int rv = NS_taccess(mFile, F_OK); + int rv = NS_taccess(mFile.get(), F_OK); if (rv) { mSkip = 1; mProgressCost = 0; return OK; } - LOG(("PREPARE REMOVEFILE " LOG_S, mFile)); + LOG(("PREPARE REMOVEFILE " LOG_S, mRelPath.get())); // Make sure that we're actually a file... struct NS_tstat_t fileInfo; - rv = NS_tstat(mFile, &fileInfo); + rv = NS_tstat(mFile.get(), &fileInfo); if (rv) { - LOG(("failed to read file status info: " LOG_S ", err: %d", mFile, + LOG(("failed to read file status info: " LOG_S ", err: %d", mFile.get(), errno)); return READ_ERROR; } if (!S_ISREG(fileInfo.st_mode)) { - LOG(("path present, but not a file: " LOG_S, mFile)); + LOG(("path present, but not a file: " LOG_S, mFile.get())); return DELETE_ERROR_EXPECTED_FILE; } - NS_tchar *slash = (NS_tchar *) NS_tstrrchr(mFile, NS_T('/')); + NS_tchar *slash = (NS_tchar *) NS_tstrrchr(mFile.get(), NS_T('/')); if (slash) { *slash = NS_T('\0'); - rv = NS_taccess(mFile, W_OK); + rv = NS_taccess(mFile.get(), W_OK); *slash = NS_T('/'); } else { rv = NS_taccess(NS_T("."), W_OK); @@ -1144,11 +1197,11 @@ RemoveFile::Execute() if (mSkip) return OK; - LOG(("EXECUTE REMOVEFILE " LOG_S, mFile)); + LOG(("EXECUTE REMOVEFILE " LOG_S, mRelPath.get())); // The file is checked for existence here and in Prepare since it might have // been removed by a separate instruction: bug 311099. - int rv = NS_taccess(mFile, F_OK); + int rv = NS_taccess(mFile.get(), F_OK); if (rv) { LOG(("file cannot be removed because it does not exist; skipping")); mSkip = 1; @@ -1156,7 +1209,7 @@ RemoveFile::Execute() } // Rename the old file. It will be removed in Finish. - rv = backup_create(mFile); + rv = backup_create(mFile.get()); if (rv) { LOG(("backup_create failed: %d", rv)); return rv; @@ -1171,15 +1224,15 @@ RemoveFile::Finish(int status) if (mSkip) return; - LOG(("FINISH REMOVEFILE " LOG_S, mFile)); + LOG(("FINISH REMOVEFILE " LOG_S, mRelPath.get())); - backup_finish(mFile, status); + backup_finish(mFile.get(), mRelPath.get(), status); } class RemoveDir : public Action { public: - RemoveDir() : mDir(nullptr), mSkip(0) { } + RemoveDir() : mSkip(0) { } virtual int Parse(NS_tchar *line); virtual int Prepare(); // check that the source dir exists @@ -1187,7 +1240,8 @@ public: virtual void Finish(int status); private: - const NS_tchar *mDir; + mozilla::UniquePtr mDir; + mozilla::UniquePtr mRelPath; int mSkip; }; @@ -1196,9 +1250,18 @@ RemoveDir::Parse(NS_tchar *line) { // format "/" - mDir = get_valid_path(&line, true); - if (!mDir) + NS_tchar * validPath = get_valid_path(&line, true); + if (!validPath) { return PARSE_ERROR; + } + + mRelPath = mozilla::MakeUnique(MAXPATHLEN); + NS_tstrcpy(mRelPath.get(), validPath); + + mDir.reset(get_full_path(validPath)); + if (!mDir) { + return PARSE_ERROR; + } return OK; } @@ -1207,30 +1270,30 @@ int RemoveDir::Prepare() { // We expect the directory to exist if we are to remove it. - int rv = NS_taccess(mDir, F_OK); + int rv = NS_taccess(mDir.get(), F_OK); if (rv) { mSkip = 1; mProgressCost = 0; return OK; } - LOG(("PREPARE REMOVEDIR " LOG_S "/", mDir)); + LOG(("PREPARE REMOVEDIR " LOG_S "/", mRelPath.get())); // Make sure that we're actually a dir. struct NS_tstat_t dirInfo; - rv = NS_tstat(mDir, &dirInfo); + rv = NS_tstat(mDir.get(), &dirInfo); if (rv) { - LOG(("failed to read directory status info: " LOG_S ", err: %d", mDir, + LOG(("failed to read directory status info: " LOG_S ", err: %d", mRelPath.get(), errno)); return READ_ERROR; } if (!S_ISDIR(dirInfo.st_mode)) { - LOG(("path present, but not a directory: " LOG_S, mDir)); + LOG(("path present, but not a directory: " LOG_S, mRelPath.get())); return DELETE_ERROR_EXPECTED_DIR; } - rv = NS_taccess(mDir, W_OK); + rv = NS_taccess(mDir.get(), W_OK); if (rv) { LOG(("access failed: %d, %d", rv, errno)); return WRITE_ERROR_DIR_ACCESS_DENIED; @@ -1245,11 +1308,11 @@ RemoveDir::Execute() if (mSkip) return OK; - LOG(("EXECUTE REMOVEDIR " LOG_S "/", mDir)); + LOG(("EXECUTE REMOVEDIR " LOG_S "/", mRelPath.get())); // The directory is checked for existence at every step since it might have // been removed by a separate instruction: bug 311099. - int rv = NS_taccess(mDir, F_OK); + int rv = NS_taccess(mDir.get(), F_OK); if (rv) { LOG(("directory no longer exists; skipping")); mSkip = 1; @@ -1264,11 +1327,11 @@ RemoveDir::Finish(int status) if (mSkip || status != OK) return; - LOG(("FINISH REMOVEDIR " LOG_S "/", mDir)); + LOG(("FINISH REMOVEDIR " LOG_S "/", mRelPath.get())); // The directory is checked for existence at every step since it might have // been removed by a separate instruction: bug 311099. - int rv = NS_taccess(mDir, F_OK); + int rv = NS_taccess(mDir.get(), F_OK); if (rv) { LOG(("directory no longer exists; skipping")); return; @@ -1276,9 +1339,9 @@ RemoveDir::Finish(int status) if (status == OK) { - if (NS_trmdir(mDir)) { + if (NS_trmdir(mDir.get())) { LOG(("non-fatal error removing directory: " LOG_S "/, rv: %d, err: %d", - mDir, rv, errno)); + mRelPath.get(), rv, errno)); } } } @@ -1286,9 +1349,7 @@ RemoveDir::Finish(int status) class AddFile : public Action { public: - AddFile() : mFile(nullptr) - , mAdded(false) - { } + AddFile() : mAdded(false) { } virtual int Parse(NS_tchar *line); virtual int Prepare(); @@ -1296,7 +1357,8 @@ public: virtual void Finish(int status); private: - const NS_tchar *mFile; + mozilla::UniquePtr mFile; + mozilla::UniquePtr mRelPath; bool mAdded; }; @@ -1305,9 +1367,18 @@ AddFile::Parse(NS_tchar *line) { // format "" - mFile = get_valid_path(&line); - if (!mFile) + NS_tchar * validPath = get_valid_path(&line); + if (!validPath) { return PARSE_ERROR; + } + + mRelPath = mozilla::MakeUnique(MAXPATHLEN); + NS_tstrcpy(mRelPath.get(), validPath); + + mFile.reset(get_full_path(validPath)); + if (!mFile) { + return PARSE_ERROR; + } return OK; } @@ -1315,7 +1386,7 @@ AddFile::Parse(NS_tchar *line) int AddFile::Prepare() { - LOG(("PREPARE ADD " LOG_S, mFile)); + LOG(("PREPARE ADD " LOG_S, mRelPath.get())); return OK; } @@ -1323,33 +1394,33 @@ AddFile::Prepare() int AddFile::Execute() { - LOG(("EXECUTE ADD " LOG_S, mFile)); + LOG(("EXECUTE ADD " LOG_S, mRelPath.get())); int rv; // First make sure that we can actually get rid of any existing file. - rv = NS_taccess(mFile, F_OK); + rv = NS_taccess(mFile.get(), F_OK); if (rv == 0) { - rv = backup_create(mFile); + rv = backup_create(mFile.get()); if (rv) return rv; } else { - rv = ensure_parent_dir(mFile); + rv = ensure_parent_dir(mFile.get()); if (rv) return rv; } #ifdef XP_WIN char sourcefile[MAXPATHLEN]; - if (!WideCharToMultiByte(CP_UTF8, 0, mFile, -1, sourcefile, MAXPATHLEN, - nullptr, nullptr)) { + if (!WideCharToMultiByte(CP_UTF8, 0, mRelPath.get(), -1, sourcefile, + MAXPATHLEN, nullptr, nullptr)) { LOG(("error converting wchar to utf8: %d", GetLastError())); return STRING_CONVERSION_ERROR; } - rv = gArchiveReader.ExtractFile(sourcefile, mFile); + rv = gArchiveReader.ExtractFile(sourcefile, mFile.get()); #else - rv = gArchiveReader.ExtractFile(mFile, mFile); + rv = gArchiveReader.ExtractFile(mRelPath.get(), mFile.get()); #endif if (!rv) { mAdded = true; @@ -1360,18 +1431,18 @@ AddFile::Execute() void AddFile::Finish(int status) { - LOG(("FINISH ADD " LOG_S, mFile)); + LOG(("FINISH ADD " LOG_S, mRelPath.get())); // When there is an update failure and a file has been added it is removed // here since there might not be a backup to replace it. if (status && mAdded) - NS_tremove(mFile); - backup_finish(mFile, status); + NS_tremove(mFile.get()); + backup_finish(mFile.get(), mRelPath.get(), status); } class PatchFile : public Action { public: - PatchFile() : mPatchIndex(-1), buf(nullptr) { } + PatchFile() : mPatchFile(nullptr), mPatchIndex(-1), buf(nullptr) { } virtual ~PatchFile(); @@ -1386,7 +1457,8 @@ private: static int sPatchIndex; const NS_tchar *mPatchFile; - const NS_tchar *mFile; + mozilla::UniquePtr mFile; + mozilla::UniquePtr mFileRelPath; int mPatchIndex; MBSPatchHeader header; unsigned char *buf; @@ -1425,7 +1497,7 @@ PatchFile::LoadSourceFile(FILE* ofile) int rv = fstat(fileno((FILE *)ofile), &os); if (rv) { LOG(("LoadSourceFile: unable to stat destination file: " LOG_S ", " \ - "err: %d", mFile, errno)); + "err: %d", mFileRelPath.get(), errno)); return READ_ERROR; } @@ -1447,7 +1519,7 @@ PatchFile::LoadSourceFile(FILE* ofile) size_t c = fread(rb, 1, count, ofile); if (c != count) { LOG(("LoadSourceFile: error reading destination file: " LOG_S, - mFile)); + mFileRelPath.get())); return READ_ERROR; } @@ -1485,7 +1557,15 @@ PatchFile::Parse(NS_tchar *line) return PARSE_ERROR; } - mFile = get_valid_path(&line); + NS_tchar * validPath = get_valid_path(&line); + if (!validPath) { + return PARSE_ERROR; + } + + mFileRelPath = mozilla::MakeUnique(MAXPATHLEN); + NS_tstrcpy(mFileRelPath.get(), validPath); + + mFile.reset(get_full_path(validPath)); if (!mFile) { return PARSE_ERROR; } @@ -1496,7 +1576,7 @@ PatchFile::Parse(NS_tchar *line) int PatchFile::Prepare() { - LOG(("PREPARE PATCH " LOG_S, mFile)); + LOG(("PREPARE PATCH " LOG_S, mFileRelPath.get())); // extract the patch to a temporary file mPatchIndex = sPatchIndex++; @@ -1537,7 +1617,7 @@ PatchFile::Prepare() int PatchFile::Execute() { - LOG(("EXECUTE PATCH " LOG_S, mFile)); + LOG(("EXECUTE PATCH " LOG_S, mFileRelPath.get())); fseek(mPatchStream, 0, SEEK_SET); @@ -1548,20 +1628,20 @@ PatchFile::Execute() FILE *origfile = nullptr; #ifdef XP_WIN - if (NS_tstrcmp(mFile, gCallbackRelPath) == 0) { + if (NS_tstrcmp(mFileRelPath.get(), gCallbackRelPath) == 0) { // Read from the copy of the callback when patching since the callback can't // be opened for reading to prevent the application from being launched. origfile = NS_tfopen(gCallbackBackupPath, NS_T("rb")); } else { - origfile = NS_tfopen(mFile, NS_T("rb")); + origfile = NS_tfopen(mFile.get(), NS_T("rb")); } #else - origfile = NS_tfopen(mFile, NS_T("rb")); + origfile = NS_tfopen(mFile.get(), NS_T("rb")); #endif if (!origfile) { - LOG(("unable to open destination file: " LOG_S ", err: %d", mFile, - errno)); + LOG(("unable to open destination file: " LOG_S ", err: %d", + mFileRelPath.get(), errno)); return READ_ERROR; } @@ -1575,20 +1655,20 @@ PatchFile::Execute() // Rename the destination file if it exists before proceeding so it can be // used to restore the file to its original state if there is an error. struct NS_tstat_t ss; - rv = NS_tstat(mFile, &ss); + rv = NS_tstat(mFile.get(), &ss); if (rv) { - LOG(("failed to read file status info: " LOG_S ", err: %d", mFile, - errno)); + LOG(("failed to read file status info: " LOG_S ", err: %d", + mFileRelPath.get(), errno)); return READ_ERROR; } - rv = backup_create(mFile); + rv = backup_create(mFile.get()); if (rv) { return rv; } #if defined(HAVE_POSIX_FALLOCATE) - AutoFile ofile(ensure_open(mFile, NS_T("wb+"), ss.st_mode)); + AutoFile ofile(ensure_open(mFile.get(), NS_T("wb+"), ss.st_mode)); posix_fallocate(fileno((FILE *)ofile), 0, header.dlen); #elif defined(XP_WIN) bool shouldTruncate = true; @@ -1599,7 +1679,7 @@ PatchFile::Execute() // 2. _get_osfhandle and then setting the size reduced fragmentation though // not completely. There are also reports of _get_osfhandle failing on // mingw. - HANDLE hfile = CreateFileW(mFile, + HANDLE hfile = CreateFileW(mFile.get(), GENERIC_WRITE, 0, nullptr, @@ -1616,10 +1696,10 @@ PatchFile::Execute() CloseHandle(hfile); } - AutoFile ofile(ensure_open(mFile, shouldTruncate ? NS_T("wb+") : NS_T("rb+"), + AutoFile ofile(ensure_open(mFile.get(), shouldTruncate ? NS_T("wb+") : NS_T("rb+"), ss.st_mode)); #elif defined(XP_MACOSX) - AutoFile ofile(ensure_open(mFile, NS_T("wb+"), ss.st_mode)); + AutoFile ofile(ensure_open(mFile.get(), NS_T("wb+"), ss.st_mode)); // Modified code from FileUtils.cpp fstore_t store = {F_ALLOCATECONTIG, F_PEOFPOSMODE, 0, header.dlen}; // Try to get a continous chunk of disk space @@ -1634,11 +1714,12 @@ PatchFile::Execute() ftruncate(fileno((FILE *)ofile), header.dlen); } #else - AutoFile ofile(ensure_open(mFile, NS_T("wb+"), ss.st_mode)); + AutoFile ofile(ensure_open(mFile.get(), NS_T("wb+"), ss.st_mode)); #endif if (ofile == nullptr) { - LOG(("unable to create new file: " LOG_S ", err: %d", mFile, errno)); + LOG(("unable to create new file: " LOG_S ", err: %d", mFileRelPath.get(), + errno)); return WRITE_ERROR_OPEN_PATCH_FILE; } @@ -1670,23 +1751,21 @@ PatchFile::Execute() void PatchFile::Finish(int status) { - LOG(("FINISH PATCH " LOG_S, mFile)); + LOG(("FINISH PATCH " LOG_S, mFileRelPath.get())); - backup_finish(mFile, status); + backup_finish(mFile.get(), mFileRelPath.get(), status); } class AddIfFile : public AddFile { public: - AddIfFile() : mTestFile(nullptr) { } - virtual int Parse(NS_tchar *line); virtual int Prepare(); virtual int Execute(); virtual void Finish(int status); protected: - const NS_tchar *mTestFile; + mozilla::UniquePtr mTestFile; }; int @@ -1694,14 +1773,16 @@ AddIfFile::Parse(NS_tchar *line) { // format "" "" - mTestFile = get_valid_path(&line); - if (!mTestFile) + mTestFile.reset(get_full_path(get_valid_path(&line))); + if (!mTestFile) { return PARSE_ERROR; + } // consume whitespace between args NS_tchar *q = mstrtok(kQuote, &line); - if (!q) + if (!q) { return PARSE_ERROR; + } return AddFile::Parse(line); } @@ -1710,7 +1791,7 @@ int AddIfFile::Prepare() { // If the test file does not exist, then skip this action. - if (NS_taccess(mTestFile, F_OK)) { + if (NS_taccess(mTestFile.get(), F_OK)) { mTestFile = nullptr; return OK; } @@ -1739,15 +1820,13 @@ AddIfFile::Finish(int status) class AddIfNotFile : public AddFile { public: - AddIfNotFile() : mTestFile(NULL) { } - virtual int Parse(NS_tchar *line); virtual int Prepare(); virtual int Execute(); virtual void Finish(int status); protected: - const NS_tchar *mTestFile; + mozilla::UniquePtr mTestFile; }; int @@ -1755,14 +1834,16 @@ AddIfNotFile::Parse(NS_tchar *line) { // format "" "" - mTestFile = get_valid_path(&line); - if (!mTestFile) + mTestFile.reset(get_full_path(get_valid_path(&line))); + if (!mTestFile) { return PARSE_ERROR; + } // consume whitespace between args NS_tchar *q = mstrtok(kQuote, &line); - if (!q) + if (!q) { return PARSE_ERROR; + } return AddFile::Parse(line); } @@ -1771,7 +1852,7 @@ int AddIfNotFile::Prepare() { // If the test file exists, then skip this action. - if (!NS_taccess(mTestFile, F_OK)) { + if (!NS_taccess(mTestFile.get(), F_OK)) { mTestFile = NULL; return OK; } @@ -1800,15 +1881,13 @@ AddIfNotFile::Finish(int status) class PatchIfFile : public PatchFile { public: - PatchIfFile() : mTestFile(nullptr) { } - virtual int Parse(NS_tchar *line); virtual int Prepare(); // should check for patch file and for checksum here virtual int Execute(); virtual void Finish(int status); private: - const NS_tchar *mTestFile; + mozilla::UniquePtr mTestFile; }; int @@ -1816,14 +1895,16 @@ PatchIfFile::Parse(NS_tchar *line) { // format "" "" "" - mTestFile = get_valid_path(&line); - if (!mTestFile) + mTestFile.reset(get_full_path(get_valid_path(&line))); + if (!mTestFile) { return PARSE_ERROR; + } // consume whitespace between args NS_tchar *q = mstrtok(kQuote, &line); - if (!q) + if (!q) { return PARSE_ERROR; + } return PatchFile::Parse(line); } @@ -1832,7 +1913,7 @@ int PatchIfFile::Prepare() { // If the test file does not exist, then skip this action. - if (NS_taccess(mTestFile, F_OK)) { + if (NS_taccess(mTestFile.get(), F_OK)) { mTestFile = nullptr; return OK; } @@ -2515,8 +2596,7 @@ UpdateThreadFunc(void *param) if (rv && (sReplaceRequest || sStagedUpdate)) { #ifdef XP_WIN // On Windows, the current working directory of the process should be changed - // so that it's not locked. The working directory for staging an update was - // already changed earlier. + // so that it's not locked. if (sStagedUpdate) { NS_tchar sysDir[MAX_PATH + 1] = { L'\0' }; if (GetSystemDirectoryW(sysDir, MAX_PATH + 1)) { @@ -2851,21 +2931,30 @@ int NS_main(int argc, NS_tchar **argv) LOG(("WORKING DIRECTORY " LOG_S, gWorkingDirPath)); #if defined(XP_WIN) - if (sReplaceRequest || sStagedUpdate) { - NS_tchar stagedParent[MAX_PATH]; - NS_tsnprintf(stagedParent, sizeof(stagedParent)/sizeof(stagedParent[0]), + if (_wcsnicmp(gWorkingDirPath, gInstallDirPath, MAX_PATH) != 0) { + if (!sStagedUpdate && !sReplaceRequest) { + WriteStatusFile(INVALID_APPLYTO_DIR_ERROR); + LOG(("Installation directory and working directory must be the same " + "for non-staged updates. Exiting.")); + LogFinish(); + return 1; + } + + NS_tchar workingDirParent[MAX_PATH]; + NS_tsnprintf(workingDirParent, + sizeof(workingDirParent) / sizeof(workingDirParent[0]), NS_T("%s"), gWorkingDirPath); - if (!PathRemoveFileSpecW(stagedParent)) { + if (!PathRemoveFileSpecW(workingDirParent)) { WriteStatusFile(REMOVE_FILE_SPEC_ERROR); LOG(("Error calling PathRemoveFileSpecW: %d", GetLastError())); LogFinish(); return 1; } - if (_wcsnicmp(stagedParent, gInstallDirPath, MAX_PATH) != 0) { - WriteStatusFile(INVALID_STAGED_PARENT_ERROR); - LOG(("Stage and Replace requests require that the working directory " \ - "is a sub-directory of the installation directory! Exiting")); + if (_wcsnicmp(workingDirParent, gInstallDirPath, MAX_PATH) != 0) { + WriteStatusFile(INVALID_APPLYTO_DIR_STAGED_ERROR); + LOG(("The apply-to directory must be the same as or " + "a child of the installation directory! Exiting.")); LogFinish(); return 1; } @@ -2923,15 +3012,6 @@ int NS_main(int argc, NS_tchar **argv) #endif #ifdef XP_WIN - if (sReplaceRequest) { - // On Windows, the current working directory of the process should be changed - // so that it's not locked. - NS_tchar sysDir[MAX_PATH + 1] = { L'\0' }; - if (GetSystemDirectoryW(sysDir, MAX_PATH + 1)) { - NS_tchdir(sysDir); - } - } - #ifdef MOZ_MAINTENANCE_SERVICE sUsingService = EnvHasValue("MOZ_USING_SERVICE"); putenv(const_cast("MOZ_USING_SERVICE=")); @@ -3262,32 +3342,16 @@ int NS_main(int argc, NS_tchar **argv) ensure_remove_recursive(gWorkingDirPath); } if (!sReplaceRequest) { - // Change current directory to the directory where we need to apply the update. - if (NS_tchdir(gWorkingDirPath) != 0) { - // Try to create the destination directory if it doesn't exist - int rv = NS_tmkdir(gWorkingDirPath, 0755); - if (rv == OK && errno != EEXIST) { - // Try changing the current directory again - if (NS_tchdir(gWorkingDirPath) != 0) { - // OK, time to give up! + // Try to create the destination directory if it doesn't exist + int rv = NS_tmkdir(gWorkingDirPath, 0755); + if (rv != OK && errno != EEXIST) { #ifdef XP_MACOSX - if (isElevated) { - freeArguments(argc, argv); - CleanupElevatedMacUpdate(true); - } -#endif - return 1; - } - } else { - // Failed to create the directory, bail out -#ifdef XP_MACOSX - if (isElevated) { - freeArguments(argc, argv); - CleanupElevatedMacUpdate(true); - } -#endif - return 1; + if (isElevated) { + freeArguments(argc, argv); + CleanupElevatedMacUpdate(true); } +#endif + return 1; } } @@ -3318,7 +3382,7 @@ int NS_main(int argc, NS_tchar **argv) NS_tchar applyDirLongPath[MAXPATHLEN]; if (!GetLongPathNameW(gWorkingDirPath, applyDirLongPath, - sizeof(applyDirLongPath)/sizeof(applyDirLongPath[0]))) { + sizeof(applyDirLongPath) / sizeof(applyDirLongPath[0]))) { LOG(("NS_main: unable to find apply to dir: " LOG_S, gWorkingDirPath)); LogFinish(); WriteStatusFile(WRITE_ERROR_APPLY_DIR_PATH); @@ -3488,13 +3552,23 @@ int NS_main(int argc, NS_tchar **argv) } } - // DELETE_DIR is not required when staging an update. + // DELETE_DIR is not required when performing a staged update or replace + // request; it can be used during a replace request but then it doesn't + // use gDeleteDirPath. if (!sStagedUpdate && !sReplaceRequest) { // The directory to move files that are in use to on Windows. This directory - // will be deleted after the update is finished or on OS reboot using - // MoveFileEx if it contains files that are in use. - if (NS_taccess(DELETE_DIR, F_OK)) { - NS_tmkdir(DELETE_DIR, 0755); + // will be deleted after the update is finished, on OS reboot using + // MoveFileEx if it contains files that are in use, or by the post update + // process after the update finishes. On Windows when performing a normal + // update (e.g. the update is not a staged update and is not a replace + // request) gWorkingDirPath is the same as gInstallDirPath and + // gWorkingDirPath is used because it is the destination directory. + NS_tsnprintf(gDeleteDirPath, + sizeof(gDeleteDirPath) / sizeof(gDeleteDirPath[0]), + NS_T("%s/%s"), gWorkingDirPath, DELETE_DIR); + + if (NS_taccess(gDeleteDirPath, F_OK)) { + NS_tmkdir(gDeleteDirPath, 0755); } } #endif /* XP_WIN */ @@ -3524,7 +3598,7 @@ int NS_main(int argc, NS_tchar **argv) NS_tremove(gCallbackBackupPath); } - if (!sStagedUpdate && !sReplaceRequest && _wrmdir(DELETE_DIR)) { + if (!sStagedUpdate && !sReplaceRequest && _wrmdir(gDeleteDirPath)) { LOG(("NS_main: unable to remove directory: " LOG_S ", err: %d", DELETE_DIR, errno)); // The directory probably couldn't be removed due to it containing files @@ -3536,7 +3610,7 @@ int NS_main(int argc, NS_tchar **argv) // access to the HKEY_LOCAL_MACHINE registry key but this is ok since the // installer / uninstaller will delete the directory along with its contents // after an update is applied, on reinstall, and on uninstall. - if (MoveFileEx(DELETE_DIR, nullptr, MOVEFILE_DELAY_UNTIL_REBOOT)) { + if (MoveFileEx(gDeleteDirPath, nullptr, MOVEFILE_DELAY_UNTIL_REBOOT)) { LOG(("NS_main: directory will be removed on OS reboot: " LOG_S, DELETE_DIR)); } else { @@ -3743,9 +3817,9 @@ int add_dir_entries(const NS_tchar *dirpath, ActionList *list) NS_tsnprintf(searchspec, sizeof(searchspec)/sizeof(searchspec[0]), NS_T("%s*"), dirpath); - const NS_tchar *pszSpec = get_full_path(searchspec); + mozilla::UniquePtr pszSpec(get_full_path(searchspec)); - hFindFile = FindFirstFileW(pszSpec, &finddata); + hFindFile = FindFirstFileW(pszSpec.get(), &finddata); if (hFindFile != INVALID_HANDLE_VALUE) { do { // Don't process the current or parent directory. @@ -3806,24 +3880,17 @@ int add_dir_entries(const NS_tchar *dirpath, ActionList *list) int add_dir_entries(const NS_tchar *dirpath, ActionList *list) { int rv = OK; - NS_tchar searchpath[MAXPATHLEN]; NS_tchar foundpath[MAXPATHLEN]; struct { dirent dent_buffer; char chars[MAXNAMLEN]; } ent_buf; struct dirent* ent; + mozilla::UniquePtr searchpath(get_full_path(dirpath)); - - NS_tsnprintf(searchpath, sizeof(searchpath)/sizeof(searchpath[0]), NS_T("%s"), - dirpath); - // Remove the trailing slash so the paths don't contain double slashes. The - // existence of the slash has already been checked in DoUpdate. - searchpath[NS_tstrlen(searchpath) - 1] = NS_T('\0'); - - DIR* dir = opendir(searchpath); + DIR* dir = opendir(searchpath.get()); if (!dir) { - LOG(("add_dir_entries error on opendir: " LOG_S ", err: %d", searchpath, + LOG(("add_dir_entries error on opendir: " LOG_S ", err: %d", searchpath.get(), errno)); return UNEXPECTED_FILE_OPERATION_ERROR; } @@ -3834,7 +3901,7 @@ int add_dir_entries(const NS_tchar *dirpath, ActionList *list) continue; NS_tsnprintf(foundpath, sizeof(foundpath)/sizeof(foundpath[0]), - NS_T("%s%s"), dirpath, ent->d_name); + NS_T("%s%s"), searchpath.get(), ent->d_name); struct stat64 st_buf; int test = stat64(foundpath, &st_buf); if (test) { @@ -3853,7 +3920,7 @@ int add_dir_entries(const NS_tchar *dirpath, ActionList *list) } } else { // Add the file to be removed to the ActionList. - NS_tchar *quotedpath = get_quoted_path(foundpath); + NS_tchar *quotedpath = get_quoted_path(get_relative_path(foundpath)); if (!quotedpath) { closedir(dir); return PARSE_ERROR; @@ -3874,7 +3941,7 @@ int add_dir_entries(const NS_tchar *dirpath, ActionList *list) closedir(dir); // Add the directory to be removed to the ActionList. - NS_tchar *quotedpath = get_quoted_path(dirpath); + NS_tchar *quotedpath = get_quoted_path(get_relative_path(dirpath)); if (!quotedpath) return PARSE_ERROR; @@ -3898,14 +3965,12 @@ int add_dir_entries(const NS_tchar *dirpath, ActionList *list) int rv = OK; FTS *ftsdir; FTSENT *ftsdirEntry; - NS_tchar searchpath[MAXPATHLEN]; + mozilla::UniquePtr searchpath(get_full_path(dirpath)); - NS_tsnprintf(searchpath, sizeof(searchpath)/sizeof(searchpath[0]), NS_T("%s"), - dirpath); // Remove the trailing slash so the paths don't contain double slashes. The // existence of the slash has already been checked in DoUpdate. - searchpath[NS_tstrlen(searchpath) - 1] = NS_T('\0'); - char* const pathargv[] = {searchpath, nullptr}; + searchpath[NS_tstrlen(searchpath.get()) - 1] = NS_T('\0'); + char* const pathargv[] = {searchpath.get(), nullptr}; // FTS_NOCHDIR is used so relative paths from the destination directory are // returned. @@ -3935,7 +4000,7 @@ int add_dir_entries(const NS_tchar *dirpath, ActionList *list) // Add the file to be removed to the ActionList. NS_tsnprintf(foundpath, sizeof(foundpath)/sizeof(foundpath[0]), NS_T("%s"), ftsdirEntry->fts_accpath); - quotedpath = get_quoted_path(foundpath); + quotedpath = get_quoted_path(get_relative_path(foundpath)); if (!quotedpath) { rv = UPDATER_QUOTED_PATH_MEM_ERROR; break; @@ -3952,7 +4017,7 @@ int add_dir_entries(const NS_tchar *dirpath, ActionList *list) // Add the directory to be removed to the ActionList. NS_tsnprintf(foundpath, sizeof(foundpath)/sizeof(foundpath[0]), NS_T("%s/"), ftsdirEntry->fts_accpath); - quotedpath = get_quoted_path(foundpath); + quotedpath = get_quoted_path(get_relative_path(foundpath)); if (!quotedpath) { rv = UPDATER_QUOTED_PATH_MEM_ERROR; break; @@ -4070,10 +4135,14 @@ int AddPreCompleteActions(ActionList *list) } #ifdef XP_MACOSX - NS_tchar *rb = GetManifestContents(NS_T("Contents/Resources/precomplete")); + mozilla::UniquePtr manifestPath(get_full_path( + NS_T("Contents/Resources/precomplete"))); #else - NS_tchar *rb = GetManifestContents(NS_T("precomplete")); + mozilla::UniquePtr manifestPath(get_full_path( + NS_T("precomplete"))); #endif + + NS_tchar *rb = GetManifestContents(manifestPath.get()); if (rb == nullptr) { LOG(("AddPreCompleteActions: error getting contents of precomplete " \ "manifest")); From eb1cbc89c718c331accba07f26f6922725a69a65 Mon Sep 17 00:00:00 2001 From: David Anderson Date: Thu, 25 Aug 2016 10:45:16 -0700 Subject: [PATCH 008/105] Fix dangling IPDL pointer in ClientContainerLayer. (bug 1297567, r=nical) --- gfx/layers/client/ClientContainerLayer.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/gfx/layers/client/ClientContainerLayer.h b/gfx/layers/client/ClientContainerLayer.h index 75a3ba01aad4..101136685075 100644 --- a/gfx/layers/client/ClientContainerLayer.h +++ b/gfx/layers/client/ClientContainerLayer.h @@ -133,6 +133,11 @@ public: void SetSupportsComponentAlphaChildren(bool aSupports) { mSupportsComponentAlphaChildren = aSupports; } + virtual void Disconnect() + { + ClientLayer::Disconnect(); + } + protected: ClientLayerManager* ClientManager() { From f7252432407a1a67a18bf083cf6a0461ade8c798 Mon Sep 17 00:00:00 2001 From: Matt Howell Date: Thu, 25 Aug 2016 11:05:51 -0700 Subject: [PATCH 009/105] Bug 1246972 followup - Fix eslint errors; CLOSED TREE MozReview-Commit-ID: FGTFeGOqpqw --HG-- extra : rebase_source : d4bf641ba9166839b6c582f11fa194efa4d0354a --- .../update/tests/data/xpcshellUtilsAUS.js | 2 +- .../marWrongApplyToDirFailure_win.js | 78 +++++++++---------- 2 files changed, 40 insertions(+), 40 deletions(-) diff --git a/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js b/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js index 89a0e1c96b3e..a4da2aa3ac1a 100644 --- a/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js +++ b/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js @@ -1717,7 +1717,7 @@ function runUpdateUsingUpdater(aExpectedStatus, aSwitchApp, aExpectedExitValue) callbackApp.permissions = PERMS_DIRECTORY; setAppBundleModTime(); - + let args = [updatesDirPath, applyToDirPath]; if (aSwitchApp) { args[2] = gApplyToDirOverride || stageDirPath; diff --git a/toolkit/mozapps/update/tests/unit_base_updater/marWrongApplyToDirFailure_win.js b/toolkit/mozapps/update/tests/unit_base_updater/marWrongApplyToDirFailure_win.js index 86ca3feedd7e..072d67729c7f 100644 --- a/toolkit/mozapps/update/tests/unit_base_updater/marWrongApplyToDirFailure_win.js +++ b/toolkit/mozapps/update/tests/unit_base_updater/marWrongApplyToDirFailure_win.js @@ -1,39 +1,39 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -/* Test trying to use an apply-to directory different from the install - * directory, which should fail. - */ - -function run_test() { - if (!setupTestCommon()) { - return; - } - gTestFiles = gTestFilesCompleteSuccess; - gTestDirs = gTestDirsCompleteSuccess; - setTestFilesAndDirsForFailure(); - setupUpdaterTest(FILE_COMPLETE_MAR, false); -} - -/** - * Called after the call to setupUpdaterTest finishes. - */ -function setupUpdaterTestFinished() { - overrideApplyToDir(getApplyDirPath() + "/../NoSuchDir"); - // If execv is used the updater process will turn into the callback process - // and the updater's return code will be that of the callback process. - runUpdateUsingUpdater(STATE_FAILED_INVALID_APPLYTO_DIR_ERROR, false, - (USE_EXECV ? 0 : 1)); -} - -/** - * Called after the call to runUpdateUsingUpdater finishes. - */ -function runUpdateFinished() { - standardInit(); - checkPostUpdateRunningFile(false); - checkFilesAfterUpdateFailure(getApplyDirFile); - waitForFilesInUse(); -} +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +/* Test trying to use an apply-to directory different from the install + * directory, which should fail. + */ + +function run_test() { + if (!setupTestCommon()) { + return; + } + gTestFiles = gTestFilesCompleteSuccess; + gTestDirs = gTestDirsCompleteSuccess; + setTestFilesAndDirsForFailure(); + setupUpdaterTest(FILE_COMPLETE_MAR, false); +} + +/** + * Called after the call to setupUpdaterTest finishes. + */ +function setupUpdaterTestFinished() { + overrideApplyToDir(getApplyDirPath() + "/../NoSuchDir"); + // If execv is used the updater process will turn into the callback process + // and the updater's return code will be that of the callback process. + runUpdateUsingUpdater(STATE_FAILED_INVALID_APPLYTO_DIR_ERROR, false, + (USE_EXECV ? 0 : 1)); +} + +/** + * Called after the call to runUpdateUsingUpdater finishes. + */ +function runUpdateFinished() { + standardInit(); + checkPostUpdateRunningFile(false); + checkFilesAfterUpdateFailure(getApplyDirFile); + waitForFilesInUse(); +} From 9c03d71187422c8f06bb809d8d8d1c5d54a1e9e9 Mon Sep 17 00:00:00 2001 From: Sebastian Hengst Date: Thu, 25 Aug 2016 20:16:18 +0200 Subject: [PATCH 010/105] Backed out changeset dd4f2955a72f (bug 1297567) for build bustage (overriding member function). r=backout on a CLOSED TREE --- gfx/layers/client/ClientContainerLayer.h | 5 ----- 1 file changed, 5 deletions(-) diff --git a/gfx/layers/client/ClientContainerLayer.h b/gfx/layers/client/ClientContainerLayer.h index 101136685075..75a3ba01aad4 100644 --- a/gfx/layers/client/ClientContainerLayer.h +++ b/gfx/layers/client/ClientContainerLayer.h @@ -133,11 +133,6 @@ public: void SetSupportsComponentAlphaChildren(bool aSupports) { mSupportsComponentAlphaChildren = aSupports; } - virtual void Disconnect() - { - ClientLayer::Disconnect(); - } - protected: ClientLayerManager* ClientManager() { From 1f49af4fc0d86f472af171048542842504d6ee92 Mon Sep 17 00:00:00 2001 From: Wes Kocher Date: Thu, 25 Aug 2016 11:29:35 -0700 Subject: [PATCH 011/105] Backed out 2 changesets (bug 1297850) for robocop bustage a=backout CLOSED TREE Backed out changeset e83c9eb279a9 (bug 1297850) Backed out changeset 979694026137 (bug 1297850) --- gfx/layers/client/ClientLayerManager.cpp | 28 +++ gfx/layers/client/ClientLayerManager.h | 16 ++ .../base/java/org/mozilla/gecko/GeckoApp.java | 8 + .../java/org/mozilla/gecko/PrivateTab.java | 5 + .../base/java/org/mozilla/gecko/Tab.java | 41 ++++ .../base/java/org/mozilla/gecko/Tabs.java | 13 ++ .../org/mozilla/gecko/prompts/Prompt.java | 4 + .../java/org/mozilla/gecko/GeckoAppShell.java | 14 ++ .../mozilla/gecko/gfx/GeckoLayerClient.java | 213 ++++++++++++++++++ .../java/org/mozilla/gecko/gfx/LayerView.java | 36 +++ .../gecko/gfx/NativePanZoomController.java | 47 ++++ .../mozilla/gecko/gfx/PanZoomController.java | 13 ++ .../org/mozilla/gecko/gfx/PanZoomTarget.java | 1 + widget/android/AndroidBridge.cpp | 27 +++ widget/android/AndroidBridge.h | 3 + widget/android/GeneratedJNINatives.h | 6 +- widget/android/GeneratedJNIWrappers.cpp | 19 ++ widget/android/GeneratedJNIWrappers.h | 63 ++++++ widget/android/nsWindow.cpp | 19 ++ 19 files changed, 575 insertions(+), 1 deletion(-) diff --git a/gfx/layers/client/ClientLayerManager.cpp b/gfx/layers/client/ClientLayerManager.cpp index 0acc69260566..68d5d2ca48d9 100644 --- a/gfx/layers/client/ClientLayerManager.cpp +++ b/gfx/layers/client/ClientLayerManager.cpp @@ -795,6 +795,34 @@ ClientLayerManager::GetBackendName(nsAString& aName) } } +bool +ClientLayerManager::ProgressiveUpdateCallback(bool aHasPendingNewThebesContent, + FrameMetrics& aMetrics, + bool aDrawingCritical) +{ +#ifdef MOZ_WIDGET_ANDROID + MOZ_ASSERT(aMetrics.IsScrollable()); + // This is derived from the code in + // gfx/layers/ipc/CompositorBridgeParent.cpp::TransformShadowTree. + CSSToLayerScale paintScale = aMetrics.LayersPixelsPerCSSPixel().ToScaleFactor(); + const CSSRect& metricsDisplayPort = + (aDrawingCritical && !aMetrics.GetCriticalDisplayPort().IsEmpty()) ? + aMetrics.GetCriticalDisplayPort() : aMetrics.GetDisplayPort(); + LayerRect displayPort = (metricsDisplayPort + aMetrics.GetScrollOffset()) * paintScale; + + ParentLayerPoint scrollOffset; + CSSToParentLayerScale zoom; + bool ret = AndroidBridge::Bridge()->ProgressiveUpdateCallback( + aHasPendingNewThebesContent, displayPort, paintScale.scale, aDrawingCritical, + scrollOffset, zoom); + aMetrics.SetScrollOffset(scrollOffset / zoom); + aMetrics.SetZoom(CSSToParentLayerScale2D(zoom)); + return ret; +#else + return false; +#endif +} + bool ClientLayerManager::AsyncPanZoomEnabled() const { diff --git a/gfx/layers/client/ClientLayerManager.h b/gfx/layers/client/ClientLayerManager.h index ad9f9ea71ea0..6fd1d8ca1304 100644 --- a/gfx/layers/client/ClientLayerManager.h +++ b/gfx/layers/client/ClientLayerManager.h @@ -155,6 +155,22 @@ public: // Disable component alpha layers with the software compositor. virtual bool ShouldAvoidComponentAlphaLayers() override { return !IsCompositingCheap(); } + /** + * Called for each iteration of a progressive tile update. Updates + * aMetrics with the current scroll offset and scale being used to composite + * the primary scrollable layer in this manager, to determine what area + * intersects with the target composition bounds. + * aDrawingCritical will be true if the current drawing operation is using + * the critical displayport. + * Returns true if the update should continue, or false if it should be + * cancelled. + * This is only called if gfxPlatform::UseProgressiveTilePainting() returns + * true. + */ + bool ProgressiveUpdateCallback(bool aHasPendingNewThebesContent, + FrameMetrics& aMetrics, + bool aDrawingCritical); + bool InConstruction() { return mPhase == PHASE_CONSTRUCTION; } #ifdef DEBUG bool InDrawing() { return mPhase == PHASE_DRAWING; } diff --git a/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java b/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java index 19688e72360e..7f037d8d735c 100644 --- a/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java +++ b/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java @@ -367,6 +367,14 @@ public abstract class GeckoApp mFormAssistPopup.hide(); break; + case LOADED: + // Sync up the layer view and the tab if the tab is + // currently displayed. + LayerView layerView = mLayerView; + if (layerView != null && Tabs.getInstance().isSelectedTab(tab)) + layerView.setBackgroundColor(tab.getBackgroundColor()); + break; + case DESKTOP_MODE_CHANGE: if (Tabs.getInstance().isSelectedTab(tab)) invalidateOptionsMenu(); diff --git a/mobile/android/base/java/org/mozilla/gecko/PrivateTab.java b/mobile/android/base/java/org/mozilla/gecko/PrivateTab.java index f3a9bcb25cb0..cca46f17f0b2 100644 --- a/mobile/android/base/java/org/mozilla/gecko/PrivateTab.java +++ b/mobile/android/base/java/org/mozilla/gecko/PrivateTab.java @@ -13,6 +13,11 @@ import org.mozilla.gecko.db.BrowserDB; public class PrivateTab extends Tab { public PrivateTab(Context context, int id, String url, boolean external, int parentId, String title) { super(context, id, url, external, parentId, title); + + // Init background to private_toolbar_grey to ensure flicker-free + // private tab creation. Page loads will reset it to white as expected. + final int bgColor = ContextCompat.getColor(context, R.color.tabs_tray_grey_pressed); + setBackgroundColor(bgColor); } @Override diff --git a/mobile/android/base/java/org/mozilla/gecko/Tab.java b/mobile/android/base/java/org/mozilla/gecko/Tab.java index 425f7083b83a..e033915f9f7d 100644 --- a/mobile/android/base/java/org/mozilla/gecko/Tab.java +++ b/mobile/android/base/java/org/mozilla/gecko/Tab.java @@ -74,6 +74,7 @@ public class Tab { private ZoomConstraints mZoomConstraints; private boolean mIsRTL; private final ArrayList mPluginViews; + private int mBackgroundColor; private int mState; private Bitmap mThumbnailBitmap; private boolean mDesktopMode; @@ -115,6 +116,8 @@ public class Tab { public static final int LOAD_PROGRESS_LOADED = 80; public static final int LOAD_PROGRESS_STOP = 100; + private static final int DEFAULT_BACKGROUND_COLOR = Color.WHITE; + public enum ErrorType { CERT_ERROR, // Pages with certificate problems BLOCKED, // Pages blocked for phishing or malware warnings @@ -140,6 +143,11 @@ public class Tab { mState = shouldShowProgress(url) ? STATE_LOADING : STATE_SUCCESS; mLoadProgress = LOAD_PROGRESS_INIT; + // At startup, the background is set to a color specified by LayerView + // when the LayerView is created. Shortly after, this background color + // will be used before the tab's content is shown. + mBackgroundColor = DEFAULT_BACKGROUND_COLOR; + updateBookmark(); } @@ -690,6 +698,7 @@ public class Tab { setSiteLogins(null); setZoomConstraints(new ZoomConstraints(true)); setHasTouchListeners(false); + setBackgroundColor(DEFAULT_BACKGROUND_COLOR); setErrorType(ErrorType.NONE); setLoadProgressIfLoading(LOAD_PROGRESS_LOCATION_CHANGE); @@ -794,6 +803,38 @@ public class Tab { return mPluginViews.toArray(new View[mPluginViews.size()]); } + public int getBackgroundColor() { + return mBackgroundColor; + } + + /** Sets a new color for the background. */ + public void setBackgroundColor(int color) { + mBackgroundColor = color; + } + + /** Parses and sets a new color for the background. */ + public void setBackgroundColor(String newColor) { + setBackgroundColor(parseColorFromGecko(newColor)); + } + + // Parses a color from an RGB triple of the form "rgb([0-9]+, [0-9]+, [0-9]+)". If the color + // cannot be parsed, returns white. + private static int parseColorFromGecko(String string) { + if (sColorPattern == null) { + sColorPattern = Pattern.compile("rgb\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)"); + } + + Matcher matcher = sColorPattern.matcher(string); + if (!matcher.matches()) { + return Color.WHITE; + } + + int r = Integer.parseInt(matcher.group(1)); + int g = Integer.parseInt(matcher.group(2)); + int b = Integer.parseInt(matcher.group(3)); + return Color.rgb(r, g, b); + } + public void setDesktopMode(boolean enabled) { mDesktopMode = enabled; } diff --git a/mobile/android/base/java/org/mozilla/gecko/Tabs.java b/mobile/android/base/java/org/mozilla/gecko/Tabs.java index 2c7451048924..e4b80342639a 100644 --- a/mobile/android/base/java/org/mozilla/gecko/Tabs.java +++ b/mobile/android/base/java/org/mozilla/gecko/Tabs.java @@ -111,6 +111,7 @@ public class Tabs implements GeckoEventListener { "Content:StateChange", "Content:LoadError", "Content:PageShow", + "DOMContentLoaded", "DOMTitleChanged", "Link:Favicon", "Link:Feed", @@ -517,6 +518,18 @@ public class Tabs implements GeckoEventListener { tab.setLoadedFromCache(message.getBoolean("fromCache")); tab.updateUserRequested(message.getString("userRequested")); notifyListeners(tab, TabEvents.PAGE_SHOW); + } else if (event.equals("DOMContentLoaded")) { + tab.handleContentLoaded(); + String backgroundColor = message.getString("bgColor"); + if (backgroundColor != null) { + tab.setBackgroundColor(backgroundColor); + } else { + // Default to white if no color is given + tab.setBackgroundColor(Color.WHITE); + } + tab.setErrorType(message.optString("errorType")); + tab.setMetadata(message.optJSONObject("metadata")); + notifyListeners(tab, Tabs.TabEvents.LOADED); } else if (event.equals("DOMTitleChanged")) { tab.updateTitle(message.getString("title")); } else if (event.equals("Link:Favicon")) { diff --git a/mobile/android/base/java/org/mozilla/gecko/prompts/Prompt.java b/mobile/android/base/java/org/mozilla/gecko/prompts/Prompt.java index 11121b2cce7d..401c9a999174 100644 --- a/mobile/android/base/java/org/mozilla/gecko/prompts/Prompt.java +++ b/mobile/android/base/java/org/mozilla/gecko/prompts/Prompt.java @@ -179,6 +179,10 @@ public class Prompt implements OnClickListener, OnCancelListener, OnItemClickLis private void create(String title, String text, PromptListItem[] listItems, int choiceMode) throws IllegalStateException { + final LayerView view = GeckoAppShell.getLayerView(); + if (view != null) { + view.abortPanning(); + } AlertDialog.Builder builder = new AlertDialog.Builder(mContext); if (!TextUtils.isEmpty(title)) { diff --git a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoAppShell.java b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoAppShell.java index 3e256db3beef..8d3913873f91 100644 --- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoAppShell.java +++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/GeckoAppShell.java @@ -1143,6 +1143,20 @@ public class GeckoAppShell }); } + @WrapForJNI(calledFrom = "gecko") + public static void notifyDefaultPrevented(final boolean defaultPrevented) { + ThreadUtils.postToUiThread(new Runnable() { + @Override + public void run() { + LayerView view = getLayerView(); + PanZoomController controller = (view == null ? null : view.getPanZoomController()); + if (controller != null) { + controller.notifyDefaultActionPrevented(defaultPrevented); + } + } + }); + } + @WrapForJNI(calledFrom = "gecko") public static boolean isNetworkLinkUp() { ConnectivityManager cm = (ConnectivityManager) diff --git a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/GeckoLayerClient.java b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/GeckoLayerClient.java index 6786b7a683e7..696ee6807733 100644 --- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/GeckoLayerClient.java +++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/GeckoLayerClient.java @@ -89,6 +89,8 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget * fields. */ private volatile ImmutableViewportMetrics mViewportMetrics; + private ZoomConstraints mZoomConstraints; + private volatile boolean mGeckoIsReady; private final PanZoomController mPanZoomController; @@ -123,8 +125,11 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); mViewportMetrics = new ImmutableViewportMetrics(displayMetrics) .setViewportSize(view.getWidth(), view.getHeight()); + mZoomConstraints = new ZoomConstraints(false); + Tab tab = Tabs.getInstance().getSelectedTab(); if (tab != null) { + mZoomConstraints = tab.getZoomConstraints(); mViewportMetrics = mViewportMetrics.setIsRTL(tab.getIsRTL()); } @@ -178,6 +183,24 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget mGeckoIsReady = false; } + /** + * Returns true if this client is fine with performing a redraw operation or false if it + * would prefer that the action didn't take place. + */ + private boolean getRedrawHint() { + if (mForceRedraw) { + mForceRedraw = false; + return true; + } + + if (!mPanZoomController.getRedrawHint()) { + return false; + } + + return DisplayPortCalculator.aboutToCheckerboard(mViewportMetrics, + mPanZoomController.getVelocityVector(), mDisplayPort); + } + public LayerView getView() { return mView; } @@ -295,11 +318,24 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget post(new Runnable() { @Override public void run() { + mPanZoomController.pageRectUpdated(); mView.requestRender(); } }); } + /** Aborts any pan/zoom animation that is currently in progress. */ + private void abortPanZoomAnimation() { + if (mPanZoomController != null) { + post(new Runnable() { + @Override + public void run() { + mPanZoomController.abortAnimation(); + } + }); + } + } + /** * The different types of Viewport messages handled. All viewport events * expect a display-port to be returned, but can handle one not being @@ -310,6 +346,57 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget PAGE_SIZE // The viewport's page-size has changed } + /** Viewport message handler. */ + private DisplayPortMetrics handleViewportMessage(ImmutableViewportMetrics messageMetrics, ViewportMessageType type) { + synchronized (getLock()) { + ImmutableViewportMetrics newMetrics; + ImmutableViewportMetrics oldMetrics = getViewportMetrics(); + + switch (type) { + default: + case UPDATE: + // Keep the old viewport size + newMetrics = messageMetrics.setViewportSize(oldMetrics.viewportRectWidth, oldMetrics.viewportRectHeight); + if (mToolbarAnimator.isResizing()) { + // If we're in the middle of a resize, we don't want to clobber + // the scroll offset, so grab the one from the oldMetrics and + // keep using that. We also don't want to abort animations, + // because at that point we're guaranteed to not be animating + // anyway, and calling abortPanZoomAnimation has a nasty + // side-effect of clmaping and clobbering the metrics, which + // we don't want here. + newMetrics = newMetrics.setViewportOrigin(oldMetrics.viewportRectLeft, oldMetrics.viewportRectTop); + break; + } + if (!oldMetrics.fuzzyEquals(newMetrics)) { + abortPanZoomAnimation(); + } + break; + case PAGE_SIZE: + // adjust the page dimensions to account for differences in zoom + // between the rendered content (which is what Gecko tells us) + // and our zoom level (which may have diverged). + float scaleFactor = oldMetrics.zoomFactor / messageMetrics.zoomFactor; + newMetrics = oldMetrics.setPageRect(RectUtils.scale(messageMetrics.getPageRect(), scaleFactor), messageMetrics.getCssPageRect()); + break; + } + + // Update the Gecko-side viewport metrics. Make sure to do this + // before modifying the metrics below. + final ImmutableViewportMetrics geckoMetrics = newMetrics.clamp(); + post(new Runnable() { + @Override + public void run() { + mGeckoViewport = geckoMetrics; + } + }); + + setViewportMetrics(newMetrics, type == ViewportMessageType.UPDATE); + mDisplayPort = DisplayPortCalculator.calculate(getViewportMetrics(), null); + } + return mDisplayPort; + } + @WrapForJNI(calledFrom = "gecko") void contentDocumentChanged() { mContentDocumentIsDisplayed = false; @@ -320,6 +407,112 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget return mContentDocumentIsDisplayed; } + // This is called on the Gecko thread to determine if we're still interested + // in the update of this display-port to continue. We can return true here + // to abort the current update and continue with any subsequent ones. This + // is useful for slow-to-render pages when the display-port starts lagging + // behind enough that continuing to draw it is wasted effort. + @WrapForJNI + public ProgressiveUpdateData progressiveUpdateCallback(boolean aHasPendingNewThebesContent, + float x, float y, float width, float height, + float resolution, boolean lowPrecision) { + // Reset the checkerboard risk flag when switching to low precision + // rendering. + if (lowPrecision && !mLastProgressiveUpdateWasLowPrecision) { + // Skip low precision rendering until we're at risk of checkerboarding. + if (!mProgressiveUpdateWasInDanger) { + mProgressiveUpdateData.abort = true; + return mProgressiveUpdateData; + } + mProgressiveUpdateWasInDanger = false; + } + mLastProgressiveUpdateWasLowPrecision = lowPrecision; + + // Grab a local copy of the last display-port sent to Gecko and the + // current viewport metrics to avoid races when accessing them. + DisplayPortMetrics displayPort = mDisplayPort; + ImmutableViewportMetrics viewportMetrics = mViewportMetrics; + mProgressiveUpdateData.setViewport(viewportMetrics); + mProgressiveUpdateData.abort = false; + + // Always abort updates if the resolution has changed. There's no use + // in drawing at the incorrect resolution. + if (!FloatUtils.fuzzyEquals(resolution, viewportMetrics.zoomFactor)) { + Log.d(LOGTAG, "Aborting draw due to resolution change: " + resolution + " != " + viewportMetrics.zoomFactor); + mProgressiveUpdateData.abort = true; + return mProgressiveUpdateData; + } + + // Store the high precision displayport for comparison when doing low + // precision updates. + if (!lowPrecision) { + if (!FloatUtils.fuzzyEquals(resolution, mProgressiveUpdateDisplayPort.resolution) || + !FloatUtils.fuzzyEquals(x, mProgressiveUpdateDisplayPort.getLeft()) || + !FloatUtils.fuzzyEquals(y, mProgressiveUpdateDisplayPort.getTop()) || + !FloatUtils.fuzzyEquals(x + width, mProgressiveUpdateDisplayPort.getRight()) || + !FloatUtils.fuzzyEquals(y + height, mProgressiveUpdateDisplayPort.getBottom())) { + mProgressiveUpdateDisplayPort = + new DisplayPortMetrics(x, y, x + width, y + height, resolution); + } + } + + // If we're not doing low precision draws and we're about to + // checkerboard, enable low precision drawing. + if (!lowPrecision && !mProgressiveUpdateWasInDanger) { + if (DisplayPortCalculator.aboutToCheckerboard(viewportMetrics, + mPanZoomController.getVelocityVector(), mProgressiveUpdateDisplayPort)) { + mProgressiveUpdateWasInDanger = true; + } + } + + // XXX All sorts of rounding happens inside Gecko that becomes hard to + // account exactly for. Given we align the display-port to tile + // boundaries (and so they rarely vary by sub-pixel amounts), just + // check that values are within a couple of pixels of the + // display-port bounds. + + // Never abort drawing if we can't be sure we've sent a more recent + // display-port. If we abort updating when we shouldn't, we can end up + // with blank regions on the screen and we open up the risk of entering + // an endless updating cycle. + if (Math.abs(displayPort.getLeft() - mProgressiveUpdateDisplayPort.getLeft()) <= 2 && + Math.abs(displayPort.getTop() - mProgressiveUpdateDisplayPort.getTop()) <= 2 && + Math.abs(displayPort.getBottom() - mProgressiveUpdateDisplayPort.getBottom()) <= 2 && + Math.abs(displayPort.getRight() - mProgressiveUpdateDisplayPort.getRight()) <= 2) { + return mProgressiveUpdateData; + } + + // Abort updates when the display-port no longer contains the visible + // area of the page (that is, the viewport cropped by the page + // boundaries). + // XXX This makes the assumption that we never let the visible area of + // the page fall outside of the display-port. + if (Math.max(viewportMetrics.viewportRectLeft, viewportMetrics.pageRectLeft) + 1 < x || + Math.max(viewportMetrics.viewportRectTop, viewportMetrics.pageRectTop) + 1 < y || + Math.min(viewportMetrics.viewportRectRight(), viewportMetrics.pageRectRight) - 1 > x + width || + Math.min(viewportMetrics.viewportRectBottom(), viewportMetrics.pageRectBottom) - 1 > y + height) { + Log.d(LOGTAG, "Aborting update due to viewport not in display-port"); + mProgressiveUpdateData.abort = true; + + // Enable low-precision drawing, as we're likely to be in danger if + // this situation has been encountered. + mProgressiveUpdateWasInDanger = true; + + return mProgressiveUpdateData; + } + + // Abort drawing stale low-precision content if there's a more recent + // display-port in the pipeline. + if (lowPrecision && !aHasPendingNewThebesContent) { + mProgressiveUpdateData.abort = true; + } + return mProgressiveUpdateData; + } + + void setZoomConstraints(ZoomConstraints constraints) { + mZoomConstraints = constraints; + } + void setIsRTL(boolean aIsRTL) { synchronized (getLock()) { ImmutableViewportMetrics newMetrics = getViewportMetrics().setIsRTL(aIsRTL); @@ -362,6 +555,20 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget setViewportMetrics(newMetrics); + if (tab != null) { + mView.setBackgroundColor(tab.getBackgroundColor()); + setZoomConstraints(tab.getZoomConstraints()); + } + + // At this point, we have just switched to displaying a different document than we + // we previously displaying. This means we need to abort any panning/zooming animations + // that are in progress and send an updated display port request to browser.js as soon + // as possible. The call to PanZoomController.abortAnimation accomplishes this by calling the + // forceRedraw function, which sends the viewport to gecko. The display port request is + // actually a full viewport update, which is fine because if browser.js has somehow moved to + // be out of sync with this first-paint viewport, then we force them back in sync. + abortPanZoomAnimation(); + // Indicate that the document is about to be composited so the // LayerView background can be removed. if (mView.getPaintState() == LayerView.PAINT_START) { @@ -705,6 +912,12 @@ class GeckoLayerClient implements LayerView.Listener, PanZoomTarget return mViewportMetrics; } + /** Implementation of PanZoomTarget */ + @Override + public ZoomConstraints getZoomConstraints() { + return mZoomConstraints; + } + /** Implementation of PanZoomTarget */ @Override public FullScreenState getFullScreenState() { diff --git a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/LayerView.java b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/LayerView.java index 1852b93e5148..97c7fe2bfc53 100644 --- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/LayerView.java +++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/LayerView.java @@ -55,6 +55,7 @@ public class LayerView extends ScrollView implements Tabs.OnTabsChangedListener private LayerRenderer mRenderer; /* Must be a PAINT_xxx constant */ private int mPaintState; + private int mBackgroundColor; private FullScreenState mFullScreenState; private SurfaceView mSurfaceView; @@ -170,6 +171,7 @@ public class LayerView extends ScrollView implements Tabs.OnTabsChangedListener super(context, attrs); mPaintState = PAINT_START; + mBackgroundColor = Color.WHITE; mFullScreenState = FullScreenState.NONE; if (Versions.feature14Plus) { @@ -375,6 +377,12 @@ public class LayerView extends ScrollView implements Tabs.OnTabsChangedListener return mLayerClient.getViewportMetrics(); } + public void abortPanning() { + if (mPanZoomController != null) { + mPanZoomController.abortPanning(); + } + } + public PointF convertViewPointToLayerPoint(PointF viewPoint) { return mLayerClient.convertViewPointToLayerPoint(viewPoint); } @@ -383,16 +391,43 @@ public class LayerView extends ScrollView implements Tabs.OnTabsChangedListener return mLayerClient.getMatrixForLayerRectToViewRect(); } + int getBackgroundColor() { + return mBackgroundColor; + } + + @Override + public void setBackgroundColor(int newColor) { + mBackgroundColor = newColor; + requestRender(); + } + void setSurfaceBackgroundColor(int newColor) { if (mSurfaceView != null) { mSurfaceView.setBackgroundColor(newColor); } } + public void setZoomConstraints(ZoomConstraints constraints) { + mLayerClient.setZoomConstraints(constraints); + } + public void setIsRTL(boolean aIsRTL) { mLayerClient.setIsRTL(aIsRTL); } + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (!mLayerClient.isGeckoReady()) { + // If gecko isn't loaded yet, don't try sending events to the + // native code because it's just going to crash + return true; + } + if (mPanZoomController != null && mPanZoomController.onKeyEvent(event)) { + return true; + } + return false; + } + public void requestRender() { if (mCompositorCreated) { mCompositor.syncInvalidateAndScheduleComposite(); @@ -760,6 +795,7 @@ public class LayerView extends ScrollView implements Tabs.OnTabsChangedListener @Override public void onTabChanged(Tab tab, Tabs.TabEvents msg, String data) { if (msg == Tabs.TabEvents.VIEWPORT_CHANGE && Tabs.getInstance().isSelectedTab(tab) && mLayerClient != null) { + setZoomConstraints(tab.getZoomConstraints()); setIsRTL(tab.getIsRTL()); } } diff --git a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/NativePanZoomController.java b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/NativePanZoomController.java index 2db0d1ac1619..c733bd1894a1 100644 --- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/NativePanZoomController.java +++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/NativePanZoomController.java @@ -190,11 +190,58 @@ class NativePanZoomController extends JNIObject implements PanZoomController { } } + @Override + public boolean onKeyEvent(KeyEvent event) { + // FIXME implement this + return false; + } + @Override public void onMotionEventVelocity(final long aEventTime, final float aSpeedY) { handleMotionEventVelocity(aEventTime, aSpeedY); } + @Override + public PointF getVelocityVector() { + // FIXME implement this + return new PointF(0, 0); + } + + @Override + public void pageRectUpdated() { + // no-op in APZC, I think + } + + @Override + public void abortPanning() { + // no-op in APZC, I think + } + + @Override + public void notifyDefaultActionPrevented(boolean prevented) { + // no-op: This could get called if accessibility is enabled and the events + // are sent to Gecko directly without going through APZ. In this case + // we just want to ignore this callback. + } + + @WrapForJNI(stubName = "AbortAnimation", calledFrom = "ui") + private native void nativeAbortAnimation(); + + @Override // PanZoomController + public void abortAnimation() + { + if (!mDestroyed) { + nativeAbortAnimation(); + } + } + + @Override // PanZoomController + public boolean getRedrawHint() + { + // FIXME implement this + return true; + } + @Override @WrapForJNI(calledFrom = "ui") // PanZoomController public void destroy() { if (mDestroyed || !mTarget.isGeckoReady()) { diff --git a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/PanZoomController.java b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/PanZoomController.java index be999729d9a4..d0ca251e0e24 100644 --- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/PanZoomController.java +++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/PanZoomController.java @@ -14,6 +14,10 @@ import android.view.MotionEvent; import android.view.View; public interface PanZoomController { + // The distance the user has to pan before we recognize it as such (e.g. to avoid 1-pixel pans + // between the touch-down and touch-up of a click). In units of density-independent pixels. + public static final float PAN_THRESHOLD = 1 / 16f * GeckoAppShell.getDpi(); + // Threshold for sending touch move events to content public static final float CLICK_THRESHOLD = 1 / 50f * GeckoAppShell.getDpi(); @@ -27,7 +31,16 @@ public interface PanZoomController { public boolean onTouchEvent(MotionEvent event); public boolean onMotionEvent(MotionEvent event); + public boolean onKeyEvent(KeyEvent event); public void onMotionEventVelocity(final long aEventTime, final float aSpeedY); + public void notifyDefaultActionPrevented(boolean prevented); + + public boolean getRedrawHint(); + public PointF getVelocityVector(); + + public void pageRectUpdated(); + public void abortPanning(); + public void abortAnimation(); public void setOverscrollHandler(final Overscroll controller); diff --git a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/PanZoomTarget.java b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/PanZoomTarget.java index f3e7231aba6c..7d5b8b1eab4d 100644 --- a/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/PanZoomTarget.java +++ b/mobile/android/geckoview/src/main/java/org/mozilla/gecko/gfx/PanZoomTarget.java @@ -12,6 +12,7 @@ import android.graphics.PointF; public interface PanZoomTarget { public ImmutableViewportMetrics getViewportMetrics(); + public ZoomConstraints getZoomConstraints(); public FullScreenState getFullScreenState(); public PointF getVisibleEndOfLayerView(); diff --git a/widget/android/AndroidBridge.cpp b/widget/android/AndroidBridge.cpp index 3d393564a4b7..53440efb71fc 100644 --- a/widget/android/AndroidBridge.cpp +++ b/widget/android/AndroidBridge.cpp @@ -1402,6 +1402,33 @@ AndroidBridge::IsContentDocumentDisplayed() return mLayerClient->IsContentDocumentDisplayed(); } +bool +AndroidBridge::ProgressiveUpdateCallback(bool aHasPendingNewThebesContent, + const LayerRect& aDisplayPort, float aDisplayResolution, + bool aDrawingCritical, ParentLayerPoint& aScrollOffset, + CSSToParentLayerScale& aZoom) +{ + if (!mLayerClient) { + ALOG_BRIDGE("Exceptional Exit: %s", __PRETTY_FUNCTION__); + return false; + } + + ProgressiveUpdateData::LocalRef progressiveUpdateData = + mLayerClient->ProgressiveUpdateCallback(aHasPendingNewThebesContent, + (float)aDisplayPort.x, + (float)aDisplayPort.y, + (float)aDisplayPort.width, + (float)aDisplayPort.height, + aDisplayResolution, + !aDrawingCritical); + + aScrollOffset.x = progressiveUpdateData->X(); + aScrollOffset.y = progressiveUpdateData->Y(); + aZoom.scale = progressiveUpdateData->Scale(); + + return progressiveUpdateData->Abort(); +} + class AndroidBridge::DelayedTask { using TimeStamp = mozilla::TimeStamp; diff --git a/widget/android/AndroidBridge.h b/widget/android/AndroidBridge.h index f66724b28c42..14958c716459 100644 --- a/widget/android/AndroidBridge.h +++ b/widget/android/AndroidBridge.h @@ -151,6 +151,9 @@ public: void ContentDocumentChanged(); bool IsContentDocumentDisplayed(); + bool ProgressiveUpdateCallback(bool aHasPendingNewThebesContent, const LayerRect& aDisplayPort, float aDisplayResolution, bool aDrawingCritical, + mozilla::ParentLayerPoint& aScrollOffset, mozilla::CSSToParentLayerScale& aZoom); + void SetLayerClient(java::GeckoLayerClient::Param jobj); const java::GeckoLayerClient::Ref& GetLayerClient() { return mLayerClient; } diff --git a/widget/android/GeneratedJNINatives.h b/widget/android/GeneratedJNINatives.h index 88921209b288..fe1cad852851 100644 --- a/widget/android/GeneratedJNINatives.h +++ b/widget/android/GeneratedJNINatives.h @@ -541,7 +541,7 @@ template class NativePanZoomController::Natives : public mozilla::jni::NativeImpl { public: - static const JNINativeMethod methods[7]; + static const JNINativeMethod methods[8]; }; template @@ -571,6 +571,10 @@ const JNINativeMethod NativePanZoomController::Natives::methods[] = { mozilla::jni::NativeStub ::template Wrap<&Impl::HandleScrollEvent>), + mozilla::jni::MakeNativeMethod( + mozilla::jni::NativeStub + ::template Wrap<&Impl::AbortAnimation>), + mozilla::jni::MakeNativeMethod( mozilla::jni::NativeStub ::template Wrap<&Impl::SetIsLongpressEnabled>) diff --git a/widget/android/GeneratedJNIWrappers.cpp b/widget/android/GeneratedJNIWrappers.cpp index f29fe54b9f58..4bf3ae38650f 100644 --- a/widget/android/GeneratedJNIWrappers.cpp +++ b/widget/android/GeneratedJNIWrappers.cpp @@ -588,6 +588,14 @@ constexpr char GeckoAppShell::NotifyObservers_t::signature[]; constexpr char GeckoAppShell::NotifyAlertListener_t::name[]; constexpr char GeckoAppShell::NotifyAlertListener_t::signature[]; +constexpr char GeckoAppShell::NotifyDefaultPrevented_t::name[]; +constexpr char GeckoAppShell::NotifyDefaultPrevented_t::signature[]; + +auto GeckoAppShell::NotifyDefaultPrevented(bool a0) -> void +{ + return mozilla::jni::Method::Call(GeckoAppShell::Context(), nullptr, a0); +} + constexpr char GeckoAppShell::NotifyUriVisited_t::name[]; constexpr char GeckoAppShell::NotifyUriVisited_t::signature[]; @@ -1300,6 +1308,14 @@ auto GeckoLayerClient::OnGeckoReady() const -> void return mozilla::jni::Method::Call(GeckoLayerClient::mCtx, nullptr); } +constexpr char GeckoLayerClient::ProgressiveUpdateCallback_t::name[]; +constexpr char GeckoLayerClient::ProgressiveUpdateCallback_t::signature[]; + +auto GeckoLayerClient::ProgressiveUpdateCallback(bool a0, float a1, float a2, float a3, float a4, float a5, bool a6) const -> mozilla::jni::Object::LocalRef +{ + return mozilla::jni::Method::Call(GeckoLayerClient::mCtx, nullptr, a0, a1, a2, a3, a4, a5, a6); +} + constexpr char GeckoLayerClient::SetFirstPaintViewport_t::name[]; constexpr char GeckoLayerClient::SetFirstPaintViewport_t::signature[]; @@ -1490,6 +1506,9 @@ constexpr char NativePanZoomController::HandleMouseEvent_t::signature[]; constexpr char NativePanZoomController::HandleScrollEvent_t::name[]; constexpr char NativePanZoomController::HandleScrollEvent_t::signature[]; +constexpr char NativePanZoomController::AbortAnimation_t::name[]; +constexpr char NativePanZoomController::AbortAnimation_t::signature[]; + constexpr char NativePanZoomController::SetIsLongpressEnabled_t::name[]; constexpr char NativePanZoomController::SetIsLongpressEnabled_t::signature[]; diff --git a/widget/android/GeneratedJNIWrappers.h b/widget/android/GeneratedJNIWrappers.h index 202e325a35be..e52b1ac85e16 100644 --- a/widget/android/GeneratedJNIWrappers.h +++ b/widget/android/GeneratedJNIWrappers.h @@ -1571,6 +1571,26 @@ public: mozilla::jni::DispatchTarget::GECKO; }; + struct NotifyDefaultPrevented_t { + typedef GeckoAppShell Owner; + typedef void ReturnType; + typedef void SetterType; + typedef mozilla::jni::Args< + bool> Args; + static constexpr char name[] = "notifyDefaultPrevented"; + static constexpr char signature[] = + "(Z)V"; + static const bool isStatic = true; + static const mozilla::jni::ExceptionMode exceptionMode = + mozilla::jni::ExceptionMode::ABORT; + static const mozilla::jni::CallingThread callingThread = + mozilla::jni::CallingThread::GECKO; + static const mozilla::jni::DispatchTarget dispatchTarget = + mozilla::jni::DispatchTarget::CURRENT; + }; + + static auto NotifyDefaultPrevented(bool) -> void; + struct NotifyUriVisited_t { typedef GeckoAppShell Owner; typedef void ReturnType; @@ -4238,6 +4258,32 @@ public: auto OnGeckoReady() const -> void; + struct ProgressiveUpdateCallback_t { + typedef GeckoLayerClient Owner; + typedef mozilla::jni::Object::LocalRef ReturnType; + typedef mozilla::jni::Object::Param SetterType; + typedef mozilla::jni::Args< + bool, + float, + float, + float, + float, + float, + bool> Args; + static constexpr char name[] = "progressiveUpdateCallback"; + static constexpr char signature[] = + "(ZFFFFFZ)Lorg/mozilla/gecko/gfx/ProgressiveUpdateData;"; + static const bool isStatic = false; + static const mozilla::jni::ExceptionMode exceptionMode = + mozilla::jni::ExceptionMode::ABORT; + static const mozilla::jni::CallingThread callingThread = + mozilla::jni::CallingThread::ANY; + static const mozilla::jni::DispatchTarget dispatchTarget = + mozilla::jni::DispatchTarget::CURRENT; + }; + + auto ProgressiveUpdateCallback(bool, float, float, float, float, float, bool) const -> mozilla::jni::Object::LocalRef; + struct SetFirstPaintViewport_t { typedef GeckoLayerClient Owner; typedef void ReturnType; @@ -4934,6 +4980,23 @@ public: mozilla::jni::DispatchTarget::CURRENT; }; + struct AbortAnimation_t { + typedef NativePanZoomController Owner; + typedef void ReturnType; + typedef void SetterType; + typedef mozilla::jni::Args<> Args; + static constexpr char name[] = "nativeAbortAnimation"; + static constexpr char signature[] = + "()V"; + static const bool isStatic = false; + static const mozilla::jni::ExceptionMode exceptionMode = + mozilla::jni::ExceptionMode::ABORT; + static const mozilla::jni::CallingThread callingThread = + mozilla::jni::CallingThread::UI; + static const mozilla::jni::DispatchTarget dispatchTarget = + mozilla::jni::DispatchTarget::CURRENT; + }; + struct SetIsLongpressEnabled_t { typedef NativePanZoomController Owner; typedef void ReturnType; diff --git a/widget/android/nsWindow.cpp b/widget/android/nsWindow.cpp index e7f6b6328a60..c603941a6aea 100644 --- a/widget/android/nsWindow.cpp +++ b/widget/android/nsWindow.cpp @@ -537,6 +537,25 @@ public: } public: + void AbortAnimation() + { + MOZ_ASSERT(AndroidBridge::IsJavaUiThread()); + + RefPtr controller; + RefPtr compositor; + + if (LockedWindowPtr window{mWindow}) { + controller = window->mAPZC; + compositor = window->GetCompositorBridgeParent(); + } + + if (controller && compositor) { + // TODO: Pass in correct values for presShellId and viewId. + controller->CancelAnimation(ScrollableLayerGuid( + compositor->RootLayerTreeId(), 0, 0)); + } + } + void AdjustScrollForSurfaceShift(float aX, float aY) { MOZ_ASSERT(AndroidBridge::IsJavaUiThread()); From 0de02db8322567aa8d5e97caf23cf0f25d8b2c78 Mon Sep 17 00:00:00 2001 From: Lee Salzman Date: Thu, 25 Aug 2016 14:27:24 -0400 Subject: [PATCH 012/105] Bug 1297201 - apply offset after pattern matrix in DrawTargetSkia::MaskSurface. r=mchang MozReview-Commit-ID: 9fjb0jAhlm3 --- gfx/2d/DrawTargetSkia.cpp | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/gfx/2d/DrawTargetSkia.cpp b/gfx/2d/DrawTargetSkia.cpp index 3531ae865dad..f1dbab2db84e 100644 --- a/gfx/2d/DrawTargetSkia.cpp +++ b/gfx/2d/DrawTargetSkia.cpp @@ -311,7 +311,7 @@ DrawTargetSkia::ReleaseBits(uint8_t* aData) } static void -SetPaintPattern(SkPaint& aPaint, const Pattern& aPattern, Float aAlpha = 1.0) +SetPaintPattern(SkPaint& aPaint, const Pattern& aPattern, Float aAlpha = 1.0, Point aOffset = Point(0, 0)) { switch (aPattern.GetType()) { case PatternType::COLOR: { @@ -333,6 +333,7 @@ SetPaintPattern(SkPaint& aPaint, const Pattern& aPattern, Float aAlpha = 1.0) SkMatrix mat; GfxMatrixToSkiaMatrix(pat.mMatrix, mat); + mat.postTranslate(SkFloatToScalar(aOffset.x), SkFloatToScalar(aOffset.y)); sk_sp shader = SkGradientShader::MakeLinear(points, &stops->mColors.front(), &stops->mPositions.front(), @@ -357,6 +358,7 @@ SetPaintPattern(SkPaint& aPaint, const Pattern& aPattern, Float aAlpha = 1.0) SkMatrix mat; GfxMatrixToSkiaMatrix(pat.mMatrix, mat); + mat.postTranslate(SkFloatToScalar(aOffset.x), SkFloatToScalar(aOffset.y)); sk_sp shader = SkGradientShader::MakeTwoPointConical(points[0], SkFloatToScalar(pat.mRadius1), points[1], @@ -375,6 +377,7 @@ SetPaintPattern(SkPaint& aPaint, const Pattern& aPattern, Float aAlpha = 1.0) SkMatrix mat; GfxMatrixToSkiaMatrix(pat.mMatrix, mat); + mat.postTranslate(SkFloatToScalar(aOffset.x), SkFloatToScalar(aOffset.y)); if (!pat.mSamplingRect.IsEmpty()) { SkIRect rect = IntRectToSkIRect(pat.mSamplingRect); @@ -415,11 +418,11 @@ GetClipBounds(SkCanvas *aCanvas) } struct AutoPaintSetup { - AutoPaintSetup(SkCanvas *aCanvas, const DrawOptions& aOptions, const Pattern& aPattern, const Rect* aMaskBounds = nullptr) + AutoPaintSetup(SkCanvas *aCanvas, const DrawOptions& aOptions, const Pattern& aPattern, const Rect* aMaskBounds = nullptr, Point aOffset = Point(0, 0)) : mNeedsRestore(false), mAlpha(1.0) { Init(aCanvas, aOptions, aMaskBounds); - SetPaintPattern(mPaint, aPattern, mAlpha); + SetPaintPattern(mPaint, aPattern, mAlpha, aOffset); } AutoPaintSetup(SkCanvas *aCanvas, const DrawOptions& aOptions, const Rect* aMaskBounds = nullptr) @@ -1311,7 +1314,7 @@ DrawTargetSkia::MaskSurface(const Pattern &aSource, const DrawOptions &aOptions) { MarkChanged(); - AutoPaintSetup paint(mCanvas.get(), aOptions, aSource); + AutoPaintSetup paint(mCanvas.get(), aOptions, aSource, nullptr, -aOffset); SkBitmap bitmap = GetBitmapForSurface(aMask); if (bitmap.colorType() != kAlpha_8_SkColorType && @@ -1320,14 +1323,6 @@ DrawTargetSkia::MaskSurface(const Pattern &aSource, return; } - if (aOffset != Point(0, 0) && - paint.mPaint.getShader()) { - SkMatrix transform; - transform.setTranslate(PointToSkPoint(-aOffset)); - sk_sp matrixShader = paint.mPaint.getShader()->makeWithLocalMatrix(transform); - paint.mPaint.setShader(matrixShader); - } - mCanvas->drawBitmap(bitmap, aOffset.x, aOffset.y, &paint.mPaint); } From adcdc0aaedb707ba417ee2664579badacfb2a732 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 25 Aug 2016 14:35:33 -0400 Subject: [PATCH 013/105] Bug 1297835. Don't suppress the scroll bits of a non-open
that has the appropriate overflow styles. r=TYLin --- layout/base/crashtests/1297835.html | 6 +++ layout/base/crashtests/crashtests.list | 1 + layout/base/nsCSSFrameConstructor.cpp | 10 ++++- .../details-summary/details-after.html | 21 ++++++++++ .../details-summary/details-before.html | 21 ++++++++++ .../details-summary/open-details-after.html | 21 ++++++++++ .../details-summary/open-details-before.html | 21 ++++++++++ .../overflow-scroll-details-ref.html | 31 ++++++++++++++ .../overflow-scroll-details.html | 42 +++++++++++++++++++ layout/reftests/details-summary/reftest.list | 7 ++++ 10 files changed, 179 insertions(+), 2 deletions(-) create mode 100644 layout/base/crashtests/1297835.html create mode 100644 layout/reftests/details-summary/details-after.html create mode 100644 layout/reftests/details-summary/details-before.html create mode 100644 layout/reftests/details-summary/open-details-after.html create mode 100644 layout/reftests/details-summary/open-details-before.html create mode 100644 layout/reftests/details-summary/overflow-scroll-details-ref.html create mode 100644 layout/reftests/details-summary/overflow-scroll-details.html diff --git a/layout/base/crashtests/1297835.html b/layout/base/crashtests/1297835.html new file mode 100644 index 000000000000..47c9e3ea4d8e --- /dev/null +++ b/layout/base/crashtests/1297835.html @@ -0,0 +1,6 @@ + +
+ Some summary + The details +
+ diff --git a/layout/base/crashtests/crashtests.list b/layout/base/crashtests/crashtests.list index ceddf6b464d9..10ce904f087d 100644 --- a/layout/base/crashtests/crashtests.list +++ b/layout/base/crashtests/crashtests.list @@ -476,4 +476,5 @@ pref(dom.webcomponents.enabled,true) load 1261351.html load 1270797-1.html load 1278455-1.html load 1286889.html +load 1297835.html load 1288608.html diff --git a/layout/base/nsCSSFrameConstructor.cpp b/layout/base/nsCSSFrameConstructor.cpp index 2158e991069f..99d97bd8f95a 100644 --- a/layout/base/nsCSSFrameConstructor.cpp +++ b/layout/base/nsCSSFrameConstructor.cpp @@ -5713,9 +5713,15 @@ nsCSSFrameConstructor::AddFrameConstructionItemsInternal(nsFrameConstructorState } // When constructing a child of a non-open
, create only the frame - // for the main element, and skip other elements. + // for the main element, and skip other elements. This only applies + // to things that are not roots of native anonymous subtrees (except for + // ::before and ::after); we always want to create "internal" anonymous + // content. auto* details = HTMLDetailsElement::FromContentOrNull(parent); - if (details && details->IsDetailsEnabled() && !details->Open()) { + if (details && details->IsDetailsEnabled() && !details->Open() && + (!aContent->IsRootOfNativeAnonymousSubtree() || + aContent->IsGeneratedContentContainerForBefore() || + aContent->IsGeneratedContentContainerForAfter())) { auto* summary = HTMLSummaryElement::FromContentOrNull(aContent); if (!summary || !summary->IsMainSummary()) { SetAsUndisplayedContent(aState, aItems, aContent, styleContext, diff --git a/layout/reftests/details-summary/details-after.html b/layout/reftests/details-summary/details-after.html new file mode 100644 index 000000000000..6746919d724b --- /dev/null +++ b/layout/reftests/details-summary/details-after.html @@ -0,0 +1,21 @@ + + + + + + + +
+ Summary +
+ + diff --git a/layout/reftests/details-summary/details-before.html b/layout/reftests/details-summary/details-before.html new file mode 100644 index 000000000000..103908919708 --- /dev/null +++ b/layout/reftests/details-summary/details-before.html @@ -0,0 +1,21 @@ + + + + + + + +
+ Summary +
+ + diff --git a/layout/reftests/details-summary/open-details-after.html b/layout/reftests/details-summary/open-details-after.html new file mode 100644 index 000000000000..1c5d8b7257a6 --- /dev/null +++ b/layout/reftests/details-summary/open-details-after.html @@ -0,0 +1,21 @@ + + + + + + + +
+ Summary +
+ + diff --git a/layout/reftests/details-summary/open-details-before.html b/layout/reftests/details-summary/open-details-before.html new file mode 100644 index 000000000000..a35a58111881 --- /dev/null +++ b/layout/reftests/details-summary/open-details-before.html @@ -0,0 +1,21 @@ + + + + + + + +
+ Summary +
+ + diff --git a/layout/reftests/details-summary/overflow-scroll-details-ref.html b/layout/reftests/details-summary/overflow-scroll-details-ref.html new file mode 100644 index 000000000000..b85a242c9d8b --- /dev/null +++ b/layout/reftests/details-summary/overflow-scroll-details-ref.html @@ -0,0 +1,31 @@ + + + + + + +
+
Lorem ipsum dolor sit amet, consectetur adipiscing elit, + sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut + enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut + aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit + in voluptate velit esse cillum dolore eu fugiat nulla pariatur. + Excepteur sint occaecat cupidatat non proident, sunt in culpa qui + officia deserunt mollit anim id est laborum. +
+
+ + diff --git a/layout/reftests/details-summary/overflow-scroll-details.html b/layout/reftests/details-summary/overflow-scroll-details.html new file mode 100644 index 000000000000..62ef22f4a883 --- /dev/null +++ b/layout/reftests/details-summary/overflow-scroll-details.html @@ -0,0 +1,42 @@ + + + + + + +
+ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do + eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad + minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip + ex ea commodo consequat. Duis aute irure dolor in reprehenderit in + voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur + sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt + mollit anim id est laborum. + + Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod + tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim + veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea + commodo consequat. Duis aute irure dolor in reprehenderit in voluptate + velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat + cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id + est laborum. +
+ + diff --git a/layout/reftests/details-summary/reftest.list b/layout/reftests/details-summary/reftest.list index b0053271f854..d9c8e5b37592 100644 --- a/layout/reftests/details-summary/reftest.list +++ b/layout/reftests/details-summary/reftest.list @@ -42,6 +42,7 @@ pref(dom.details_element.enabled,false) == no-summary.html disabled-no-summary-r # With 'overflow' property == overflow-hidden-open-details.html overflow-hidden-open-details-ref.html == overflow-auto-open-details.html overflow-auto-open-details-ref.html +== overflow-scroll-details.html overflow-scroll-details-ref.html # With pagination property == details-page-break-after-1.html details-two-pages.html @@ -84,3 +85,9 @@ pref(dom.details_element.enabled,false) == no-summary.html disabled-no-summary-r == key-enter-open-second-summary.html open-multiple-summary.html == key-enter-prevent-default.html single-summary.html == key-space-single-summary.html open-single-summary.html + +# Generated content bits +== details-after.html single-summary.html +== details-before.html single-summary.html +== open-details-after.html open-single-summary.html +== open-details-before.html open-single-summary.html From 16d1de5631d27a9c69d3bfe4cd6373b9933dd942 Mon Sep 17 00:00:00 2001 From: Boris Zbarsky Date: Thu, 25 Aug 2016 14:36:45 -0400 Subject: [PATCH 014/105] Bug 1250725. Correctly flag the we synthesize when references a as allowed to be reframed. r=dbaron --- dom/svg/SVGUseElement.cpp | 20 ++++++++++---------- dom/svg/crashtests/1250725.html | 16 ++++++++++++++++ dom/svg/crashtests/crashtests.list | 1 + 3 files changed, 27 insertions(+), 10 deletions(-) create mode 100644 dom/svg/crashtests/1250725.html diff --git a/dom/svg/SVGUseElement.cpp b/dom/svg/SVGUseElement.cpp index e913a4c200ff..a61e63609cb3 100644 --- a/dom/svg/SVGUseElement.cpp +++ b/dom/svg/SVGUseElement.cpp @@ -269,16 +269,6 @@ SVGUseElement::CreateAnonymousContent() if (!newcontent) return nullptr; -#ifdef DEBUG - // Our anonymous clone can get restyled by various things - // (e.g. SMIL). Reconstructing its frame is OK, though, because - // it's going to be our _only_ child in the frame tree, so can't get - // mis-ordered with anything. - newcontent->SetProperty(nsGkAtoms::restylableAnonymousNode, - reinterpret_cast(true)); -#endif // DEBUG - - if (newcontent->IsSVGElement(nsGkAtoms::symbol)) { nsIDocument *document = GetComposedDoc(); if (!document) @@ -341,6 +331,16 @@ SVGUseElement::CreateAnonymousContent() targetContent->AddMutationObserver(this); mClone = newcontent; + +#ifdef DEBUG + // Our anonymous clone can get restyled by various things + // (e.g. SMIL). Reconstructing its frame is OK, though, because + // it's going to be our _only_ child in the frame tree, so can't get + // mis-ordered with anything. + mClone->SetProperty(nsGkAtoms::restylableAnonymousNode, + reinterpret_cast(true)); +#endif // DEBUG + return mClone; } diff --git a/dom/svg/crashtests/1250725.html b/dom/svg/crashtests/1250725.html new file mode 100644 index 000000000000..68052f344f36 --- /dev/null +++ b/dom/svg/crashtests/1250725.html @@ -0,0 +1,16 @@ + + + + + + + + + diff --git a/dom/svg/crashtests/crashtests.list b/dom/svg/crashtests/crashtests.list index 2ecea825919a..d609d2eb9308 100644 --- a/dom/svg/crashtests/crashtests.list +++ b/dom/svg/crashtests/crashtests.list @@ -75,6 +75,7 @@ load 898915-1.svg load 1035248-1.svg load 1035248-2.svg load 1244898-1.xhtml +load 1250725.html load 1267272-1.svg load 1282985-1.svg # Disabled for now due to it taking a very long time to run - bug 1259356 From 7f34cdcfa6da27a2d8d2181f546d9d611809ea18 Mon Sep 17 00:00:00 2001 From: George Wright Date: Wed, 24 Aug 2016 15:47:11 -0400 Subject: [PATCH 015/105] Bug 1297797 - Set the process name for the GPU process r=dvander --- gfx/ipc/GPUParent.cpp | 2 ++ gfx/ipc/moz.build | 2 ++ 2 files changed, 4 insertions(+) diff --git a/gfx/ipc/GPUParent.cpp b/gfx/ipc/GPUParent.cpp index 6cf9b453aa9d..117f269b1e59 100644 --- a/gfx/ipc/GPUParent.cpp +++ b/gfx/ipc/GPUParent.cpp @@ -16,6 +16,7 @@ #include "mozilla/layers/ImageBridgeParent.h" #include "nsDebugImpl.h" #include "mozilla/layers/LayerTreeOwnerTracker.h" +#include "ProcessUtils.h" #include "VRManager.h" #include "VRManagerParent.h" #include "VsyncBridgeParent.h" @@ -64,6 +65,7 @@ GPUParent::Init(base::ProcessId aParentPid, CompositorThreadHolder::Start(); VRManager::ManagerInit(); LayerTreeOwnerTracker::Initialize(); + mozilla::ipc::SetThisProcessName("GPU Process"); return true; } diff --git a/gfx/ipc/moz.build b/gfx/ipc/moz.build index 34d684b80101..372356c0865a 100644 --- a/gfx/ipc/moz.build +++ b/gfx/ipc/moz.build @@ -64,6 +64,8 @@ IPDL_SOURCES = [ 'PVsyncBridge.ipdl', ] +LOCAL_INCLUDES += ['/dom/ipc'] + include('/ipc/chromium/chromium-config.mozbuild') FINAL_LIBRARY = 'xul' From dda03690ef974fc4e9ba24075de34fca3299ba75 Mon Sep 17 00:00:00 2001 From: Seth Fowler Date: Fri, 19 Aug 2016 15:04:34 -0700 Subject: [PATCH 016/105] Bug 1296762 (Part 1) - Remove SurfaceCache::InsertPlaceholder(). r=dholbert --- image/SurfaceCache.cpp | 24 ++---------------------- image/SurfaceCache.h | 41 +++-------------------------------------- 2 files changed, 5 insertions(+), 60 deletions(-) diff --git a/image/SurfaceCache.cpp b/image/SurfaceCache.cpp index 27206e2b5a1f..bd822be900ed 100644 --- a/image/SurfaceCache.cpp +++ b/image/SurfaceCache.cpp @@ -67,12 +67,6 @@ static StaticRefPtr sInstance; */ typedef size_t Cost; -// Placeholders do not have surfaces, but need to be given a trivial cost for -// our invariants to hold. -// XXX(seth): This is only true of old-style placeholders inserted via -// InsertPlaceholder(). -static const Cost sPlaceholderCost = 1; - static Cost ComputeCost(const IntSize& aSize, uint32_t aBytesPerPixel) { @@ -141,8 +135,7 @@ public: , mImageKey(aImageKey) , mSurfaceKey(aSurfaceKey) { - MOZ_ASSERT(aProvider || mCost == sPlaceholderCost, - "Old-style placeholders should have trivial cost"); + MOZ_ASSERT(aProvider); MOZ_ASSERT(mImageKey, "Must have a valid image key"); } @@ -367,7 +360,7 @@ public: } } else { if (exactMatch) { - // We found an "exact match", it must have been a placeholder. + // We found an "exact match"; it must have been a placeholder. MOZ_ASSERT(exactMatch->IsPlaceholder()); matchType = MatchType::PENDING; } else { @@ -1065,19 +1058,6 @@ SurfaceCache::Insert(NotNull aProvider, /* aSetAvailable = */ false); } -/* static */ InsertOutcome -SurfaceCache::InsertPlaceholder(const ImageKey aImageKey, - const SurfaceKey& aSurfaceKey) -{ - if (!sInstance) { - return InsertOutcome::FAILURE; - } - - MutexAutoLock lock(sInstance->GetMutex()); - return sInstance->Insert(nullptr, sPlaceholderCost, aImageKey, aSurfaceKey, - /* aSetAvailable = */ false); -} - /* static */ bool SurfaceCache::CanHold(const IntSize& aSize, uint32_t aBytesPerPixel /* = 4 */) { diff --git a/image/SurfaceCache.h b/image/SurfaceCache.h index 1abbeb08ade7..e009caae767e 100644 --- a/image/SurfaceCache.h +++ b/image/SurfaceCache.h @@ -240,8 +240,8 @@ struct SurfaceCache /** * Insert an ISurfaceProvider into the cache. If an entry with the same * ImageKey and SurfaceKey is already in the cache, Insert returns - * FAILURE_ALREADY_PRESENT. If a matching placeholder is already present, the - * placeholder is removed. + * FAILURE_ALREADY_PRESENT. If a matching placeholder is already present, it + * is replaced. * * Cache entries will never expire as long as they remain locked, but if they * become unlocked, they can expire either because the SurfaceCache runs out @@ -285,33 +285,6 @@ struct SurfaceCache const ImageKey aImageKey, const SurfaceKey& aSurfaceKey); - /** - * Insert a placeholder entry into the cache. If an entry with the same - * ImageKey and SurfaceKey is already in the cache, InsertPlaceholder() - * returns FAILURE_ALREADY_PRESENT. - * - * Placeholders exist to allow lazy allocation of surfaces. The Lookup*() - * methods will report whether a placeholder for an exactly matching cache - * entry existed by returning a MatchType of PENDING or - * SUBSTITUTE_BECAUSE_PENDING, but they will never return a placeholder - * directly. (They couldn't, since placeholders don't have an associated - * surface.) - * - * Placeholders are automatically removed when a real entry that matches the - * placeholder is inserted with Insert(), or when RemoveImage() is called. - * - * @param aImageKey Key data identifying which image the cache entry - * belongs to. - * @param aSurfaceKey Key data which uniquely identifies the requested - * cache entry. - * @return SUCCESS if the placeholder was inserted successfully. - * FAILURE if the placeholder could not be inserted for some reason. - * FAILURE_ALREADY_PRESENT if an entry with the same ImageKey and - * SurfaceKey already exists in the cache. - */ - static InsertOutcome InsertPlaceholder(const ImageKey aImageKey, - const SurfaceKey& aSurfaceKey); - /** * Mark the cache entry @aProvider as having an available surface. This turns * a placeholder cache entry into a normal cache entry. The cache entry @@ -325,14 +298,6 @@ struct SurfaceCache * definition, non-placeholder ISurfaceProviders should have a surface * available already. * - * XXX(seth): We're currently in a transitional state where two notions of - * placeholder exist: the old one (placeholders are an "empty" cache entry - * inserted via InsertPlaceholder(), which then gets replaced by inserting a - * real cache entry with the same keys via Insert()) and the new one (where - * the same cache entry, inserted via Insert(), starts in a placeholder state - * and then transitions to being a normal cache entry via this function). The - * old mechanism will be removed in bug 1292392. - * * @param aProvider The cache entry that now has a surface available. * @param aImageKey Key data identifying which image the cache entry * belongs to. @@ -423,7 +388,7 @@ struct SurfaceCache static void UnlockEntries(const ImageKey aImageKey); /** - * Removes all cache entries (both real and placeholder) associated with the + * Removes all cache entries (including placeholders) associated with the * given image from the cache. If the image is locked, it is automatically * unlocked. * From 6006fb4945b59ece549922c8304e1a813eec6a3d Mon Sep 17 00:00:00 2001 From: Seth Fowler Date: Fri, 19 Aug 2016 15:07:47 -0700 Subject: [PATCH 017/105] Bug 1296762 (Part 2) - Forbid null ISurfaceProviders in SurfaceCache. r=dholbert --- image/SurfaceCache.cpp | 43 +++++++++++++++++------------------------- 1 file changed, 17 insertions(+), 26 deletions(-) diff --git a/image/SurfaceCache.cpp b/image/SurfaceCache.cpp index bd822be900ed..03d3466d4edb 100644 --- a/image/SurfaceCache.cpp +++ b/image/SurfaceCache.cpp @@ -126,16 +126,15 @@ public: MOZ_DECLARE_REFCOUNTED_TYPENAME(CachedSurface) NS_INLINE_DECL_THREADSAFE_REFCOUNTING(CachedSurface) - CachedSurface(ISurfaceProvider* aProvider, - const Cost aCost, - const ImageKey aImageKey, - const SurfaceKey& aSurfaceKey) + CachedSurface(NotNull aProvider, + const Cost aCost, + const ImageKey aImageKey, + const SurfaceKey& aSurfaceKey) : mProvider(aProvider) , mCost(aCost) , mImageKey(aImageKey) , mSurfaceKey(aSurfaceKey) { - MOZ_ASSERT(aProvider); MOZ_ASSERT(mImageKey, "Must have a valid image key"); } @@ -158,23 +157,15 @@ public: mProvider->SetLocked(aLocked); } - bool IsPlaceholder() const - { - return !mProvider || mProvider->Availability().IsPlaceholder(); - } - bool IsLocked() const { return !IsPlaceholder() && mProvider->IsLocked(); } + bool IsPlaceholder() const { return mProvider->Availability().IsPlaceholder(); } + bool IsDecoded() const { return !IsPlaceholder() && mProvider->IsFinished(); } ImageKey GetImageKey() const { return mImageKey; } SurfaceKey GetSurfaceKey() const { return mSurfaceKey; } CostEntry GetCostEntry() { return image::CostEntry(this, mCost); } nsExpirationState* GetExpirationState() { return &mExpirationState; } - bool IsDecoded() const - { - return !IsPlaceholder() && mProvider->IsFinished(); - } - // A helper type used by SurfaceCacheImpl::CollectSizeOfSurfaces. struct MOZ_STACK_CLASS SurfaceMemoryReport { @@ -215,11 +206,11 @@ public: }; private: - nsExpirationState mExpirationState; - RefPtr mProvider; - const Cost mCost; - const ImageKey mImageKey; - const SurfaceKey mSurfaceKey; + nsExpirationState mExpirationState; + NotNull> mProvider; + const Cost mCost; + const ImageKey mImageKey; + const SurfaceKey mSurfaceKey; }; static int64_t @@ -431,11 +422,11 @@ public: Mutex& GetMutex() { return mMutex; } - InsertOutcome Insert(ISurfaceProvider* aProvider, - const Cost aCost, - const ImageKey aImageKey, - const SurfaceKey& aSurfaceKey, - bool aSetAvailable) + InsertOutcome Insert(NotNull aProvider, + const Cost aCost, + const ImageKey aImageKey, + const SurfaceKey& aSurfaceKey, + bool aSetAvailable) { // If this is a duplicate surface, refuse to replace the original. // XXX(seth): Calling Lookup() and then RemoveEntry() does the lookup @@ -1054,7 +1045,7 @@ SurfaceCache::Insert(NotNull aProvider, MutexAutoLock lock(sInstance->GetMutex()); Cost cost = aProvider->LogicalSizeInBytes(); - return sInstance->Insert(aProvider.get(), cost, aImageKey, aSurfaceKey, + return sInstance->Insert(aProvider, cost, aImageKey, aSurfaceKey, /* aSetAvailable = */ false); } From fd83d4ee88978de67e6e90ae7b482d7b1fb471bf Mon Sep 17 00:00:00 2001 From: Seth Fowler Date: Fri, 19 Aug 2016 15:09:52 -0700 Subject: [PATCH 018/105] Bug 1296762 (Part 3) - Use NotNull for all CachedSurfaces in SurfaceCache. r=dholbert --- image/SurfaceCache.cpp | 73 +++++++++++++++++++----------------------- 1 file changed, 33 insertions(+), 40 deletions(-) diff --git a/image/SurfaceCache.cpp b/image/SurfaceCache.cpp index 03d3466d4edb..e8d4c1e9ce38 100644 --- a/image/SurfaceCache.cpp +++ b/image/SurfaceCache.cpp @@ -88,14 +88,12 @@ ComputeCost(const IntSize& aSize, uint32_t aBytesPerPixel) class CostEntry { public: - CostEntry(CachedSurface* aSurface, Cost aCost) + CostEntry(NotNull aSurface, Cost aCost) : mSurface(aSurface) , mCost(aCost) - { - MOZ_ASSERT(aSurface, "Must have a surface"); - } + { } - CachedSurface* GetSurface() const { return mSurface; } + NotNull Surface() const { return mSurface; } Cost GetCost() const { return mCost; } bool operator==(const CostEntry& aOther) const @@ -111,8 +109,8 @@ public: } private: - CachedSurface* mSurface; - Cost mCost; + NotNull mSurface; + Cost mCost; }; /** @@ -163,7 +161,7 @@ public: ImageKey GetImageKey() const { return mImageKey; } SurfaceKey GetSurfaceKey() const { return mSurfaceKey; } - CostEntry GetCostEntry() { return image::CostEntry(this, mCost); } + CostEntry GetCostEntry() { return image::CostEntry(WrapNotNull(this), mCost); } nsExpirationState* GetExpirationState() { return &mExpirationState; } // A helper type used by SurfaceCacheImpl::CollectSizeOfSurfaces. @@ -175,10 +173,8 @@ public: , mMallocSizeOf(aMallocSizeOf) { } - void Add(CachedSurface* aCachedSurface) + void Add(NotNull aCachedSurface) { - MOZ_ASSERT(aCachedSurface, "Should have a CachedSurface"); - SurfaceMemoryCounter counter(aCachedSurface->GetSurfaceKey(), aCachedSurface->IsLocked()); @@ -241,17 +237,15 @@ public: bool IsEmpty() const { return mSurfaces.Count() == 0; } - void Insert(const SurfaceKey& aKey, CachedSurface* aSurface) + void Insert(const SurfaceKey& aKey, NotNull aSurface) { - MOZ_ASSERT(aSurface, "Should have a surface"); MOZ_ASSERT(!mLocked || aSurface->IsPlaceholder() || aSurface->IsLocked(), "Inserting an unlocked surface for a locked image"); mSurfaces.Put(aKey, aSurface); } - void Remove(CachedSurface* aSurface) + void Remove(NotNull aSurface) { - MOZ_ASSERT(aSurface, "Should have a surface"); MOZ_ASSERT(mSurfaces.GetWeak(aSurface->GetSurfaceKey()), "Should not be removing a surface we don't have"); @@ -278,7 +272,7 @@ public: // There's no perfect match, so find the best match we can. RefPtr bestMatch; for (auto iter = ConstIter(); !iter.Done(); iter.Next()) { - CachedSurface* current = iter.UserData(); + NotNull current = WrapNotNull(iter.UserData()); const SurfaceKey& currentKey = current->GetSurfaceKey(); // We never match a placeholder. @@ -456,7 +450,7 @@ public: while (aCost > mAvailableCost) { MOZ_ASSERT(!mCosts.IsEmpty(), "Removed everything and it still won't fit"); - Remove(mCosts.LastElement().GetSurface()); + Remove(mCosts.LastElement().Surface()); } // Locate the appropriate per-image cache. If there's not an existing cache @@ -472,8 +466,8 @@ public: aProvider->Availability().SetAvailable(); } - RefPtr surface = - new CachedSurface(aProvider, aCost, aImageKey, aSurfaceKey); + NotNull> surface = + WrapNotNull(new CachedSurface(aProvider, aCost, aImageKey, aSurfaceKey)); // We require that locking succeed if the image is locked and we're not // inserting a placeholder; the caller may need to know this to handle @@ -493,9 +487,8 @@ public: return InsertOutcome::SUCCESS; } - void Remove(CachedSurface* aSurface) + void Remove(NotNull aSurface) { - MOZ_ASSERT(aSurface, "Should have a surface"); ImageKey imageKey = aSurface->GetImageKey(); RefPtr cache = GetImageCache(imageKey); @@ -516,7 +509,7 @@ public: } } - void StartTracking(CachedSurface* aSurface) + void StartTracking(NotNull aSurface) { CostEntry costEntry = aSurface->GetCostEntry(); MOZ_ASSERT(costEntry.GetCost() <= mAvailableCost, @@ -535,9 +528,8 @@ public: } } - void StopTracking(CachedSurface* aSurface) + void StopTracking(NotNull aSurface) { - MOZ_ASSERT(aSurface, "Should have a surface"); CostEntry costEntry = aSurface->GetCostEntry(); if (aSurface->IsLocked()) { @@ -589,12 +581,12 @@ public: if (!drawableSurface) { // The surface was released by the operating system. Remove the cache // entry as well. - Remove(surface); + Remove(WrapNotNull(surface)); return LookupResult(MatchType::NOT_FOUND); } if (aMarkUsed) { - MarkUsed(surface, cache); + MarkUsed(WrapNotNull(surface), WrapNotNull(cache)); } MOZ_ASSERT(surface->GetSurfaceKey() == aSurfaceKey, @@ -634,7 +626,7 @@ public: // The surface was released by the operating system. Remove the cache // entry as well. - Remove(surface); + Remove(WrapNotNull(surface)); } MOZ_ASSERT_IF(matchType == MatchType::EXACT, @@ -646,7 +638,7 @@ public: surface->GetSurfaceKey().Flags() == aSurfaceKey.Flags()); if (matchType == MatchType::EXACT) { - MarkUsed(surface, cache); + MarkUsed(WrapNotNull(surface), WrapNotNull(cache)); } return LookupResult(Move(drawableSurface), matchType); @@ -703,7 +695,7 @@ public: } cache->SetLocked(false); - DoUnlockSurfaces(cache); + DoUnlockSurfaces(WrapNotNull(cache)); } void UnlockEntries(const ImageKey aImageKey) @@ -715,7 +707,7 @@ public: // (Note that we *don't* unlock the per-image cache here; that's the // difference between this and UnlockImage.) - DoUnlockSurfaces(cache); + DoUnlockSurfaces(WrapNotNull(cache)); } void RemoveImage(const ImageKey aImageKey) @@ -731,7 +723,7 @@ public: // small, performance should be good, but if usage patterns change we should // change the data structure used for mCosts. for (auto iter = cache->ConstIter(); !iter.Done(); iter.Next()) { - StopTracking(iter.UserData()); + StopTracking(WrapNotNull(iter.UserData())); } // The per-image cache isn't needed anymore, so remove it as well. @@ -745,7 +737,7 @@ public: // structures are all hash tables. Note that locked surfaces are not // removed, since they aren't present in mCosts. while (!mCosts.IsEmpty()) { - Remove(mCosts.LastElement().GetSurface()); + Remove(mCosts.LastElement().Surface()); } } @@ -771,11 +763,11 @@ public: // Discard surfaces until we've reduced our cost to our target cost. while (mAvailableCost < targetCost) { MOZ_ASSERT(!mCosts.IsEmpty(), "Removed everything and still not done"); - Remove(mCosts.LastElement().GetSurface()); + Remove(mCosts.LastElement().Surface()); } } - void LockSurface(CachedSurface* aSurface) + void LockSurface(NotNull aSurface) { if (aSurface->IsPlaceholder() || aSurface->IsLocked()) { return; @@ -829,7 +821,7 @@ public: // Report all surfaces in the per-image cache. CachedSurface::SurfaceMemoryReport report(aCounters, aMallocSizeOf); for (auto iter = cache->ConstIter(); !iter.Done(); iter.Next()) { - report.Add(iter.UserData()); + report.Add(WrapNotNull(iter.UserData())); } } @@ -851,7 +843,8 @@ private: return aCost <= mMaxCost - mLockedCost; } - void MarkUsed(CachedSurface* aSurface, ImageSurfaceCache* aCache) + void MarkUsed(NotNull aSurface, + NotNull aCache) { if (aCache->IsLocked()) { LockSurface(aSurface); @@ -860,11 +853,11 @@ private: } } - void DoUnlockSurfaces(ImageSurfaceCache* aCache) + void DoUnlockSurfaces(NotNull aCache) { // Unlock all the surfaces the per-image cache is holding. for (auto iter = aCache->ConstIter(); !iter.Done(); iter.Next()) { - CachedSurface* surface = iter.UserData(); + NotNull surface = WrapNotNull(iter.UserData()); if (surface->IsPlaceholder() || !surface->IsLocked()) { continue; } @@ -887,7 +880,7 @@ private: return; // Lookup in the per-image cache missed. } - Remove(surface); + Remove(WrapNotNull(surface)); } struct SurfaceTracker : public nsExpirationTracker @@ -902,7 +895,7 @@ private: { if (sInstance) { MutexAutoLock lock(sInstance->GetMutex()); - sInstance->Remove(aSurface); + sInstance->Remove(WrapNotNull(aSurface)); } } }; From 0f1e872d3fb227db0476b0821bbf846e453a1234 Mon Sep 17 00:00:00 2001 From: Sumit Tiwari Date: Thu, 25 Aug 2016 12:21:51 -0700 Subject: [PATCH 019/105] Bug 1295034 - Assertion failure when sorting TypedArrays constructed under JIT; r=mrrrgn --- js/src/builtin/Sorting.js | 11 +++++++--- .../tests/ecma_6/TypedArray/sort_jit_array.js | 22 +++++++++++++++++++ js/src/vm/SelfHosting.cpp | 3 ++- js/src/vm/TypedArrayObject.cpp | 4 ++-- js/src/vm/TypedArrayObject.h | 2 ++ 5 files changed, 36 insertions(+), 6 deletions(-) create mode 100644 js/src/tests/ecma_6/TypedArray/sort_jit_array.js diff --git a/js/src/builtin/Sorting.js b/js/src/builtin/Sorting.js index 0451ceb7a2fb..660ab079fd0e 100644 --- a/js/src/builtin/Sorting.js +++ b/js/src/builtin/Sorting.js @@ -101,9 +101,6 @@ function RadixSort(array, len, buffer, nbytes, signed, floating, comparefn) { return array; } - // Verify that the buffer is non-null - assert(buffer !== null, "Attached data buffer should be reified when array length is >= 128."); - let aux = new List(); for (let i = 0; i < len; i++) { aux[i] = 0; @@ -114,6 +111,14 @@ function RadixSort(array, len, buffer, nbytes, signed, floating, comparefn) { // Preprocess if (floating) { + // This happens if the array object is constructed under JIT + if (buffer === null) { + buffer = callFunction(std_TypedArray_buffer, array); + } + + // Verify that the buffer is non-null + assert(buffer !== null, "Attached data buffer should be reified when array length is >= 128."); + view = new Int32Array(buffer); // Flip sign bit for positive numbers; flip all bits for negative diff --git a/js/src/tests/ecma_6/TypedArray/sort_jit_array.js b/js/src/tests/ecma_6/TypedArray/sort_jit_array.js new file mode 100644 index 000000000000..6d17103c55c7 --- /dev/null +++ b/js/src/tests/ecma_6/TypedArray/sort_jit_array.js @@ -0,0 +1,22 @@ +const constructors = [ + Int8Array, + Uint8Array, + Uint8ClampedArray, + Int16Array, + Uint16Array, + Int32Array, + Uint32Array, + Float32Array, + Float64Array ]; + +// Ensure that when creating TypedArrays under JIT +// the sort() method works as expected (bug 1295034). +for (var ctor of constructors) { + for (var _ of Array(1024)) { + var testArray = new ctor(1024); + testArray.sort(); + } +} + +if (typeof reportCompare === "function") + reportCompare(true, true); \ No newline at end of file diff --git a/js/src/vm/SelfHosting.cpp b/js/src/vm/SelfHosting.cpp index ab7f7f9e1d4f..0601a00d3aab 100644 --- a/js/src/vm/SelfHosting.cpp +++ b/js/src/vm/SelfHosting.cpp @@ -2338,7 +2338,8 @@ static const JSFunctionSpec intrinsic_functions[] = { JS_FN("std_String_normalize", str_normalize, 0,0), #endif JS_FN("std_String_concat", str_concat, 1,0), - + + JS_FN("std_TypedArray_buffer", js::TypedArray_bufferGetter, 1,0), JS_FN("std_WeakMap_has", WeakMap_has, 1,0), JS_FN("std_WeakMap_get", WeakMap_get, 2,0), diff --git a/js/src/vm/TypedArrayObject.cpp b/js/src/vm/TypedArrayObject.cpp index 20e75f3c34f8..9db51cc4f4e1 100644 --- a/js/src/vm/TypedArrayObject.cpp +++ b/js/src/vm/TypedArrayObject.cpp @@ -1326,8 +1326,8 @@ BufferGetterImpl(JSContext* cx, const CallArgs& args) return true; } -static bool -TypedArray_bufferGetter(JSContext* cx, unsigned argc, Value* vp) +/*static*/ bool +js::TypedArray_bufferGetter(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); return CallNonGenericMethod(cx, args); diff --git a/js/src/vm/TypedArrayObject.h b/js/src/vm/TypedArrayObject.h index 4019c482b1d0..965ca282510b 100644 --- a/js/src/vm/TypedArrayObject.h +++ b/js/src/vm/TypedArrayObject.h @@ -294,6 +294,8 @@ class TypedArrayObject : public NativeObject static bool set(JSContext* cx, unsigned argc, Value* vp); }; +MOZ_MUST_USE bool TypedArray_bufferGetter(JSContext* cx, unsigned argc, Value* vp); + extern TypedArrayObject* TypedArrayCreateWithTemplate(JSContext* cx, HandleObject templateObj, int32_t len); From 43e77092c94b0292b2ee8f7bad7ba92e19feff21 Mon Sep 17 00:00:00 2001 From: Mason Chang Date: Thu, 25 Aug 2016 12:35:41 -0700 Subject: [PATCH 020/105] Bug 1007702. Enable skia on unaccelerated windows. r=lsalzman --- image/test/reftest/downscaling/reftest.list | 5 +++-- layout/reftests/abs-pos/reftest.list | 4 ++-- layout/reftests/backgrounds/reftest.list | 10 +++++----- layout/reftests/border-image/reftest.list | 2 +- layout/reftests/box-shadow/reftest.list | 2 +- layout/reftests/bugs/reftest.list | 4 ++-- layout/reftests/columns/reftest.list | 2 +- layout/reftests/forms/fieldset/reftest.list | 2 +- layout/reftests/forms/input/text/reftest.list | 2 +- layout/reftests/mathml/reftest.list | 2 +- .../position-dynamic-changes/relative/reftest.list | 8 ++++---- layout/reftests/position-sticky/reftest.list | 4 ++-- layout/reftests/scrolling/reftest.list | 4 ++-- layout/reftests/svg/text/reftest.list | 10 +++++----- layout/reftests/text-overflow/reftest.list | 2 +- layout/reftests/text/reftest.list | 2 +- layout/reftests/transform-3d/reftest.list | 2 +- layout/reftests/writing-mode/reftest.list | 2 +- layout/reftests/xul/reftest.list | 2 +- modules/libpref/init/all.js | 2 +- .../dir-isolation-002a.html.ini | 7 ------- .../dir-isolation-002b.html.ini | 8 -------- .../dir-isolation-002c.html.ini | 8 -------- .../dir-isolation-006a.html.ini | 7 ------- .../dir-isolation-006b.html.ini | 8 -------- .../dir-isolation-006c.html.ini | 8 -------- .../dir-isolation-009a.html.ini | 8 -------- .../dir-isolation-009b.html.ini | 8 -------- .../dir-isolation-009c.html.ini | 7 ------- 29 files changed, 37 insertions(+), 105 deletions(-) delete mode 100644 testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-002a.html.ini delete mode 100644 testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-002b.html.ini delete mode 100644 testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-002c.html.ini delete mode 100644 testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-006a.html.ini delete mode 100644 testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-006b.html.ini delete mode 100644 testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-006c.html.ini delete mode 100644 testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-009a.html.ini delete mode 100644 testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-009b.html.ini delete mode 100644 testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-009c.html.ini diff --git a/image/test/reftest/downscaling/reftest.list b/image/test/reftest/downscaling/reftest.list index facb3164b414..7e54860fe8a0 100644 --- a/image/test/reftest/downscaling/reftest.list +++ b/image/test/reftest/downscaling/reftest.list @@ -87,7 +87,7 @@ fuzzy(20,999) != downscale-2c.html?205,53,bottom about:blank fuzzy(20,999) != downscale-2d.html?205,53,bottom about:blank fuzzy(20,999) fails-if(OSX>=1008&&!skiaContent) != downscale-2e.html?205,53,bottom about:blank -fuzzy(52,3386) == downscale-moz-icon-1.html downscale-moz-icon-1-ref.html +fuzzy(63,3386) == downscale-moz-icon-1.html downscale-moz-icon-1-ref.html == downscale-png.html?16,16,interlaced downscale-png.html?16,16,normal == downscale-png.html?24,24,interlaced downscale-png.html?24,24,normal @@ -170,7 +170,8 @@ fuzzy(20,999) != downscale-2d.html?205,53,bottom about:blank fuzzy(20,999) != downscale-2e.html?205,53,bottom about:blank fuzzy(20,999) != downscale-2f.html?205,53,bottom about:blank -fuzzy(71,4439) == downscale-moz-icon-1.html downscale-moz-icon-1-ref.html +# Skip on WinXP with skia content +fuzzy(71,4439) fails-if(/^Windows\x20NT\x205\.1/.test(http.oscpu)) == downscale-moz-icon-1.html downscale-moz-icon-1-ref.html == downscale-png.html?16,16,interlaced downscale-png.html?16,16,normal == downscale-png.html?24,24,interlaced downscale-png.html?24,24,normal diff --git a/layout/reftests/abs-pos/reftest.list b/layout/reftests/abs-pos/reftest.list index c20f10ae1fd3..5da9705fca81 100644 --- a/layout/reftests/abs-pos/reftest.list +++ b/layout/reftests/abs-pos/reftest.list @@ -49,11 +49,11 @@ skip-if((B2G&&browserIsRemote)||Mulet) != table-cell-8.html table-print-1-ref.ht == continuation-positioned-inline-1.html continuation-positioned-inline-ref.html == continuation-positioned-inline-2.html continuation-positioned-inline-ref.html == scrollframe-1.html scrollframe-1-ref.html -fuzzy-if(gtkWidget,1,1) skip-if(B2G||Mulet) fuzzy-if(Android,9,185) fuzzy-if(asyncPan&&!layersGPUAccelerated,121,107) == scrollframe-2.html scrollframe-2-ref.html #bug 756530 # Initial mulet triage: parity with B2G/B2G Desktop +fuzzy-if(gtkWidget,1,1) skip-if(B2G||Mulet) fuzzy-if(Android,9,185) fuzzy-if(asyncPan&&!layersGPUAccelerated,121,144) == scrollframe-2.html scrollframe-2-ref.html #bug 756530 # Initial mulet triage: parity with B2G/B2G Desktop fuzzy-if(gtkWidget,1,8) == select-1.html select-1-ref.html fuzzy-if(gtkWidget,1,8) == select-1-dynamic.html select-1-ref.html == select-2.html select-2-ref.html -fuzzy-if(gtkWidget,1,19) fuzzy-if(Android||B2G,17,726) fuzzy-if(asyncPan&&!layersGPUAccelerated,102,98) fuzzy-if(browserIsRemote&&winWidget,102,107) == select-3.html select-3-ref.html +fuzzy-if(gtkWidget,1,19) fuzzy-if(Android||B2G,17,726) fuzzy-if(asyncPan&&!layersGPUAccelerated,110,114) fuzzy-if(browserIsRemote&&winWidget,110,114) == select-3.html select-3-ref.html == multi-column-1.html multi-column-1-ref.html == button-1.html button-1-ref.html == button-2.html button-2-ref.html diff --git a/layout/reftests/backgrounds/reftest.list b/layout/reftests/backgrounds/reftest.list index 7b02b82c1730..1019e1a1c78a 100644 --- a/layout/reftests/backgrounds/reftest.list +++ b/layout/reftests/backgrounds/reftest.list @@ -179,11 +179,11 @@ fuzzy(30,474) fuzzy-if(skiaContent,31,474) == background-tiling-zoom-1.html back skip-if(!cocoaWidget) == background-repeat-resampling.html background-repeat-resampling-ref.html -pref(layout.css.background-clip-text.enabled,true) fuzzy-if(winWidget,102,2032) fuzzy-if(skiaContent,102,2595) == background-clip-text-1a.html background-clip-text-1-ref.html -pref(layout.css.background-clip-text.enabled,true) fuzzy-if(winWidget,102,2032) fuzzy-if(skiaContent,102,2595) == background-clip-text-1b.html background-clip-text-1-ref.html -pref(layout.css.background-clip-text.enabled,true) fuzzy-if(winWidget,102,2032) fuzzy-if(skiaContent,102,2595) == background-clip-text-1c.html background-clip-text-1-ref.html -pref(layout.css.background-clip-text.enabled,true) fuzzy-if(winWidget,102,2032) fuzzy-if(skiaContent,102,2595) == background-clip-text-1d.html background-clip-text-1-ref.html -pref(layout.css.background-clip-text.enabled,true) fuzzy-if(winWidget,102,2032) fuzzy-if(skiaContent,102,2595) == background-clip-text-1e.html background-clip-text-1-ref.html +pref(layout.css.background-clip-text.enabled,true) fuzzy-if(winWidget,102,2032) fuzzy-if(skiaContent,102,2617) == background-clip-text-1a.html background-clip-text-1-ref.html +pref(layout.css.background-clip-text.enabled,true) fuzzy-if(winWidget,102,2032) fuzzy-if(skiaContent,102,2617) == background-clip-text-1b.html background-clip-text-1-ref.html +pref(layout.css.background-clip-text.enabled,true) fuzzy-if(winWidget,102,2032) fuzzy-if(skiaContent,102,2617) == background-clip-text-1c.html background-clip-text-1-ref.html +pref(layout.css.background-clip-text.enabled,true) fuzzy-if(winWidget,102,2032) fuzzy-if(skiaContent,102,2617) == background-clip-text-1d.html background-clip-text-1-ref.html +pref(layout.css.background-clip-text.enabled,true) fuzzy-if(winWidget,102,2032) fuzzy-if(skiaContent,102,2617) == background-clip-text-1e.html background-clip-text-1-ref.html pref(layout.css.background-clip-text.enabled,false) != background-clip-text-1a.html background-clip-text-1-ref.html pref(layout.css.background-clip-text.enabled,true) == background-clip-text-2.html background-clip-text-2-ref.html diff --git a/layout/reftests/border-image/reftest.list b/layout/reftests/border-image/reftest.list index b95f1afd8f4c..eeb65755057a 100644 --- a/layout/reftests/border-image/reftest.list +++ b/layout/reftests/border-image/reftest.list @@ -36,7 +36,7 @@ fails-if(Android||B2G) fails-if(usesRepeatResampling) == center-scaling-3.html c == border-image-outset-1c.html border-image-outset-1-ref.html == border-image-nofill-1.html border-image-nofill-1-ref.html == border-image-outset-resize-1.html border-image-outset-resize-1-ref.html -fuzzy-if(asyncPan&&!layersGPUAccelerated,121,447) == border-image-outset-move-1.html border-image-outset-move-1-ref.html +fuzzy-if(asyncPan&&!layersGPUAccelerated,121,514) == border-image-outset-move-1.html border-image-outset-move-1-ref.html == border-image-style-none.html border-image-style-none-ref.html == border-image-style-none-length.html border-image-style-none-length-ref.html == border-image-style-none-auto.html border-image-style-none-auto-ref.html diff --git a/layout/reftests/box-shadow/reftest.list b/layout/reftests/box-shadow/reftest.list index 7a29b836a686..77f188d9ebc1 100644 --- a/layout/reftests/box-shadow/reftest.list +++ b/layout/reftests/box-shadow/reftest.list @@ -41,5 +41,5 @@ fuzzy-if(winWidget,5,30) fuzzy-if(skiaContent,16,10) == fieldset.html fieldset-r fuzzy-if(winWidget,5,30) fuzzy-if(skiaContent,16,10) == fieldset-inset.html fieldset-inset-ref.html # minor anti-aliasing problem on Windows == 1178575.html 1178575-ref.html == 1178575-2.html 1178575-2-ref.html -fuzzy(159,2) fails-if(!d2d) == 1212823-1.html 1212823-1-ref.html +fuzzy(159,2) fails-if(!dwrite) == 1212823-1.html 1212823-1-ref.html == boxshadow-large-offset.html boxshadow-large-offset-ref.html diff --git a/layout/reftests/bugs/reftest.list b/layout/reftests/bugs/reftest.list index 31cc55372026..b6113dd23506 100644 --- a/layout/reftests/bugs/reftest.list +++ b/layout/reftests/bugs/reftest.list @@ -1565,7 +1565,7 @@ skip-if(B2G||Mulet) == 569006-1.html 569006-1-ref.html # Initial mulet triage: p random-if(!winWidget) fails-if(/^Windows\x20NT\x2010\.0/.test(http.oscpu)&&d2d) == 574907-1.html 574907-1-ref.html # Bug 1258240 random-if(!winWidget) fails-if(/^Windows\x20NT\x2010\.0/.test(http.oscpu)&&d2d) == 574907-2.html 574907-2-ref.html # Bug 1258240 # 574907-3 only worked under directwrite, and even there it now depends on the rendering mode; marking as random for now -random-if(!winWidget) fails-if(winWidget&&!d2d) random-if(winWidget&&d2d) != 574907-3.html 574907-3-notref.html +random-if(!winWidget) fails-if(winWidget&&!dwrite) random-if(winWidget&&dwrite) != 574907-3.html 574907-3-notref.html == 577838-1.html 577838-1-ref.html == 577838-2.html 577838-2-ref.html == 579323-1.html 579323-1-ref.html @@ -1574,7 +1574,7 @@ random-if(!winWidget) fails-if(winWidget&&!d2d) random-if(winWidget&&d2d) != 574 skip-if(!haveTestPlugin) skip-if(B2G||Mulet) fails-if(Android) == 579808-1.html 579808-1-ref.html # Initial mulet triage: parity with B2G/B2G Desktop skip-if(B2G||Mulet) fails-if(Android) random-if(layersGPUAccelerated) fuzzy-if(skiaContent,1,10000) == 579985-1.html 579985-1-ref.html # bug 623452 for WinXP; this bug was only for a regression in BasicLayers anyway # Initial mulet triage: parity with B2G/B2G Desktop skip-if(B2G||Mulet) skip-if(Android) == 580160-1.html 580160-1-ref.html # bug 920927 for Android; issues without the test-plugin # Initial mulet triage: parity with B2G/B2G Desktop -fuzzy-if(asyncPan&&!layersGPUAccelerated,255,33) HTTP(..) == 580863-1.html 580863-1-ref.html +fuzzy-if(asyncPan&&!layersGPUAccelerated,255,141) HTTP(..) == 580863-1.html 580863-1-ref.html skip-if(B2G||Mulet) fails-if(Android) random-if(layersGPUAccelerated) fuzzy-if(skiaContent,1,6436) == 581317-1.html 581317-1-ref.html # Initial mulet triage: parity with B2G/B2G Desktop == 581579-1.html 581579-1-ref.html == 582037-1a.html 582037-1-ref.html diff --git a/layout/reftests/columns/reftest.list b/layout/reftests/columns/reftest.list index 2b7dd0bcba09..fb68d06f57d0 100644 --- a/layout/reftests/columns/reftest.list +++ b/layout/reftests/columns/reftest.list @@ -34,4 +34,4 @@ skip-if(B2G||Mulet) == columnfill-overflow.html columnfill-overflow-ref.html # b == columnrule-overflow.html columnrule-overflow-ref.html == columns-table-caption-000.html columns-table-caption-000-ref.html == positioning-transforms-bug1112501.html positioning-transforms-bug1112501-ref.html -fuzzy-if(browserIsRemote&&winWidget,121,221) == fieldset-columns-001.html fieldset-columns-001-ref.html +fuzzy-if(browserIsRemote&&winWidget,121,276) == fieldset-columns-001.html fieldset-columns-001-ref.html diff --git a/layout/reftests/forms/fieldset/reftest.list b/layout/reftests/forms/fieldset/reftest.list index 75b590e6ae5e..56c8440cb236 100644 --- a/layout/reftests/forms/fieldset/reftest.list +++ b/layout/reftests/forms/fieldset/reftest.list @@ -5,7 +5,7 @@ fuzzy-if(skiaContent,2,13) == dynamic-legend-scroll-1.html dynamic-legend-scroll == fieldset-scroll-1.html fieldset-scroll-1-ref.html == fieldset-scrolled-1.html fieldset-scrolled-1-ref.html random-if(B2G||Mulet) == fieldset-overflow-auto-1.html fieldset-overflow-auto-1-ref.html # Initial mulet triage: parity with B2G/B2G Desktop -fuzzy-if(winWidget&&!layersGPUAccelerated,121,221) == positioned-container-1.html positioned-container-1-ref.html +fuzzy-if(winWidget&&!layersGPUAccelerated,121,276) == positioned-container-1.html positioned-container-1-ref.html == relpos-legend-1.html relpos-legend-1-ref.html == relpos-legend-2.html relpos-legend-2-ref.html skip-if((B2G&&browserIsRemote)||Mulet) == sticky-legend-1.html sticky-legend-1-ref.html # Initial mulet triage: parity with B2G/B2G Desktop diff --git a/layout/reftests/forms/input/text/reftest.list b/layout/reftests/forms/input/text/reftest.list index fec770bbd0a7..e5c1584228e5 100644 --- a/layout/reftests/forms/input/text/reftest.list +++ b/layout/reftests/forms/input/text/reftest.list @@ -1,5 +1,5 @@ == bounds-1.html bounds-1-ref.html -fuzzy-if(asyncPan&&!layersGPUAccelerated,121,84) == size-1.html size-1-ref.html +fuzzy-if(asyncPan&&!layersGPUAccelerated,121,111) == size-1.html size-1-ref.html skip-if(B2G||Mulet) == size-2.html size-2-ref.html # Initial mulet triage: parity with B2G/B2G Desktop HTTP(..) == baseline-1.html baseline-1-ref.html skip-if((B2G&&browserIsRemote)||Mulet) HTTP(..) == centering-1.xul centering-1-ref.xul # bug 974780 # Initial mulet triage: parity with B2G/B2G Desktop diff --git a/layout/reftests/mathml/reftest.list b/layout/reftests/mathml/reftest.list index 8afb1082bf89..ef7a8e86ec63 100644 --- a/layout/reftests/mathml/reftest.list +++ b/layout/reftests/mathml/reftest.list @@ -204,7 +204,7 @@ random-if(winWidget&&!d2d) == opentype-stretchy.html opentype-stretchy-ref.html == operator-1.xhtml operator-1-ref.xhtml == scriptshift-1.xhtml scriptshift-1-ref.xhtml == number-size-1.xhtml number-size-1-ref.xhtml -random-if((B2G&&browserIsRemote)||Mulet) fails-if(winWidget&&/^Windows\x20NT\x205\.1/.test(http.oscpu)) fuzzy-if(skiaContent,1,80) == multiscripts-1.html multiscripts-1-ref.html # B2G - slight height variation from font metrics # Initial mulet triage: parity with B2G/B2G Desktop +random-if((B2G&&browserIsRemote)||Mulet) fuzzy-if(skiaContent,1,80) fails-if(winWidget&&/^Windows\x20NT\x205\.1/.test(http.oscpu)) == multiscripts-1.html multiscripts-1-ref.html # B2G - slight height variation from font metrics # Initial mulet triage: parity with B2G/B2G Desktop == mathml-mmultiscript-base.html mathml-mmultiscript-base-ref.html == mathml-mmultiscript-mprescript.html mathml-mmultiscript-mprescript-ref.html != menclose-1a.html menclose-1-ref.html diff --git a/layout/reftests/position-dynamic-changes/relative/reftest.list b/layout/reftests/position-dynamic-changes/relative/reftest.list index 28da9dea4ef8..a3f4ab47723c 100644 --- a/layout/reftests/position-dynamic-changes/relative/reftest.list +++ b/layout/reftests/position-dynamic-changes/relative/reftest.list @@ -1,5 +1,5 @@ -fuzzy-if(cocoaWidget,1,2) fuzzy-if(d2d,47,26) fuzzy-if(asyncPan&&!layersGPUAccelerated,121,614) == move-right-bottom.html move-right-bottom-ref.html -fuzzy-if(cocoaWidget,1,2) fuzzy-if(asyncPan&&!layersGPUAccelerated,121,614) == move-top-left.html move-top-left-ref.html # Bug 688545 -fuzzy-if(cocoaWidget,1,3) fuzzy-if(asyncPan&&!layersGPUAccelerated,121,497) == move-right-bottom-table.html move-right-bottom-table-ref.html -fuzzy-if(cocoaWidget,1,3) fuzzy-if(asyncPan&&!layersGPUAccelerated,121,497) == move-top-left-table.html move-top-left-table-ref.html # Bug 688545 +fuzzy-if(cocoaWidget,1,2) fuzzy-if(d2d,47,26) fuzzy-if(asyncPan&&!layersGPUAccelerated,121,716) == move-right-bottom.html move-right-bottom-ref.html +fuzzy-if(cocoaWidget,1,2) fuzzy-if(asyncPan&&!layersGPUAccelerated,121,716) == move-top-left.html move-top-left-ref.html # Bug 688545 +fuzzy-if(cocoaWidget,1,3) fuzzy-if(asyncPan&&!layersGPUAccelerated,121,580) == move-right-bottom-table.html move-right-bottom-table-ref.html +fuzzy-if(cocoaWidget,1,3) fuzzy-if(asyncPan&&!layersGPUAccelerated,121,580) == move-top-left-table.html move-top-left-table-ref.html # Bug 688545 == percent.html percent-ref.html diff --git a/layout/reftests/position-sticky/reftest.list b/layout/reftests/position-sticky/reftest.list index dcd409112e35..31f6e62c8989 100644 --- a/layout/reftests/position-sticky/reftest.list +++ b/layout/reftests/position-sticky/reftest.list @@ -46,6 +46,6 @@ fails == column-contain-1a.html column-contain-1-ref.html == column-contain-2.html column-contain-2-ref.html == block-in-inline-1.html block-in-inline-1-ref.html fuzzy-if(skiaContent,1,22) fuzzy-if(winWidget&&!layersGPUAccelerated,116,1320) fuzzy-if(Android,8,1533) skip-if((B2G&&browserIsRemote)||Mulet) == block-in-inline-2.html block-in-inline-2-ref.html # Initial mulet triage: parity with B2G/B2G Desktop -fuzzy-if(winWidget&&!layersGPUAccelerated,116,1320) fuzzy-if(Android,8,630) fuzzy-if(OSX>=1008,1,11) skip-if((B2G&&browserIsRemote)||Mulet) fuzzy-if(skiaContent,1,124) == block-in-inline-3.html block-in-inline-3-ref.html # Initial mulet triage: parity with B2G/B2G Desktop +fuzzy-if(Android,8,630) fuzzy-if(OSX>=1008,1,11) skip-if((B2G&&browserIsRemote)||Mulet) fuzzy-if(skiaContent,1,124) fuzzy-if(winWidget&&!layersGPUAccelerated,116,1320) == block-in-inline-3.html block-in-inline-3-ref.html # Initial mulet triage: parity with B2G/B2G Desktop == block-in-inline-continuations.html block-in-inline-continuations-ref.html -fuzzy-if(winWidget&&!layersGPUAccelerated,121,111) == inner-table-1.html inner-table-1-ref.html +fuzzy-if(winWidget&&!layersGPUAccelerated,121,140) == inner-table-1.html inner-table-1-ref.html diff --git a/layout/reftests/scrolling/reftest.list b/layout/reftests/scrolling/reftest.list index 48cb87cad3cc..84a7d7678fdf 100644 --- a/layout/reftests/scrolling/reftest.list +++ b/layout/reftests/scrolling/reftest.list @@ -28,11 +28,11 @@ skip-if(B2G||Mulet) fuzzy-if(d2d,1,4) HTTP == transformed-1.html transformed-1.h HTTP == transformed-1.html?up transformed-1.html?ref fuzzy-if(Android,5,20000) == uncovering-1.html uncovering-1-ref.html fuzzy-if(Android,5,20000) == uncovering-2.html uncovering-2-ref.html -skip-if(B2G||Mulet) fuzzy-if(asyncPan&&!layersGPUAccelerated,121,3721) == less-than-scrollbar-height.html less-than-scrollbar-height-ref.html # Initial mulet triage: parity with B2G/B2G Desktop +skip-if(B2G||Mulet) fuzzy-if(asyncPan&&!layersGPUAccelerated,121,4520) == less-than-scrollbar-height.html less-than-scrollbar-height-ref.html # Initial mulet triage: parity with B2G/B2G Desktop skip-if(B2G||Mulet) == huge-horizontal-overflow.html huge-horizontal-overflow-ref.html # Initial mulet triage: parity with B2G/B2G Desktop skip-if(B2G||Mulet) == huge-vertical-overflow.html huge-vertical-overflow-ref.html # Initial mulet triage: parity with B2G/B2G Desktop fuzzy-if(asyncPan&&!layersGPUAccelerated,102,6818) == iframe-scrolling-attr-1.html iframe-scrolling-attr-ref.html -skip-if((B2G&&browserIsRemote)||Mulet) fuzzy-if(asyncPan&&!layersGPUAccelerated,102,6818) == iframe-scrolling-attr-2.html iframe-scrolling-attr-ref.html # Initial mulet triage: parity with B2G/B2G Desktop +skip-if((B2G&&browserIsRemote)||Mulet) fuzzy-if(asyncPan&&!layersGPUAccelerated,121,6818) == iframe-scrolling-attr-2.html iframe-scrolling-attr-ref.html # Initial mulet triage: parity with B2G/B2G Desktop == frame-scrolling-attr-1.html frame-scrolling-attr-ref.html fuzzy-if(asyncPan&&!layersGPUAccelerated,102,2420) == frame-scrolling-attr-2.html frame-scrolling-attr-ref.html == move-item.html move-item-ref.html # bug 1125750 diff --git a/layout/reftests/svg/text/reftest.list b/layout/reftests/svg/text/reftest.list index 492851de81a4..5edef4c6b218 100644 --- a/layout/reftests/svg/text/reftest.list +++ b/layout/reftests/svg/text/reftest.list @@ -5,7 +5,7 @@ == simple-anchor-end-bidi.svg simple-anchor-end-bidi-ref.html == simple-anchor-end-rtl.svg simple-anchor-end-rtl-ref.html == simple-anchor-end.svg simple-anchor-end-ref.html -== simple-anchor-middle-bidi.svg simple-anchor-middle-bidi-ref.html +fuzzy-if(skiaContent&&dwrite,103,131) == simple-anchor-middle-bidi.svg simple-anchor-middle-bidi-ref.html == simple-anchor-middle-rtl.svg simple-anchor-middle-rtl-ref.html fuzzy-if(skiaContent,111,81) == simple-anchor-middle.svg simple-anchor-middle-ref.html == simple-bidi.svg simple-bidi-ref.html @@ -171,20 +171,20 @@ fuzzy-if(!d2d,14,2) fuzzy-if(azureQuartz,1,6) fuzzy-if(skiaContent,1,200) == dyn == dynamic-text-shadow.svg text-shadow-ref.svg # text and masks -fuzzy-if(skiaContent&&winWidget,39,224) HTTP(../..) == mask-applied.svg mask-applied-ref.svg +fuzzy-if(skiaContent&&winWidget,50,224) HTTP(../..) == mask-applied.svg mask-applied-ref.svg fuzzy-if(skiaContent&&winWidget,77,56) HTTP(../..) == mask-content.svg mask-content-ref.svg -fuzzy-if(skiaContent&&winWidget,39,112) HTTP(../..) == mask-content-2.svg mask-content-2-ref.svg +fuzzy-if(skiaContent&&winWidget,50,112) HTTP(../..) == mask-content-2.svg mask-content-2-ref.svg # text and clipPaths HTTP(../..) == clipPath-applied.svg clipPath-applied-ref.svg fuzzy-if(skiaContent&&winWidget,77,56) HTTP(../..) == clipPath-content.svg clipPath-content-ref.svg -fuzzy-if(skiaContent&&winWidget,39,112) HTTP(../..) == clipPath-content-2.svg clipPath-content-2-ref.svg +fuzzy-if(skiaContent&&winWidget,50,112) HTTP(../..) == clipPath-content-2.svg clipPath-content-2-ref.svg # text and patterns fuzzy-if(cocoaWidget,1,6) == pattern-content.svg pattern-content-ref.svg # text and filters -fuzzy-if(skiaContent&&winWidget,109,336) HTTP(../..) == filter-applied.svg filter-applied-ref.svg +fuzzy-if(skiaContent&&winWidget,122,336) HTTP(../..) == filter-applied.svg filter-applied-ref.svg # vertical text fuzzy-if(skiaContent,1,80) == textpath-vertical-dx.svg textpath-vertical-dx-ref.svg diff --git a/layout/reftests/text-overflow/reftest.list b/layout/reftests/text-overflow/reftest.list index d1b43b623825..5a85ea8e8200 100644 --- a/layout/reftests/text-overflow/reftest.list +++ b/layout/reftests/text-overflow/reftest.list @@ -4,7 +4,7 @@ fuzzy-if(Android,16,244) skip-if(B2G||Mulet) HTTP(..) == marker-basic.html marke skip-if(B2G||Mulet) HTTP(..) == marker-string.html marker-string-ref.html # Initial mulet triage: parity with B2G/B2G Desktop skip-if(Android||B2G) HTTP(..) == bidi-simple.html bidi-simple-ref.html # Fails on Android due to anti-aliasing skip-if(!gtkWidget) fuzzy-if(gtkWidget,2,289) HTTP(..) == bidi-simple-scrolled.html bidi-simple-scrolled-ref.html # Fails on Windows and OSX due to anti-aliasing -skip-if(B2G||Mulet) fuzzy-if(Android,24,4000) fuzzy-if(cocoaWidget,1,40) fuzzy-if(asyncPan&&!layersGPUAccelerated,121,1770) HTTP(..) == scroll-rounding.html scroll-rounding-ref.html # bug 760264 # Initial mulet triage: parity with B2G/B2G Desktop +skip-if(B2G||Mulet) fuzzy-if(Android,24,4000) fuzzy-if(cocoaWidget,1,40) fuzzy-if(asyncPan&&!layersGPUAccelerated,121,1836) HTTP(..) == scroll-rounding.html scroll-rounding-ref.html # bug 760264 # Initial mulet triage: parity with B2G/B2G Desktop fuzzy(2,453) fuzzy-if(skiaContent,9,2100) HTTP(..) == anonymous-block.html anonymous-block-ref.html skip-if(B2G||Mulet) HTTP(..) == false-marker-overlap.html false-marker-overlap-ref.html # Initial mulet triage: parity with B2G/B2G Desktop HTTP(..) == visibility-hidden.html visibility-hidden-ref.html diff --git a/layout/reftests/text/reftest.list b/layout/reftests/text/reftest.list index 2c29b18da551..1bcb2c275e74 100644 --- a/layout/reftests/text/reftest.list +++ b/layout/reftests/text/reftest.list @@ -24,7 +24,7 @@ HTTP(..) load ligature-with-space-1.html == line-editing-1c.html line-editing-1-ref.html == line-editing-1d.html line-editing-1-ref.html == line-editing-1e.html line-editing-1-ref.html -fails-if(cocoaWidget||(winWidget&&d2d&&layersGPUAccelerated)||(winWidget&&skiaContent&&layersGPUAccelerated)) HTTP(..) == lineheight-metrics-1.html lineheight-metrics-1-ref.html # bug 657864 +fails-if(cocoaWidget||(winWidget&&dwrite)) HTTP(..) == lineheight-metrics-1.html lineheight-metrics-1-ref.html # bug 657864 HTTP(..) == lineheight-metrics-2a.html lineheight-metrics-2-ref.html HTTP(..) == lineheight-metrics-2b.html lineheight-metrics-2-ref.html == lineheight-percentage-1.html lineheight-percentage-1-ref.html diff --git a/layout/reftests/transform-3d/reftest.list b/layout/reftests/transform-3d/reftest.list index d98caf7416f4..732dcfb0e3e1 100644 --- a/layout/reftests/transform-3d/reftest.list +++ b/layout/reftests/transform-3d/reftest.list @@ -11,7 +11,7 @@ == rotatex-perspective-1c.html rotatex-1-ref.html == rotatex-perspective-3a.html rotatex-perspective-3-ref.html == scalez-1a.html scalez-1-ref.html -fuzzy-if(gtkWidget||winWidget,8,376) fuzzy-if(Android,8,441) fuzzy-if(cocoaWidget,17,4) fuzzy-if(skiaContent,16,250) == preserve3d-1a.html preserve3d-1-ref.html +fuzzy-if(gtkWidget||winWidget,8,376) fuzzy-if(Android,8,441) fuzzy-if(cocoaWidget,17,4) fuzzy-if(skiaContent,16,281) == preserve3d-1a.html preserve3d-1-ref.html == preserve3d-1b.html about:blank == preserve3d-clipped.html about:blank == preserve3d-2a.html preserve3d-2-ref.html diff --git a/layout/reftests/writing-mode/reftest.list b/layout/reftests/writing-mode/reftest.list index 5dba703efa4b..c854050af276 100644 --- a/layout/reftests/writing-mode/reftest.list +++ b/layout/reftests/writing-mode/reftest.list @@ -35,7 +35,7 @@ fails == 1102175-1a.html 1102175-1-ref.html == 1106669-1-intrinsic-for-container.html 1106669-1-intrinsic-for-container-ref.html == 1108923-1-percentage-margins.html 1108923-1-percentage-margins-ref.html == 1111944-1-list-marker.html 1111944-1-list-marker-ref.html -fuzzy(116,94) HTTP(..) == 1115916-1-vertical-metrics.html 1115916-1-vertical-metrics-ref.html +fuzzy(116,94) fuzzy-if(skiaContent&&dwrite,119,124) HTTP(..) == 1115916-1-vertical-metrics.html 1115916-1-vertical-metrics-ref.html == 1117210-1-vertical-baseline-snap.html 1117210-1-vertical-baseline-snap-ref.html == 1117227-1-text-overflow.html 1117227-1-text-overflow-ref.html == 1122366-1-margin-collapse.html 1122366-1-margin-collapse-ref.html diff --git a/layout/reftests/xul/reftest.list b/layout/reftests/xul/reftest.list index 6535802c0f2f..77f7e7755b73 100644 --- a/layout/reftests/xul/reftest.list +++ b/layout/reftests/xul/reftest.list @@ -5,7 +5,7 @@ random-if(Android||B2G) fails-if(winWidget) skip-if((B2G&&browserIsRemote)||Mule skip-if((B2G&&browserIsRemote)||Mulet) == textbox-overflow-1.xul textbox-overflow-1-ref.xul # for bug 749658 # Initial mulet triage: parity with B2G/B2G Desktop # accesskeys are not normally displayed on Mac, so skip this test skip-if(cocoaWidget) skip-if((B2G&&browserIsRemote)||Mulet) == accesskey.xul accesskey-ref.xul # Initial mulet triage: parity with B2G/B2G Desktop -fails-if(cocoaWidget) fails-if(browserIsRemote&&d2d) fuzzy-if(xulRuntime.widgetToolkit=="gtk3",1,11) skip-if((B2G&&browserIsRemote)||Mulet) == tree-row-outline-1.xul tree-row-outline-1-ref.xul # Initial mulet triage: parity with B2G/B2G Desktop, win8: bug 1254832 +fails-if(cocoaWidget) fails-if(browserIsRemote&&dwrite) fuzzy-if(xulRuntime.widgetToolkit=="gtk3",1,11) skip-if((B2G&&browserIsRemote)||Mulet) == tree-row-outline-1.xul tree-row-outline-1-ref.xul # Initial mulet triage: parity with B2G/B2G Desktop, win8: bug 1254832 skip-if((B2G&&browserIsRemote)||Mulet) != tree-row-outline-1.xul tree-row-outline-1-notref.xul # Initial mulet triage: parity with B2G/B2G Desktop skip-if((B2G&&browserIsRemote)||Mulet) == text-small-caps-1.xul text-small-caps-1-ref.xul # Initial mulet triage: parity with B2G/B2G Desktop skip-if((B2G&&browserIsRemote)||Mulet) fuzzy-if(skiaContent,1,60) fuzzy-if(cocoaWidget&&browserIsRemote&&!skiaContent,1,31) fuzzy-if(winWidget&&browserIsRemote&&layersGPUAccelerated,1,50) == inactive-fixed-bg-bug1205630.xul inactive-fixed-bg-bug1205630-ref.html diff --git a/modules/libpref/init/all.js b/modules/libpref/init/all.js index b492f1929a65..b3b0bb4f4ae4 100644 --- a/modules/libpref/init/all.js +++ b/modules/libpref/init/all.js @@ -753,7 +753,7 @@ pref("gfx.font_rendering.opentype_svg.enabled", true); // comma separated list of backends to use in order of preference // e.g., pref("gfx.canvas.azure.backends", "direct2d,skia,cairo"); pref("gfx.canvas.azure.backends", "direct2d1.1,skia,cairo"); -pref("gfx.content.azure.backends", "direct2d1.1,cairo"); +pref("gfx.content.azure.backends", "direct2d1.1,skia,cairo"); #else #ifdef XP_MACOSX pref("gfx.content.azure.backends", "skia"); diff --git a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-002a.html.ini b/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-002a.html.ini deleted file mode 100644 index 9c0e6c1e1935..000000000000 --- a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-002a.html.ini +++ /dev/null @@ -1,7 +0,0 @@ -[dir-isolation-002a.html] - type: reftest - expected: - if debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL diff --git a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-002b.html.ini b/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-002b.html.ini deleted file mode 100644 index a9b6334a56c1..000000000000 --- a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-002b.html.ini +++ /dev/null @@ -1,8 +0,0 @@ -[dir-isolation-002b.html] - type: reftest - expected: - if debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL diff --git a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-002c.html.ini b/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-002c.html.ini deleted file mode 100644 index 2295b85c47a9..000000000000 --- a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-002c.html.ini +++ /dev/null @@ -1,8 +0,0 @@ -[dir-isolation-002c.html] - type: reftest - expected: - if debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL diff --git a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-006a.html.ini b/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-006a.html.ini deleted file mode 100644 index 855d556093c6..000000000000 --- a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-006a.html.ini +++ /dev/null @@ -1,7 +0,0 @@ -[dir-isolation-006a.html] - type: reftest - expected: - if debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL diff --git a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-006b.html.ini b/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-006b.html.ini deleted file mode 100644 index 9f3e7ef6f3b9..000000000000 --- a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-006b.html.ini +++ /dev/null @@ -1,8 +0,0 @@ -[dir-isolation-006b.html] - type: reftest - expected: - if debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL diff --git a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-006c.html.ini b/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-006c.html.ini deleted file mode 100644 index b9a6937fac89..000000000000 --- a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-006c.html.ini +++ /dev/null @@ -1,8 +0,0 @@ -[dir-isolation-006c.html] - type: reftest - expected: - if debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL diff --git a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-009a.html.ini b/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-009a.html.ini deleted file mode 100644 index ad1eb20d4ca3..000000000000 --- a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-009a.html.ini +++ /dev/null @@ -1,8 +0,0 @@ -[dir-isolation-009a.html] - type: reftest - expected: - if debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL diff --git a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-009b.html.ini b/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-009b.html.ini deleted file mode 100644 index 0768172c451c..000000000000 --- a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-009b.html.ini +++ /dev/null @@ -1,8 +0,0 @@ -[dir-isolation-009b.html] - type: reftest - expected: - if debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL diff --git a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-009c.html.ini b/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-009c.html.ini deleted file mode 100644 index a392992382fb..000000000000 --- a/testing/web-platform/meta/html/dom/elements/requirements-relating-to-bidirectional-algorithm-formatting-characters/dir-isolation-009c.html.ini +++ /dev/null @@ -1,7 +0,0 @@ -[dir-isolation-009c.html] - type: reftest - expected: - if debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if not debug and not e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL - if debug and e10s and (os == "win") and (version == "6.1.7601") and (processor == "x86") and (bits == 32): FAIL From 16258149e3dbe33ced67894481c641660193c624 Mon Sep 17 00:00:00 2001 From: Benjamin Smedberg Date: Wed, 24 Aug 2016 12:40:17 -0400 Subject: [PATCH 021/105] Bug 1293062 - Plugin permissions are confused between Flash and the VLC plugin. Fix this by checking that the plugin name for the special Flash plugin is "Shockwave Flash", which is true of Adobe Flash but not replacement plugins such as VLC or even gnash. This causes other plugins to have their own pref tag so that users can enable/disable them separately. r=jimm MozReview-Commit-ID: 3sGKO4S3U8U --HG-- extra : rebase_source : e72b15f6de6e0f8e2c4307f2d37301d138001a86 --- dom/plugins/base/nsPluginTags.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/dom/plugins/base/nsPluginTags.cpp b/dom/plugins/base/nsPluginTags.cpp index 8ba9e0f218a2..02fe913b19f4 100644 --- a/dom/plugins/base/nsPluginTags.cpp +++ b/dom/plugins/base/nsPluginTags.cpp @@ -360,8 +360,12 @@ void nsPluginTag::InitMime(const char* const* aMimeTypes, mSupportsAsyncInit = true; break; case nsPluginHost::eSpecialType_Flash: - mIsFlashPlugin = true; - mSupportsAsyncInit = true; + // VLC sometimes claims to implement the Flash MIME type, and we want + // to allow users to control that separately from Adobe Flash. + if (Name().EqualsLiteral("Shockwave Flash")) { + mIsFlashPlugin = true; + mSupportsAsyncInit = true; + } break; case nsPluginHost::eSpecialType_Silverlight: case nsPluginHost::eSpecialType_Unity: From 2c15b0b1f8f7a03b444ffcd86e1c45c14cca9ddc Mon Sep 17 00:00:00 2001 From: Wes Kocher Date: Thu, 25 Aug 2016 13:02:17 -0700 Subject: [PATCH 022/105] Backed out 2 changesets (bug 1246972) for marSuccessComplete.js failures a=backout Backed out changeset 4576637003b6 (bug 1246972) Backed out changeset c079fb045b9d (bug 1246972) --HG-- extra : rebase_source : 3a3acdca0561b777bb35f73746766904b21a7f00 --- toolkit/mozapps/update/common/errors.h | 3 +- toolkit/mozapps/update/tests/chrome/utils.js | 4 +- .../update/tests/data/sharedUpdateXML.js | 18 +- .../update/tests/data/xpcshellUtilsAUS.js | 18 +- .../marWrongApplyToDirFailure_win.js | 39 -- .../tests/unit_base_updater/xpcshell.ini | 2 - toolkit/mozapps/update/updater/updater.cpp | 445 ++++++++---------- 7 files changed, 199 insertions(+), 330 deletions(-) delete mode 100644 toolkit/mozapps/update/tests/unit_base_updater/marWrongApplyToDirFailure_win.js diff --git a/toolkit/mozapps/update/common/errors.h b/toolkit/mozapps/update/common/errors.h index fa83c21d4ab1..33ee98c56af5 100644 --- a/toolkit/mozapps/update/common/errors.h +++ b/toolkit/mozapps/update/common/errors.h @@ -83,9 +83,8 @@ #define WRITE_ERROR_DELETE_BACKUP 69 #define WRITE_ERROR_EXTRACT 70 #define REMOVE_FILE_SPEC_ERROR 71 -#define INVALID_APPLYTO_DIR_STAGED_ERROR 72 +#define INVALID_STAGED_PARENT_ERROR 72 #define LOCK_ERROR_PATCH_FILE 73 -#define INVALID_APPLYTO_DIR_ERROR 74 // Error codes 80 through 99 are reserved for nsUpdateService.js diff --git a/toolkit/mozapps/update/tests/chrome/utils.js b/toolkit/mozapps/update/tests/chrome/utils.js index e49f2ec22831..64f32d5cb350 100644 --- a/toolkit/mozapps/update/tests/chrome/utils.js +++ b/toolkit/mozapps/update/tests/chrome/utils.js @@ -747,7 +747,7 @@ function verifyTestsRan() { */ function setupFiles() { // Backup the updater-settings.ini file if it exists by moving it. - let baseAppDir = getGREDir(); + let baseAppDir = getAppBaseDir(); let updateSettingsIni = baseAppDir.clone(); updateSettingsIni.append(FILE_UPDATE_SETTINGS_INI); if (updateSettingsIni.exists()) { @@ -902,7 +902,7 @@ function setupPrefs() { */ function resetFiles() { // Restore the backed up updater-settings.ini if it exists. - let baseAppDir = getGREDir(); + let baseAppDir = getAppBaseDir(); let updateSettingsIni = baseAppDir.clone(); updateSettingsIni.append(FILE_UPDATE_SETTINGS_INI_BAK); if (updateSettingsIni.exists()) { diff --git a/toolkit/mozapps/update/tests/data/sharedUpdateXML.js b/toolkit/mozapps/update/tests/data/sharedUpdateXML.js index 14c2c6ca53ea..c6da47909aa6 100644 --- a/toolkit/mozapps/update/tests/data/sharedUpdateXML.js +++ b/toolkit/mozapps/update/tests/data/sharedUpdateXML.js @@ -35,14 +35,12 @@ const STATE_SUCCEEDED = "succeeded"; const STATE_DOWNLOAD_FAILED = "download-failed"; const STATE_FAILED = "failed"; -const LOADSOURCE_ERROR_WRONG_SIZE = 2; -const CRC_ERROR = 4; -const READ_ERROR = 6; -const WRITE_ERROR = 7; -const MAR_CHANNEL_MISMATCH_ERROR = 22; -const VERSION_DOWNGRADE_ERROR = 23; -const INVALID_APPLYTO_DIR_STAGED_ERROR = 72; -const INVALID_APPLYTO_DIR_ERROR = 74; +const LOADSOURCE_ERROR_WRONG_SIZE = 2; +const CRC_ERROR = 4; +const READ_ERROR = 6; +const WRITE_ERROR = 7; +const MAR_CHANNEL_MISMATCH_ERROR = 22; +const VERSION_DOWNGRADE_ERROR = 23; const STATE_FAILED_DELIMETER = ": "; @@ -58,10 +56,6 @@ const STATE_FAILED_MAR_CHANNEL_MISMATCH_ERROR = STATE_FAILED + STATE_FAILED_DELIMETER + MAR_CHANNEL_MISMATCH_ERROR; const STATE_FAILED_VERSION_DOWNGRADE_ERROR = STATE_FAILED + STATE_FAILED_DELIMETER + VERSION_DOWNGRADE_ERROR; -const STATE_FAILED_INVALID_APPLYTO_DIR_STAGED_ERROR = - STATE_FAILED + STATE_FAILED_DELIMETER + INVALID_APPLYTO_DIR_STAGED_ERROR; -const STATE_FAILED_INVALID_APPLYTO_DIR_ERROR = - STATE_FAILED + STATE_FAILED_DELIMETER + INVALID_APPLYTO_DIR_ERROR; /** * Constructs a string representing a remote update xml file. diff --git a/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js b/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js index a4da2aa3ac1a..5c46960ef450 100644 --- a/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js +++ b/toolkit/mozapps/update/tests/data/xpcshellUtilsAUS.js @@ -155,8 +155,6 @@ var gGREDirOrig; var gGREBinDirOrig; var gAppDirOrig; -var gApplyToDirOverride; - var gServiceLaunchedCallbackLog = null; var gServiceLaunchedCallbackArgs = null; @@ -1139,18 +1137,6 @@ function getAppVersion() { return iniParser.getString("App", "Version"); } -/** - * Override the apply-to directory parameter to be passed to the updater. - * This ought to cause the updater to fail when using any value that isn't the - * default, automatically computed one. - * - * @param dir - * Complete string to use as the apply-to directory parameter. - */ -function overrideApplyToDir(dir) { - gApplyToDirOverride = dir; -} - /** * Helper function for getting the relative path to the directory where the * application binary is located (e.g. /dir.app/). @@ -1720,10 +1706,10 @@ function runUpdateUsingUpdater(aExpectedStatus, aSwitchApp, aExpectedExitValue) let args = [updatesDirPath, applyToDirPath]; if (aSwitchApp) { - args[2] = gApplyToDirOverride || stageDirPath; + args[2] = stageDirPath; args[3] = "0/replace"; } else { - args[2] = gApplyToDirOverride || applyToDirPath; + args[2] = applyToDirPath; args[3] = "0"; } args = args.concat([callbackApp.parent.path, callbackApp.path]); diff --git a/toolkit/mozapps/update/tests/unit_base_updater/marWrongApplyToDirFailure_win.js b/toolkit/mozapps/update/tests/unit_base_updater/marWrongApplyToDirFailure_win.js deleted file mode 100644 index 072d67729c7f..000000000000 --- a/toolkit/mozapps/update/tests/unit_base_updater/marWrongApplyToDirFailure_win.js +++ /dev/null @@ -1,39 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. - */ - -/* Test trying to use an apply-to directory different from the install - * directory, which should fail. - */ - -function run_test() { - if (!setupTestCommon()) { - return; - } - gTestFiles = gTestFilesCompleteSuccess; - gTestDirs = gTestDirsCompleteSuccess; - setTestFilesAndDirsForFailure(); - setupUpdaterTest(FILE_COMPLETE_MAR, false); -} - -/** - * Called after the call to setupUpdaterTest finishes. - */ -function setupUpdaterTestFinished() { - overrideApplyToDir(getApplyDirPath() + "/../NoSuchDir"); - // If execv is used the updater process will turn into the callback process - // and the updater's return code will be that of the callback process. - runUpdateUsingUpdater(STATE_FAILED_INVALID_APPLYTO_DIR_ERROR, false, - (USE_EXECV ? 0 : 1)); -} - -/** - * Called after the call to runUpdateUsingUpdater finishes. - */ -function runUpdateFinished() { - standardInit(); - checkPostUpdateRunningFile(false); - checkFilesAfterUpdateFailure(getApplyDirFile); - waitForFilesInUse(); -} diff --git a/toolkit/mozapps/update/tests/unit_base_updater/xpcshell.ini b/toolkit/mozapps/update/tests/unit_base_updater/xpcshell.ini index 40206798b8f8..81ef7053dd30 100644 --- a/toolkit/mozapps/update/tests/unit_base_updater/xpcshell.ini +++ b/toolkit/mozapps/update/tests/unit_base_updater/xpcshell.ini @@ -77,5 +77,3 @@ reason = bug 1164150 [marAppApplyUpdateStageSuccess.js] skip-if = toolkit == 'gonk' reason = bug 1164150 -[marWrongApplyToDirFailure_win.js] -skip-if = os != 'win' diff --git a/toolkit/mozapps/update/updater/updater.cpp b/toolkit/mozapps/update/updater/updater.cpp index 1cf901f0ae0e..550c29914b28 100644 --- a/toolkit/mozapps/update/updater/updater.cpp +++ b/toolkit/mozapps/update/updater/updater.cpp @@ -59,7 +59,6 @@ #include "mozilla/Compiler.h" #include "mozilla/Types.h" -#include "mozilla/UniquePtr.h" // Amount of the progress bar to use in each of the 3 update stages, // should total 100.0. @@ -321,7 +320,6 @@ static bool sIsOSUpdate = false; static NS_tchar* gDestPath; static NS_tchar gCallbackRelPath[MAXPATHLEN]; static NS_tchar gCallbackBackupPath[MAXPATHLEN]; -static NS_tchar gDeleteDirPath[MAXPATHLEN]; #endif static const NS_tchar kWhitespace[] = NS_T(" \t"); @@ -382,8 +380,9 @@ EnvHasValue(const char *name) return (val && *val); } +#ifdef XP_WIN /** - * Coverts a relative update path to a full path. + * Coverts a relative update path to a full path for Windows. * * @param relpath * The relative path to convert to a full path. @@ -392,56 +391,23 @@ EnvHasValue(const char *name) static NS_tchar* get_full_path(const NS_tchar *relpath) { - NS_tchar *destpath = sStagedUpdate ? gWorkingDirPath : gInstallDirPath; - size_t lendestpath = NS_tstrlen(destpath); + size_t lendestpath = NS_tstrlen(gDestPath); size_t lenrelpath = NS_tstrlen(relpath); - NS_tchar *s = new NS_tchar[lendestpath + lenrelpath + 2]; - if (!s) { + NS_tchar *s = (NS_tchar *) malloc((lendestpath + lenrelpath + 1) * sizeof(NS_tchar)); + if (!s) return nullptr; - } NS_tchar *c = s; - NS_tstrcpy(c, destpath); + NS_tstrcpy(c, gDestPath); c += lendestpath; - NS_tstrcat(c, NS_T("/")); - c++; - NS_tstrcat(c, relpath); c += lenrelpath; *c = NS_T('\0'); + c++; return s; } - -/** - * Converts a full update path into a relative path; reverses get_full_path. - * - * @param fullpath - * The absolute path to convert into a relative path. - * return pointer to the location within fullpath where the relative path starts - * or fullpath itself if it already looks relative. - */ -static const NS_tchar* -get_relative_path(const NS_tchar *fullpath) -{ - // If the path isn't absolute, just return it as-is. -#ifdef XP_WIN - if (fullpath[1] != ':' && fullpath[2] != '\\') { -#else - if (fullpath[0] != '/') { #endif - return fullpath; - } - - NS_tchar *prefix = sStagedUpdate ? gWorkingDirPath : gInstallDirPath; - - // If the path isn't long enough to be absolute, return it as-is. - if (NS_tstrlen(fullpath) <= NS_tstrlen(prefix)) { - return fullpath; - } - - return fullpath + NS_tstrlen(prefix) + 1; -} /** * Gets the platform specific path and performs simple checks to the path. If @@ -1002,18 +968,14 @@ static int backup_create(const NS_tchar *path) // Rename the backup of the specified file that was created by renaming it back // to the original file. -static int backup_restore(const NS_tchar *path, const NS_tchar *relPath) +static int backup_restore(const NS_tchar *path) { NS_tchar backup[MAXPATHLEN]; NS_tsnprintf(backup, sizeof(backup)/sizeof(backup[0]), NS_T("%s") BACKUP_EXT, path); - NS_tchar relBackup[MAXPATHLEN]; - NS_tsnprintf(relBackup, sizeof(relBackup) / sizeof(relBackup[0]), - NS_T("%s") BACKUP_EXT, relPath); - if (NS_taccess(backup, F_OK)) { - LOG(("backup_restore: backup file doesn't exist: " LOG_S, relBackup)); + LOG(("backup_restore: backup file doesn't exist: " LOG_S, backup)); return OK; } @@ -1021,16 +983,12 @@ static int backup_restore(const NS_tchar *path, const NS_tchar *relPath) } // Discard the backup of the specified file that was created by renaming it. -static int backup_discard(const NS_tchar *path, const NS_tchar *relPath) +static int backup_discard(const NS_tchar *path) { NS_tchar backup[MAXPATHLEN]; NS_tsnprintf(backup, sizeof(backup)/sizeof(backup[0]), NS_T("%s") BACKUP_EXT, path); - NS_tchar relBackup[MAXPATHLEN]; - NS_tsnprintf(relBackup, sizeof(relBackup) / sizeof(relBackup[0]), - NS_T("%s") BACKUP_EXT, relPath); - // Nothing to discard if (NS_taccess(backup, F_OK)) { return OK; @@ -1039,12 +997,12 @@ static int backup_discard(const NS_tchar *path, const NS_tchar *relPath) int rv = ensure_remove(backup); #if defined(XP_WIN) if (rv && !sStagedUpdate && !sReplaceRequest) { - LOG(("backup_discard: unable to remove: " LOG_S, relBackup)); + LOG(("backup_discard: unable to remove: " LOG_S, backup)); NS_tchar path[MAXPATHLEN]; - GetTempFileNameW(gDeleteDirPath, L"moz", 0, path); + GetTempFileNameW(DELETE_DIR, L"moz", 0, path); if (rename_file(backup, path)) { LOG(("backup_discard: failed to rename file:" LOG_S ", dst:" LOG_S, - relBackup, relPath)); + backup, path)); return WRITE_ERROR_DELETE_BACKUP; } // The MoveFileEx call to remove the file on OS reboot will fail if the @@ -1054,10 +1012,10 @@ static int backup_discard(const NS_tchar *path, const NS_tchar *relPath) // applied, on reinstall, and on uninstall. if (MoveFileEx(path, nullptr, MOVEFILE_DELAY_UNTIL_REBOOT)) { LOG(("backup_discard: file renamed and will be removed on OS " \ - "reboot: " LOG_S, relPath)); + "reboot: " LOG_S, path)); } else { LOG(("backup_discard: failed to schedule OS reboot removal of " \ - "file: " LOG_S, relPath)); + "file: " LOG_S, path)); } } #else @@ -1069,13 +1027,12 @@ static int backup_discard(const NS_tchar *path, const NS_tchar *relPath) } // Helper function for post-processing a temporary backup. -static void backup_finish(const NS_tchar *path, const NS_tchar *relPath, - int status) +static void backup_finish(const NS_tchar *path, int status) { if (status == OK) - backup_discard(path, relPath); + backup_discard(path); else - backup_restore(path, relPath); + backup_restore(path); } //----------------------------------------------------------------------------- @@ -1113,7 +1070,7 @@ private: class RemoveFile : public Action { public: - RemoveFile() : mSkip(0) { } + RemoveFile() : mFile(nullptr), mSkip(0) { } int Parse(NS_tchar *line); int Prepare(); @@ -1121,8 +1078,7 @@ public: void Finish(int status); private: - mozilla::UniquePtr mFile; - mozilla::UniquePtr mRelPath; + const NS_tchar *mFile; int mSkip; }; @@ -1131,18 +1087,9 @@ RemoveFile::Parse(NS_tchar *line) { // format "" - NS_tchar * validPath = get_valid_path(&line); - if (!validPath) { + mFile = get_valid_path(&line); + if (!mFile) return PARSE_ERROR; - } - - mRelPath = mozilla::MakeUnique(MAXPATHLEN); - NS_tstrcpy(mRelPath.get(), validPath); - - mFile.reset(get_full_path(validPath)); - if (!mFile) { - return PARSE_ERROR; - } return OK; } @@ -1151,33 +1098,33 @@ int RemoveFile::Prepare() { // Skip the file if it already doesn't exist. - int rv = NS_taccess(mFile.get(), F_OK); + int rv = NS_taccess(mFile, F_OK); if (rv) { mSkip = 1; mProgressCost = 0; return OK; } - LOG(("PREPARE REMOVEFILE " LOG_S, mRelPath.get())); + LOG(("PREPARE REMOVEFILE " LOG_S, mFile)); // Make sure that we're actually a file... struct NS_tstat_t fileInfo; - rv = NS_tstat(mFile.get(), &fileInfo); + rv = NS_tstat(mFile, &fileInfo); if (rv) { - LOG(("failed to read file status info: " LOG_S ", err: %d", mFile.get(), + LOG(("failed to read file status info: " LOG_S ", err: %d", mFile, errno)); return READ_ERROR; } if (!S_ISREG(fileInfo.st_mode)) { - LOG(("path present, but not a file: " LOG_S, mFile.get())); + LOG(("path present, but not a file: " LOG_S, mFile)); return DELETE_ERROR_EXPECTED_FILE; } - NS_tchar *slash = (NS_tchar *) NS_tstrrchr(mFile.get(), NS_T('/')); + NS_tchar *slash = (NS_tchar *) NS_tstrrchr(mFile, NS_T('/')); if (slash) { *slash = NS_T('\0'); - rv = NS_taccess(mFile.get(), W_OK); + rv = NS_taccess(mFile, W_OK); *slash = NS_T('/'); } else { rv = NS_taccess(NS_T("."), W_OK); @@ -1197,11 +1144,11 @@ RemoveFile::Execute() if (mSkip) return OK; - LOG(("EXECUTE REMOVEFILE " LOG_S, mRelPath.get())); + LOG(("EXECUTE REMOVEFILE " LOG_S, mFile)); // The file is checked for existence here and in Prepare since it might have // been removed by a separate instruction: bug 311099. - int rv = NS_taccess(mFile.get(), F_OK); + int rv = NS_taccess(mFile, F_OK); if (rv) { LOG(("file cannot be removed because it does not exist; skipping")); mSkip = 1; @@ -1209,7 +1156,7 @@ RemoveFile::Execute() } // Rename the old file. It will be removed in Finish. - rv = backup_create(mFile.get()); + rv = backup_create(mFile); if (rv) { LOG(("backup_create failed: %d", rv)); return rv; @@ -1224,15 +1171,15 @@ RemoveFile::Finish(int status) if (mSkip) return; - LOG(("FINISH REMOVEFILE " LOG_S, mRelPath.get())); + LOG(("FINISH REMOVEFILE " LOG_S, mFile)); - backup_finish(mFile.get(), mRelPath.get(), status); + backup_finish(mFile, status); } class RemoveDir : public Action { public: - RemoveDir() : mSkip(0) { } + RemoveDir() : mDir(nullptr), mSkip(0) { } virtual int Parse(NS_tchar *line); virtual int Prepare(); // check that the source dir exists @@ -1240,8 +1187,7 @@ public: virtual void Finish(int status); private: - mozilla::UniquePtr mDir; - mozilla::UniquePtr mRelPath; + const NS_tchar *mDir; int mSkip; }; @@ -1250,18 +1196,9 @@ RemoveDir::Parse(NS_tchar *line) { // format "/" - NS_tchar * validPath = get_valid_path(&line, true); - if (!validPath) { + mDir = get_valid_path(&line, true); + if (!mDir) return PARSE_ERROR; - } - - mRelPath = mozilla::MakeUnique(MAXPATHLEN); - NS_tstrcpy(mRelPath.get(), validPath); - - mDir.reset(get_full_path(validPath)); - if (!mDir) { - return PARSE_ERROR; - } return OK; } @@ -1270,30 +1207,30 @@ int RemoveDir::Prepare() { // We expect the directory to exist if we are to remove it. - int rv = NS_taccess(mDir.get(), F_OK); + int rv = NS_taccess(mDir, F_OK); if (rv) { mSkip = 1; mProgressCost = 0; return OK; } - LOG(("PREPARE REMOVEDIR " LOG_S "/", mRelPath.get())); + LOG(("PREPARE REMOVEDIR " LOG_S "/", mDir)); // Make sure that we're actually a dir. struct NS_tstat_t dirInfo; - rv = NS_tstat(mDir.get(), &dirInfo); + rv = NS_tstat(mDir, &dirInfo); if (rv) { - LOG(("failed to read directory status info: " LOG_S ", err: %d", mRelPath.get(), + LOG(("failed to read directory status info: " LOG_S ", err: %d", mDir, errno)); return READ_ERROR; } if (!S_ISDIR(dirInfo.st_mode)) { - LOG(("path present, but not a directory: " LOG_S, mRelPath.get())); + LOG(("path present, but not a directory: " LOG_S, mDir)); return DELETE_ERROR_EXPECTED_DIR; } - rv = NS_taccess(mDir.get(), W_OK); + rv = NS_taccess(mDir, W_OK); if (rv) { LOG(("access failed: %d, %d", rv, errno)); return WRITE_ERROR_DIR_ACCESS_DENIED; @@ -1308,11 +1245,11 @@ RemoveDir::Execute() if (mSkip) return OK; - LOG(("EXECUTE REMOVEDIR " LOG_S "/", mRelPath.get())); + LOG(("EXECUTE REMOVEDIR " LOG_S "/", mDir)); // The directory is checked for existence at every step since it might have // been removed by a separate instruction: bug 311099. - int rv = NS_taccess(mDir.get(), F_OK); + int rv = NS_taccess(mDir, F_OK); if (rv) { LOG(("directory no longer exists; skipping")); mSkip = 1; @@ -1327,11 +1264,11 @@ RemoveDir::Finish(int status) if (mSkip || status != OK) return; - LOG(("FINISH REMOVEDIR " LOG_S "/", mRelPath.get())); + LOG(("FINISH REMOVEDIR " LOG_S "/", mDir)); // The directory is checked for existence at every step since it might have // been removed by a separate instruction: bug 311099. - int rv = NS_taccess(mDir.get(), F_OK); + int rv = NS_taccess(mDir, F_OK); if (rv) { LOG(("directory no longer exists; skipping")); return; @@ -1339,9 +1276,9 @@ RemoveDir::Finish(int status) if (status == OK) { - if (NS_trmdir(mDir.get())) { + if (NS_trmdir(mDir)) { LOG(("non-fatal error removing directory: " LOG_S "/, rv: %d, err: %d", - mRelPath.get(), rv, errno)); + mDir, rv, errno)); } } } @@ -1349,7 +1286,9 @@ RemoveDir::Finish(int status) class AddFile : public Action { public: - AddFile() : mAdded(false) { } + AddFile() : mFile(nullptr) + , mAdded(false) + { } virtual int Parse(NS_tchar *line); virtual int Prepare(); @@ -1357,8 +1296,7 @@ public: virtual void Finish(int status); private: - mozilla::UniquePtr mFile; - mozilla::UniquePtr mRelPath; + const NS_tchar *mFile; bool mAdded; }; @@ -1367,18 +1305,9 @@ AddFile::Parse(NS_tchar *line) { // format "" - NS_tchar * validPath = get_valid_path(&line); - if (!validPath) { + mFile = get_valid_path(&line); + if (!mFile) return PARSE_ERROR; - } - - mRelPath = mozilla::MakeUnique(MAXPATHLEN); - NS_tstrcpy(mRelPath.get(), validPath); - - mFile.reset(get_full_path(validPath)); - if (!mFile) { - return PARSE_ERROR; - } return OK; } @@ -1386,7 +1315,7 @@ AddFile::Parse(NS_tchar *line) int AddFile::Prepare() { - LOG(("PREPARE ADD " LOG_S, mRelPath.get())); + LOG(("PREPARE ADD " LOG_S, mFile)); return OK; } @@ -1394,33 +1323,33 @@ AddFile::Prepare() int AddFile::Execute() { - LOG(("EXECUTE ADD " LOG_S, mRelPath.get())); + LOG(("EXECUTE ADD " LOG_S, mFile)); int rv; // First make sure that we can actually get rid of any existing file. - rv = NS_taccess(mFile.get(), F_OK); + rv = NS_taccess(mFile, F_OK); if (rv == 0) { - rv = backup_create(mFile.get()); + rv = backup_create(mFile); if (rv) return rv; } else { - rv = ensure_parent_dir(mFile.get()); + rv = ensure_parent_dir(mFile); if (rv) return rv; } #ifdef XP_WIN char sourcefile[MAXPATHLEN]; - if (!WideCharToMultiByte(CP_UTF8, 0, mRelPath.get(), -1, sourcefile, - MAXPATHLEN, nullptr, nullptr)) { + if (!WideCharToMultiByte(CP_UTF8, 0, mFile, -1, sourcefile, MAXPATHLEN, + nullptr, nullptr)) { LOG(("error converting wchar to utf8: %d", GetLastError())); return STRING_CONVERSION_ERROR; } - rv = gArchiveReader.ExtractFile(sourcefile, mFile.get()); + rv = gArchiveReader.ExtractFile(sourcefile, mFile); #else - rv = gArchiveReader.ExtractFile(mRelPath.get(), mFile.get()); + rv = gArchiveReader.ExtractFile(mFile, mFile); #endif if (!rv) { mAdded = true; @@ -1431,18 +1360,18 @@ AddFile::Execute() void AddFile::Finish(int status) { - LOG(("FINISH ADD " LOG_S, mRelPath.get())); + LOG(("FINISH ADD " LOG_S, mFile)); // When there is an update failure and a file has been added it is removed // here since there might not be a backup to replace it. if (status && mAdded) - NS_tremove(mFile.get()); - backup_finish(mFile.get(), mRelPath.get(), status); + NS_tremove(mFile); + backup_finish(mFile, status); } class PatchFile : public Action { public: - PatchFile() : mPatchFile(nullptr), mPatchIndex(-1), buf(nullptr) { } + PatchFile() : mPatchIndex(-1), buf(nullptr) { } virtual ~PatchFile(); @@ -1457,8 +1386,7 @@ private: static int sPatchIndex; const NS_tchar *mPatchFile; - mozilla::UniquePtr mFile; - mozilla::UniquePtr mFileRelPath; + const NS_tchar *mFile; int mPatchIndex; MBSPatchHeader header; unsigned char *buf; @@ -1497,7 +1425,7 @@ PatchFile::LoadSourceFile(FILE* ofile) int rv = fstat(fileno((FILE *)ofile), &os); if (rv) { LOG(("LoadSourceFile: unable to stat destination file: " LOG_S ", " \ - "err: %d", mFileRelPath.get(), errno)); + "err: %d", mFile, errno)); return READ_ERROR; } @@ -1519,7 +1447,7 @@ PatchFile::LoadSourceFile(FILE* ofile) size_t c = fread(rb, 1, count, ofile); if (c != count) { LOG(("LoadSourceFile: error reading destination file: " LOG_S, - mFileRelPath.get())); + mFile)); return READ_ERROR; } @@ -1557,15 +1485,7 @@ PatchFile::Parse(NS_tchar *line) return PARSE_ERROR; } - NS_tchar * validPath = get_valid_path(&line); - if (!validPath) { - return PARSE_ERROR; - } - - mFileRelPath = mozilla::MakeUnique(MAXPATHLEN); - NS_tstrcpy(mFileRelPath.get(), validPath); - - mFile.reset(get_full_path(validPath)); + mFile = get_valid_path(&line); if (!mFile) { return PARSE_ERROR; } @@ -1576,7 +1496,7 @@ PatchFile::Parse(NS_tchar *line) int PatchFile::Prepare() { - LOG(("PREPARE PATCH " LOG_S, mFileRelPath.get())); + LOG(("PREPARE PATCH " LOG_S, mFile)); // extract the patch to a temporary file mPatchIndex = sPatchIndex++; @@ -1617,7 +1537,7 @@ PatchFile::Prepare() int PatchFile::Execute() { - LOG(("EXECUTE PATCH " LOG_S, mFileRelPath.get())); + LOG(("EXECUTE PATCH " LOG_S, mFile)); fseek(mPatchStream, 0, SEEK_SET); @@ -1628,20 +1548,20 @@ PatchFile::Execute() FILE *origfile = nullptr; #ifdef XP_WIN - if (NS_tstrcmp(mFileRelPath.get(), gCallbackRelPath) == 0) { + if (NS_tstrcmp(mFile, gCallbackRelPath) == 0) { // Read from the copy of the callback when patching since the callback can't // be opened for reading to prevent the application from being launched. origfile = NS_tfopen(gCallbackBackupPath, NS_T("rb")); } else { - origfile = NS_tfopen(mFile.get(), NS_T("rb")); + origfile = NS_tfopen(mFile, NS_T("rb")); } #else - origfile = NS_tfopen(mFile.get(), NS_T("rb")); + origfile = NS_tfopen(mFile, NS_T("rb")); #endif if (!origfile) { - LOG(("unable to open destination file: " LOG_S ", err: %d", - mFileRelPath.get(), errno)); + LOG(("unable to open destination file: " LOG_S ", err: %d", mFile, + errno)); return READ_ERROR; } @@ -1655,20 +1575,20 @@ PatchFile::Execute() // Rename the destination file if it exists before proceeding so it can be // used to restore the file to its original state if there is an error. struct NS_tstat_t ss; - rv = NS_tstat(mFile.get(), &ss); + rv = NS_tstat(mFile, &ss); if (rv) { - LOG(("failed to read file status info: " LOG_S ", err: %d", - mFileRelPath.get(), errno)); + LOG(("failed to read file status info: " LOG_S ", err: %d", mFile, + errno)); return READ_ERROR; } - rv = backup_create(mFile.get()); + rv = backup_create(mFile); if (rv) { return rv; } #if defined(HAVE_POSIX_FALLOCATE) - AutoFile ofile(ensure_open(mFile.get(), NS_T("wb+"), ss.st_mode)); + AutoFile ofile(ensure_open(mFile, NS_T("wb+"), ss.st_mode)); posix_fallocate(fileno((FILE *)ofile), 0, header.dlen); #elif defined(XP_WIN) bool shouldTruncate = true; @@ -1679,7 +1599,7 @@ PatchFile::Execute() // 2. _get_osfhandle and then setting the size reduced fragmentation though // not completely. There are also reports of _get_osfhandle failing on // mingw. - HANDLE hfile = CreateFileW(mFile.get(), + HANDLE hfile = CreateFileW(mFile, GENERIC_WRITE, 0, nullptr, @@ -1696,10 +1616,10 @@ PatchFile::Execute() CloseHandle(hfile); } - AutoFile ofile(ensure_open(mFile.get(), shouldTruncate ? NS_T("wb+") : NS_T("rb+"), + AutoFile ofile(ensure_open(mFile, shouldTruncate ? NS_T("wb+") : NS_T("rb+"), ss.st_mode)); #elif defined(XP_MACOSX) - AutoFile ofile(ensure_open(mFile.get(), NS_T("wb+"), ss.st_mode)); + AutoFile ofile(ensure_open(mFile, NS_T("wb+"), ss.st_mode)); // Modified code from FileUtils.cpp fstore_t store = {F_ALLOCATECONTIG, F_PEOFPOSMODE, 0, header.dlen}; // Try to get a continous chunk of disk space @@ -1714,12 +1634,11 @@ PatchFile::Execute() ftruncate(fileno((FILE *)ofile), header.dlen); } #else - AutoFile ofile(ensure_open(mFile.get(), NS_T("wb+"), ss.st_mode)); + AutoFile ofile(ensure_open(mFile, NS_T("wb+"), ss.st_mode)); #endif if (ofile == nullptr) { - LOG(("unable to create new file: " LOG_S ", err: %d", mFileRelPath.get(), - errno)); + LOG(("unable to create new file: " LOG_S ", err: %d", mFile, errno)); return WRITE_ERROR_OPEN_PATCH_FILE; } @@ -1751,21 +1670,23 @@ PatchFile::Execute() void PatchFile::Finish(int status) { - LOG(("FINISH PATCH " LOG_S, mFileRelPath.get())); + LOG(("FINISH PATCH " LOG_S, mFile)); - backup_finish(mFile.get(), mFileRelPath.get(), status); + backup_finish(mFile, status); } class AddIfFile : public AddFile { public: + AddIfFile() : mTestFile(nullptr) { } + virtual int Parse(NS_tchar *line); virtual int Prepare(); virtual int Execute(); virtual void Finish(int status); protected: - mozilla::UniquePtr mTestFile; + const NS_tchar *mTestFile; }; int @@ -1773,16 +1694,14 @@ AddIfFile::Parse(NS_tchar *line) { // format "" "" - mTestFile.reset(get_full_path(get_valid_path(&line))); - if (!mTestFile) { + mTestFile = get_valid_path(&line); + if (!mTestFile) return PARSE_ERROR; - } // consume whitespace between args NS_tchar *q = mstrtok(kQuote, &line); - if (!q) { + if (!q) return PARSE_ERROR; - } return AddFile::Parse(line); } @@ -1791,7 +1710,7 @@ int AddIfFile::Prepare() { // If the test file does not exist, then skip this action. - if (NS_taccess(mTestFile.get(), F_OK)) { + if (NS_taccess(mTestFile, F_OK)) { mTestFile = nullptr; return OK; } @@ -1820,13 +1739,15 @@ AddIfFile::Finish(int status) class AddIfNotFile : public AddFile { public: + AddIfNotFile() : mTestFile(NULL) { } + virtual int Parse(NS_tchar *line); virtual int Prepare(); virtual int Execute(); virtual void Finish(int status); protected: - mozilla::UniquePtr mTestFile; + const NS_tchar *mTestFile; }; int @@ -1834,16 +1755,14 @@ AddIfNotFile::Parse(NS_tchar *line) { // format "" "" - mTestFile.reset(get_full_path(get_valid_path(&line))); - if (!mTestFile) { + mTestFile = get_valid_path(&line); + if (!mTestFile) return PARSE_ERROR; - } // consume whitespace between args NS_tchar *q = mstrtok(kQuote, &line); - if (!q) { + if (!q) return PARSE_ERROR; - } return AddFile::Parse(line); } @@ -1852,7 +1771,7 @@ int AddIfNotFile::Prepare() { // If the test file exists, then skip this action. - if (!NS_taccess(mTestFile.get(), F_OK)) { + if (!NS_taccess(mTestFile, F_OK)) { mTestFile = NULL; return OK; } @@ -1881,13 +1800,15 @@ AddIfNotFile::Finish(int status) class PatchIfFile : public PatchFile { public: + PatchIfFile() : mTestFile(nullptr) { } + virtual int Parse(NS_tchar *line); virtual int Prepare(); // should check for patch file and for checksum here virtual int Execute(); virtual void Finish(int status); private: - mozilla::UniquePtr mTestFile; + const NS_tchar *mTestFile; }; int @@ -1895,16 +1816,14 @@ PatchIfFile::Parse(NS_tchar *line) { // format "" "" "" - mTestFile.reset(get_full_path(get_valid_path(&line))); - if (!mTestFile) { + mTestFile = get_valid_path(&line); + if (!mTestFile) return PARSE_ERROR; - } // consume whitespace between args NS_tchar *q = mstrtok(kQuote, &line); - if (!q) { + if (!q) return PARSE_ERROR; - } return PatchFile::Parse(line); } @@ -1913,7 +1832,7 @@ int PatchIfFile::Prepare() { // If the test file does not exist, then skip this action. - if (NS_taccess(mTestFile.get(), F_OK)) { + if (NS_taccess(mTestFile, F_OK)) { mTestFile = nullptr; return OK; } @@ -2596,7 +2515,8 @@ UpdateThreadFunc(void *param) if (rv && (sReplaceRequest || sStagedUpdate)) { #ifdef XP_WIN // On Windows, the current working directory of the process should be changed - // so that it's not locked. + // so that it's not locked. The working directory for staging an update was + // already changed earlier. if (sStagedUpdate) { NS_tchar sysDir[MAX_PATH + 1] = { L'\0' }; if (GetSystemDirectoryW(sysDir, MAX_PATH + 1)) { @@ -2931,30 +2851,21 @@ int NS_main(int argc, NS_tchar **argv) LOG(("WORKING DIRECTORY " LOG_S, gWorkingDirPath)); #if defined(XP_WIN) - if (_wcsnicmp(gWorkingDirPath, gInstallDirPath, MAX_PATH) != 0) { - if (!sStagedUpdate && !sReplaceRequest) { - WriteStatusFile(INVALID_APPLYTO_DIR_ERROR); - LOG(("Installation directory and working directory must be the same " - "for non-staged updates. Exiting.")); - LogFinish(); - return 1; - } - - NS_tchar workingDirParent[MAX_PATH]; - NS_tsnprintf(workingDirParent, - sizeof(workingDirParent) / sizeof(workingDirParent[0]), + if (sReplaceRequest || sStagedUpdate) { + NS_tchar stagedParent[MAX_PATH]; + NS_tsnprintf(stagedParent, sizeof(stagedParent)/sizeof(stagedParent[0]), NS_T("%s"), gWorkingDirPath); - if (!PathRemoveFileSpecW(workingDirParent)) { + if (!PathRemoveFileSpecW(stagedParent)) { WriteStatusFile(REMOVE_FILE_SPEC_ERROR); LOG(("Error calling PathRemoveFileSpecW: %d", GetLastError())); LogFinish(); return 1; } - if (_wcsnicmp(workingDirParent, gInstallDirPath, MAX_PATH) != 0) { - WriteStatusFile(INVALID_APPLYTO_DIR_STAGED_ERROR); - LOG(("The apply-to directory must be the same as or " - "a child of the installation directory! Exiting.")); + if (_wcsnicmp(stagedParent, gInstallDirPath, MAX_PATH) != 0) { + WriteStatusFile(INVALID_STAGED_PARENT_ERROR); + LOG(("Stage and Replace requests require that the working directory " \ + "is a sub-directory of the installation directory! Exiting")); LogFinish(); return 1; } @@ -3012,6 +2923,15 @@ int NS_main(int argc, NS_tchar **argv) #endif #ifdef XP_WIN + if (sReplaceRequest) { + // On Windows, the current working directory of the process should be changed + // so that it's not locked. + NS_tchar sysDir[MAX_PATH + 1] = { L'\0' }; + if (GetSystemDirectoryW(sysDir, MAX_PATH + 1)) { + NS_tchdir(sysDir); + } + } + #ifdef MOZ_MAINTENANCE_SERVICE sUsingService = EnvHasValue("MOZ_USING_SERVICE"); putenv(const_cast("MOZ_USING_SERVICE=")); @@ -3342,16 +3262,32 @@ int NS_main(int argc, NS_tchar **argv) ensure_remove_recursive(gWorkingDirPath); } if (!sReplaceRequest) { - // Try to create the destination directory if it doesn't exist - int rv = NS_tmkdir(gWorkingDirPath, 0755); - if (rv != OK && errno != EEXIST) { + // Change current directory to the directory where we need to apply the update. + if (NS_tchdir(gWorkingDirPath) != 0) { + // Try to create the destination directory if it doesn't exist + int rv = NS_tmkdir(gWorkingDirPath, 0755); + if (rv == OK && errno != EEXIST) { + // Try changing the current directory again + if (NS_tchdir(gWorkingDirPath) != 0) { + // OK, time to give up! #ifdef XP_MACOSX - if (isElevated) { - freeArguments(argc, argv); - CleanupElevatedMacUpdate(true); - } + if (isElevated) { + freeArguments(argc, argv); + CleanupElevatedMacUpdate(true); + } #endif - return 1; + return 1; + } + } else { + // Failed to create the directory, bail out +#ifdef XP_MACOSX + if (isElevated) { + freeArguments(argc, argv); + CleanupElevatedMacUpdate(true); + } +#endif + return 1; + } } } @@ -3382,7 +3318,7 @@ int NS_main(int argc, NS_tchar **argv) NS_tchar applyDirLongPath[MAXPATHLEN]; if (!GetLongPathNameW(gWorkingDirPath, applyDirLongPath, - sizeof(applyDirLongPath) / sizeof(applyDirLongPath[0]))) { + sizeof(applyDirLongPath)/sizeof(applyDirLongPath[0]))) { LOG(("NS_main: unable to find apply to dir: " LOG_S, gWorkingDirPath)); LogFinish(); WriteStatusFile(WRITE_ERROR_APPLY_DIR_PATH); @@ -3552,23 +3488,13 @@ int NS_main(int argc, NS_tchar **argv) } } - // DELETE_DIR is not required when performing a staged update or replace - // request; it can be used during a replace request but then it doesn't - // use gDeleteDirPath. + // DELETE_DIR is not required when staging an update. if (!sStagedUpdate && !sReplaceRequest) { // The directory to move files that are in use to on Windows. This directory - // will be deleted after the update is finished, on OS reboot using - // MoveFileEx if it contains files that are in use, or by the post update - // process after the update finishes. On Windows when performing a normal - // update (e.g. the update is not a staged update and is not a replace - // request) gWorkingDirPath is the same as gInstallDirPath and - // gWorkingDirPath is used because it is the destination directory. - NS_tsnprintf(gDeleteDirPath, - sizeof(gDeleteDirPath) / sizeof(gDeleteDirPath[0]), - NS_T("%s/%s"), gWorkingDirPath, DELETE_DIR); - - if (NS_taccess(gDeleteDirPath, F_OK)) { - NS_tmkdir(gDeleteDirPath, 0755); + // will be deleted after the update is finished or on OS reboot using + // MoveFileEx if it contains files that are in use. + if (NS_taccess(DELETE_DIR, F_OK)) { + NS_tmkdir(DELETE_DIR, 0755); } } #endif /* XP_WIN */ @@ -3598,7 +3524,7 @@ int NS_main(int argc, NS_tchar **argv) NS_tremove(gCallbackBackupPath); } - if (!sStagedUpdate && !sReplaceRequest && _wrmdir(gDeleteDirPath)) { + if (!sStagedUpdate && !sReplaceRequest && _wrmdir(DELETE_DIR)) { LOG(("NS_main: unable to remove directory: " LOG_S ", err: %d", DELETE_DIR, errno)); // The directory probably couldn't be removed due to it containing files @@ -3610,7 +3536,7 @@ int NS_main(int argc, NS_tchar **argv) // access to the HKEY_LOCAL_MACHINE registry key but this is ok since the // installer / uninstaller will delete the directory along with its contents // after an update is applied, on reinstall, and on uninstall. - if (MoveFileEx(gDeleteDirPath, nullptr, MOVEFILE_DELAY_UNTIL_REBOOT)) { + if (MoveFileEx(DELETE_DIR, nullptr, MOVEFILE_DELAY_UNTIL_REBOOT)) { LOG(("NS_main: directory will be removed on OS reboot: " LOG_S, DELETE_DIR)); } else { @@ -3817,9 +3743,9 @@ int add_dir_entries(const NS_tchar *dirpath, ActionList *list) NS_tsnprintf(searchspec, sizeof(searchspec)/sizeof(searchspec[0]), NS_T("%s*"), dirpath); - mozilla::UniquePtr pszSpec(get_full_path(searchspec)); + const NS_tchar *pszSpec = get_full_path(searchspec); - hFindFile = FindFirstFileW(pszSpec.get(), &finddata); + hFindFile = FindFirstFileW(pszSpec, &finddata); if (hFindFile != INVALID_HANDLE_VALUE) { do { // Don't process the current or parent directory. @@ -3880,17 +3806,24 @@ int add_dir_entries(const NS_tchar *dirpath, ActionList *list) int add_dir_entries(const NS_tchar *dirpath, ActionList *list) { int rv = OK; + NS_tchar searchpath[MAXPATHLEN]; NS_tchar foundpath[MAXPATHLEN]; struct { dirent dent_buffer; char chars[MAXNAMLEN]; } ent_buf; struct dirent* ent; - mozilla::UniquePtr searchpath(get_full_path(dirpath)); - DIR* dir = opendir(searchpath.get()); + + NS_tsnprintf(searchpath, sizeof(searchpath)/sizeof(searchpath[0]), NS_T("%s"), + dirpath); + // Remove the trailing slash so the paths don't contain double slashes. The + // existence of the slash has already been checked in DoUpdate. + searchpath[NS_tstrlen(searchpath) - 1] = NS_T('\0'); + + DIR* dir = opendir(searchpath); if (!dir) { - LOG(("add_dir_entries error on opendir: " LOG_S ", err: %d", searchpath.get(), + LOG(("add_dir_entries error on opendir: " LOG_S ", err: %d", searchpath, errno)); return UNEXPECTED_FILE_OPERATION_ERROR; } @@ -3901,7 +3834,7 @@ int add_dir_entries(const NS_tchar *dirpath, ActionList *list) continue; NS_tsnprintf(foundpath, sizeof(foundpath)/sizeof(foundpath[0]), - NS_T("%s%s"), searchpath.get(), ent->d_name); + NS_T("%s%s"), dirpath, ent->d_name); struct stat64 st_buf; int test = stat64(foundpath, &st_buf); if (test) { @@ -3920,7 +3853,7 @@ int add_dir_entries(const NS_tchar *dirpath, ActionList *list) } } else { // Add the file to be removed to the ActionList. - NS_tchar *quotedpath = get_quoted_path(get_relative_path(foundpath)); + NS_tchar *quotedpath = get_quoted_path(foundpath); if (!quotedpath) { closedir(dir); return PARSE_ERROR; @@ -3941,7 +3874,7 @@ int add_dir_entries(const NS_tchar *dirpath, ActionList *list) closedir(dir); // Add the directory to be removed to the ActionList. - NS_tchar *quotedpath = get_quoted_path(get_relative_path(dirpath)); + NS_tchar *quotedpath = get_quoted_path(dirpath); if (!quotedpath) return PARSE_ERROR; @@ -3965,12 +3898,14 @@ int add_dir_entries(const NS_tchar *dirpath, ActionList *list) int rv = OK; FTS *ftsdir; FTSENT *ftsdirEntry; - mozilla::UniquePtr searchpath(get_full_path(dirpath)); + NS_tchar searchpath[MAXPATHLEN]; + NS_tsnprintf(searchpath, sizeof(searchpath)/sizeof(searchpath[0]), NS_T("%s"), + dirpath); // Remove the trailing slash so the paths don't contain double slashes. The // existence of the slash has already been checked in DoUpdate. - searchpath[NS_tstrlen(searchpath.get()) - 1] = NS_T('\0'); - char* const pathargv[] = {searchpath.get(), nullptr}; + searchpath[NS_tstrlen(searchpath) - 1] = NS_T('\0'); + char* const pathargv[] = {searchpath, nullptr}; // FTS_NOCHDIR is used so relative paths from the destination directory are // returned. @@ -4000,7 +3935,7 @@ int add_dir_entries(const NS_tchar *dirpath, ActionList *list) // Add the file to be removed to the ActionList. NS_tsnprintf(foundpath, sizeof(foundpath)/sizeof(foundpath[0]), NS_T("%s"), ftsdirEntry->fts_accpath); - quotedpath = get_quoted_path(get_relative_path(foundpath)); + quotedpath = get_quoted_path(foundpath); if (!quotedpath) { rv = UPDATER_QUOTED_PATH_MEM_ERROR; break; @@ -4017,7 +3952,7 @@ int add_dir_entries(const NS_tchar *dirpath, ActionList *list) // Add the directory to be removed to the ActionList. NS_tsnprintf(foundpath, sizeof(foundpath)/sizeof(foundpath[0]), NS_T("%s/"), ftsdirEntry->fts_accpath); - quotedpath = get_quoted_path(get_relative_path(foundpath)); + quotedpath = get_quoted_path(foundpath); if (!quotedpath) { rv = UPDATER_QUOTED_PATH_MEM_ERROR; break; @@ -4135,14 +4070,10 @@ int AddPreCompleteActions(ActionList *list) } #ifdef XP_MACOSX - mozilla::UniquePtr manifestPath(get_full_path( - NS_T("Contents/Resources/precomplete"))); + NS_tchar *rb = GetManifestContents(NS_T("Contents/Resources/precomplete")); #else - mozilla::UniquePtr manifestPath(get_full_path( - NS_T("precomplete"))); + NS_tchar *rb = GetManifestContents(NS_T("precomplete")); #endif - - NS_tchar *rb = GetManifestContents(manifestPath.get()); if (rb == nullptr) { LOG(("AddPreCompleteActions: error getting contents of precomplete " \ "manifest")); From 6e5d1c263b58f876e91c0609f1041176b78445a2 Mon Sep 17 00:00:00 2001 From: Stephen A Pohl Date: Thu, 25 Aug 2016 16:14:11 -0400 Subject: [PATCH 023/105] Bug 1286490: Handle IPC timeout exceptions during elevated updates on OSX. r=mstange --- .../mozapps/update/updater/launchchild_osx.mm | 21 ++++++++++++------- toolkit/xre/MacLaunchHelper.mm | 16 +++++++------- 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/toolkit/mozapps/update/updater/launchchild_osx.mm b/toolkit/mozapps/update/updater/launchchild_osx.mm index f75c6e2dea4a..b86dd517a71b 100644 --- a/toolkit/mozapps/update/updater/launchchild_osx.mm +++ b/toolkit/mozapps/update/updater/launchchild_osx.mm @@ -108,12 +108,12 @@ id ConnectToUpdateServer() MacAutoreleasePool pool; id updateServer = nil; - @try { - BOOL isConnected = NO; - int currTry = 0; - const int numRetries = 10; // Number of IPC connection retries before - // giving up. - while (!isConnected && currTry < numRetries) { + BOOL isConnected = NO; + int currTry = 0; + const int numRetries = 10; // Number of IPC connection retries before + // giving up. + while (!isConnected && currTry < numRetries) { + @try { updateServer = (id)[NSConnection rootProxyForConnectionWithRegisteredName: @"org.mozilla.updater.server" @@ -129,9 +129,14 @@ id ConnectToUpdateServer() } else { isConnected = YES; } + } @catch (NSException* e) { + NSLog(@"Encountered exception, retrying: %@: %@", e.name, e.reason); + sleep(1); // Wait 1 second. + currTry++; } - } @catch (NSException* e) { - NSLog(@"%@: %@", e.name, e.reason); + } + if (!isConnected) { + NSLog(@"Failed to connect to update server after several retries."); return nil; } return updateServer; diff --git a/toolkit/xre/MacLaunchHelper.mm b/toolkit/xre/MacLaunchHelper.mm index ce3219f9f387..91477e8ecf59 100644 --- a/toolkit/xre/MacLaunchHelper.mm +++ b/toolkit/xre/MacLaunchHelper.mm @@ -149,11 +149,11 @@ void AbortElevatedUpdate() mozilla::MacAutoreleasePool pool; id updateServer = nil; - @try { - int currTry = 0; - const int numRetries = 10; // Number of IPC connection retries before - // giving up. - while (currTry < numRetries) { + int currTry = 0; + const int numRetries = 10; // Number of IPC connection retries before + // giving up. + while (currTry < numRetries) { + @try { updateServer = (id)[NSConnection rootProxyForConnectionWithRegisteredName: @"org.mozilla.updater.server" @@ -167,9 +167,11 @@ void AbortElevatedUpdate() NSLog(@"Server doesn't exist or doesn't provide correct selectors."); sleep(1); // Wait 1 second. currTry++; + } @catch (NSException* e) { + NSLog(@"Encountered exception, retrying: %@: %@", e.name, e.reason); + sleep(1); // Wait 1 second. + currTry++; } - } @catch (NSException* e) { - NSLog(@"%@: %@", e.name, e.reason); } NSLog(@"Unable to clean up updater."); } From 1465871242f26ee528468e16fdb7d4e0c3264caf Mon Sep 17 00:00:00 2001 From: Wes Kocher Date: Thu, 25 Aug 2016 13:19:48 -0700 Subject: [PATCH 024/105] Backed out 1 changesets (bug 1295034) for spidermonkey failures a=backout Backed out changeset 024e7dc7a219 (bug 1295034) --- js/src/builtin/Sorting.js | 11 +++------- .../tests/ecma_6/TypedArray/sort_jit_array.js | 22 ------------------- js/src/vm/SelfHosting.cpp | 3 +-- js/src/vm/TypedArrayObject.cpp | 4 ++-- js/src/vm/TypedArrayObject.h | 2 -- 5 files changed, 6 insertions(+), 36 deletions(-) delete mode 100644 js/src/tests/ecma_6/TypedArray/sort_jit_array.js diff --git a/js/src/builtin/Sorting.js b/js/src/builtin/Sorting.js index 660ab079fd0e..0451ceb7a2fb 100644 --- a/js/src/builtin/Sorting.js +++ b/js/src/builtin/Sorting.js @@ -101,6 +101,9 @@ function RadixSort(array, len, buffer, nbytes, signed, floating, comparefn) { return array; } + // Verify that the buffer is non-null + assert(buffer !== null, "Attached data buffer should be reified when array length is >= 128."); + let aux = new List(); for (let i = 0; i < len; i++) { aux[i] = 0; @@ -111,14 +114,6 @@ function RadixSort(array, len, buffer, nbytes, signed, floating, comparefn) { // Preprocess if (floating) { - // This happens if the array object is constructed under JIT - if (buffer === null) { - buffer = callFunction(std_TypedArray_buffer, array); - } - - // Verify that the buffer is non-null - assert(buffer !== null, "Attached data buffer should be reified when array length is >= 128."); - view = new Int32Array(buffer); // Flip sign bit for positive numbers; flip all bits for negative diff --git a/js/src/tests/ecma_6/TypedArray/sort_jit_array.js b/js/src/tests/ecma_6/TypedArray/sort_jit_array.js deleted file mode 100644 index 6d17103c55c7..000000000000 --- a/js/src/tests/ecma_6/TypedArray/sort_jit_array.js +++ /dev/null @@ -1,22 +0,0 @@ -const constructors = [ - Int8Array, - Uint8Array, - Uint8ClampedArray, - Int16Array, - Uint16Array, - Int32Array, - Uint32Array, - Float32Array, - Float64Array ]; - -// Ensure that when creating TypedArrays under JIT -// the sort() method works as expected (bug 1295034). -for (var ctor of constructors) { - for (var _ of Array(1024)) { - var testArray = new ctor(1024); - testArray.sort(); - } -} - -if (typeof reportCompare === "function") - reportCompare(true, true); \ No newline at end of file diff --git a/js/src/vm/SelfHosting.cpp b/js/src/vm/SelfHosting.cpp index 0601a00d3aab..ab7f7f9e1d4f 100644 --- a/js/src/vm/SelfHosting.cpp +++ b/js/src/vm/SelfHosting.cpp @@ -2338,8 +2338,7 @@ static const JSFunctionSpec intrinsic_functions[] = { JS_FN("std_String_normalize", str_normalize, 0,0), #endif JS_FN("std_String_concat", str_concat, 1,0), - - JS_FN("std_TypedArray_buffer", js::TypedArray_bufferGetter, 1,0), + JS_FN("std_WeakMap_has", WeakMap_has, 1,0), JS_FN("std_WeakMap_get", WeakMap_get, 2,0), diff --git a/js/src/vm/TypedArrayObject.cpp b/js/src/vm/TypedArrayObject.cpp index 9db51cc4f4e1..20e75f3c34f8 100644 --- a/js/src/vm/TypedArrayObject.cpp +++ b/js/src/vm/TypedArrayObject.cpp @@ -1326,8 +1326,8 @@ BufferGetterImpl(JSContext* cx, const CallArgs& args) return true; } -/*static*/ bool -js::TypedArray_bufferGetter(JSContext* cx, unsigned argc, Value* vp) +static bool +TypedArray_bufferGetter(JSContext* cx, unsigned argc, Value* vp) { CallArgs args = CallArgsFromVp(argc, vp); return CallNonGenericMethod(cx, args); diff --git a/js/src/vm/TypedArrayObject.h b/js/src/vm/TypedArrayObject.h index 965ca282510b..4019c482b1d0 100644 --- a/js/src/vm/TypedArrayObject.h +++ b/js/src/vm/TypedArrayObject.h @@ -294,8 +294,6 @@ class TypedArrayObject : public NativeObject static bool set(JSContext* cx, unsigned argc, Value* vp); }; -MOZ_MUST_USE bool TypedArray_bufferGetter(JSContext* cx, unsigned argc, Value* vp); - extern TypedArrayObject* TypedArrayCreateWithTemplate(JSContext* cx, HandleObject templateObj, int32_t len); From 5dc1176290189d62c4f092a4c2e9d2999057c2dc Mon Sep 17 00:00:00 2001 From: Robert Strong Date: Thu, 25 Aug 2016 13:32:07 -0700 Subject: [PATCH 025/105] bug 1296207 Firefox code - Remove unused app update billboard capability. r=jaws --- .../base/content/aboutDialog-appUpdater.js | 20 ------------------- browser/base/content/aboutDialog.xul | 7 ------- .../en-US/chrome/browser/aboutDialog.dtd | 6 ++---- 3 files changed, 2 insertions(+), 31 deletions(-) diff --git a/browser/base/content/aboutDialog-appUpdater.js b/browser/base/content/aboutDialog-appUpdater.js index 21621201ac40..76ee07169e5d 100644 --- a/browser/base/content/aboutDialog-appUpdater.js +++ b/browser/base/content/aboutDialog-appUpdater.js @@ -240,21 +240,6 @@ appUpdater.prototype = Components.interfaces.nsIAppStartup.eRestart); }, - /** - * Handles oncommand for the "Apply Update…" button - * which is presented if we need to show the billboard. - */ - buttonApplyBillboard: function() { - const URI_UPDATE_PROMPT_DIALOG = "chrome://mozapps/content/update/updates.xul"; - var ary = null; - ary = Components.classes["@mozilla.org/supports-array;1"]. - createInstance(Components.interfaces.nsISupportsArray); - ary.AppendElement(this.update); - var openFeatures = "chrome,centerscreen,dialog=no,resizable=no,titlebar,toolbar=no"; - Services.ww.openWindow(null, URI_UPDATE_PROMPT_DIALOG, "", openFeatures, ary); - window.close(); // close the "About" window; updates.xul takes over. - }, - /** * Implements nsIUpdateCheckListener. The methods implemented by * nsIUpdateCheckListener are in a different scope from nsIIncrementalDownload @@ -287,11 +272,6 @@ appUpdater.prototype = return; } - if (gAppUpdater.update.billboardURL) { - gAppUpdater.selectPanel("applyBillboard"); - return; - } - if (gAppUpdater.updateAuto) // automatically download and install gAppUpdater.startDownload(); else // ask diff --git a/browser/base/content/aboutDialog.xul b/browser/base/content/aboutDialog.xul index 94ed677f9a58..cbb07a5e11af 100644 --- a/browser/base/content/aboutDialog.xul +++ b/browser/base/content/aboutDialog.xul @@ -78,13 +78,6 @@ oncommand="gAppUpdater.buttonRestartAfterDownload();"/> - -