Microsoft Media Foundation Camera Sample for Windows RT added.pull/1040/head
@ -0,0 +1,114 @@ |
||||
//*********************************************************
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
|
||||
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
|
||||
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
|
||||
//
|
||||
//*********************************************************
|
||||
|
||||
//
|
||||
// App.xaml.cpp
|
||||
// Implementation of the App.xaml class.
|
||||
//
|
||||
|
||||
#include "pch.h" |
||||
#include "MainPage.xaml.h" |
||||
#include "Common\SuspensionManager.h" |
||||
|
||||
using namespace SDKSample; |
||||
using namespace SDKSample::Common; |
||||
|
||||
using namespace Concurrency; |
||||
using namespace Platform; |
||||
using namespace Windows::ApplicationModel; |
||||
using namespace Windows::ApplicationModel::Activation; |
||||
using namespace Windows::Foundation; |
||||
using namespace Windows::Foundation::Collections; |
||||
using namespace Windows::UI::Core; |
||||
using namespace Windows::UI::Xaml; |
||||
using namespace Windows::UI::Xaml::Controls; |
||||
using namespace Windows::UI::Xaml::Controls::Primitives; |
||||
using namespace Windows::UI::Xaml::Data; |
||||
using namespace Windows::UI::Xaml::Input; |
||||
using namespace Windows::UI::Xaml::Interop; |
||||
using namespace Windows::UI::Xaml::Media; |
||||
using namespace Windows::UI::Xaml::Navigation; |
||||
|
||||
/// <summary>
|
||||
/// Initializes the singleton application object. This is the first line of authored code
|
||||
/// executed, and as such is the logical equivalent of main() or WinMain().
|
||||
/// </summary>
|
||||
App::App() |
||||
{ |
||||
InitializeComponent(); |
||||
this->Suspending += ref new SuspendingEventHandler(this, &SDKSample::App::OnSuspending); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Invoked when the application is launched normally by the end user. Other entry points will
|
||||
/// be used when the application is launched to open a specific file, to display search results,
|
||||
/// and so forth.
|
||||
/// </summary>
|
||||
/// <param name="pArgs">Details about the launch request and process.</param>
|
||||
void App::OnLaunched(LaunchActivatedEventArgs^ pArgs) |
||||
{ |
||||
this->LaunchArgs = pArgs; |
||||
|
||||
// Do not repeat app initialization when already running, just ensure that
|
||||
// the window is active
|
||||
if (pArgs->PreviousExecutionState == ApplicationExecutionState::Running) |
||||
{ |
||||
Window::Current->Activate(); |
||||
return; |
||||
} |
||||
|
||||
// Create a Frame to act as the navigation context and associate it with
|
||||
// a SuspensionManager key
|
||||
auto rootFrame = ref new Frame(); |
||||
SuspensionManager::RegisterFrame(rootFrame, "AppFrame"); |
||||
|
||||
auto prerequisite = task<void>([](){}); |
||||
if (pArgs->PreviousExecutionState == ApplicationExecutionState::Terminated) |
||||
{ |
||||
// Restore the saved session state only when appropriate, scheduling the
|
||||
// final launch steps after the restore is complete
|
||||
prerequisite = SuspensionManager::RestoreAsync(); |
||||
} |
||||
prerequisite.then([=]() |
||||
{ |
||||
// When the navigation stack isn't restored navigate to the first page,
|
||||
// configuring the new page by passing required information as a navigation
|
||||
// parameter
|
||||
if (rootFrame->Content == nullptr) |
||||
{ |
||||
if (!rootFrame->Navigate(TypeName(MainPage::typeid))) |
||||
{ |
||||
throw ref new FailureException("Failed to create initial page"); |
||||
} |
||||
} |
||||
|
||||
// Place the frame in the current Window and ensure that it is active
|
||||
Window::Current->Content = rootFrame; |
||||
Window::Current->Activate(); |
||||
}, task_continuation_context::use_current()); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Invoked when application execution is being suspended. Application state is saved
|
||||
/// without knowing whether the application will be terminated or resumed with the contents
|
||||
/// of memory still intact.
|
||||
/// </summary>
|
||||
/// <param name="sender">The source of the suspend request.</param>
|
||||
/// <param name="e">Details about the suspend request.</param>
|
||||
void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e) |
||||
{ |
||||
(void) sender; // Unused parameter
|
||||
|
||||
auto deferral = e->SuspendingOperation->GetDeferral(); |
||||
SuspensionManager::SaveAsync().then([=]() |
||||
{ |
||||
deferral->Complete(); |
||||
}); |
||||
} |
@ -0,0 +1,35 @@ |
||||
//*********************************************************
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
|
||||
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
|
||||
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
|
||||
//
|
||||
//*********************************************************
|
||||
|
||||
//
|
||||
// App.xaml.h
|
||||
// Declaration of the App.xaml class.
|
||||
//
|
||||
|
||||
#pragma once |
||||
|
||||
#include "pch.h" |
||||
#include "App.g.h" |
||||
#include "MainPage.g.h" |
||||
|
||||
namespace SDKSample |
||||
{ |
||||
ref class App |
||||
{ |
||||
internal: |
||||
App(); |
||||
virtual void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ pArgs); |
||||
Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs; |
||||
protected: |
||||
virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override; |
||||
private: |
||||
Windows::UI::Xaml::Controls::Frame^ rootFrame; |
||||
}; |
||||
} |
@ -0,0 +1,24 @@ |
||||
//*********************************************************
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
|
||||
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
|
||||
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
|
||||
//
|
||||
//*********************************************************
|
||||
|
||||
#include "pch.h" |
||||
#include "MainPage.xaml.h" |
||||
#include "Constants.h" |
||||
|
||||
using namespace SDKSample; |
||||
|
||||
Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario> |
||||
{ |
||||
// The format here is the following:
|
||||
// { "Description for the sample", "Fully quaified name for the class that implements the scenario" }
|
||||
{ "Video preview, record and take pictures", "SDKSample.MediaCapture.BasicCapture" }, |
||||
{ "Enumerate cameras and add a video effect", "SDKSample.MediaCapture.AdvancedCapture" }, |
||||
{ "Audio Capture", "SDKSample.MediaCapture.AudioCapture" } |
||||
}; |
@ -0,0 +1,45 @@ |
||||
//*********************************************************
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
|
||||
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
|
||||
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
|
||||
//
|
||||
//*********************************************************
|
||||
|
||||
#pragma once |
||||
|
||||
#include <collection.h> |
||||
namespace SDKSample |
||||
{ |
||||
public value struct Scenario |
||||
{ |
||||
Platform::String^ Title; |
||||
Platform::String^ ClassName; |
||||
}; |
||||
|
||||
partial ref class MainPage |
||||
{ |
||||
public: |
||||
static property Platform::String^ FEATURE_NAME |
||||
{ |
||||
Platform::String^ get() |
||||
{ |
||||
return ref new Platform::String(L"MediaCapture CPP sample"); |
||||
} |
||||
} |
||||
|
||||
static property Platform::Array<Scenario>^ scenarios |
||||
{ |
||||
Platform::Array<Scenario>^ get() |
||||
{ |
||||
return scenariosInner; |
||||
} |
||||
} |
||||
private: |
||||
static Platform::Array<Scenario>^ scenariosInner; |
||||
}; |
||||
|
||||
|
||||
} |
@ -0,0 +1,315 @@ |
||||
//*********************************************************
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
|
||||
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
|
||||
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
|
||||
//
|
||||
//*********************************************************
|
||||
|
||||
//
|
||||
// MainPage.xaml.cpp
|
||||
// Implementation of the MainPage.xaml class.
|
||||
//
|
||||
|
||||
#include "pch.h" |
||||
#include "MainPage.xaml.h" |
||||
#include "App.xaml.h" |
||||
|
||||
#include <collection.h> |
||||
|
||||
using namespace Windows::UI::Xaml; |
||||
using namespace Windows::UI::Xaml::Controls; |
||||
using namespace Windows::Foundation; |
||||
using namespace Windows::Foundation::Collections; |
||||
using namespace Platform; |
||||
using namespace SDKSample; |
||||
using namespace Windows::UI::Xaml::Navigation; |
||||
using namespace Windows::UI::Xaml::Interop; |
||||
using namespace Windows::Graphics::Display; |
||||
using namespace Windows::UI::ViewManagement; |
||||
|
||||
MainPage^ MainPage::Current = nullptr; |
||||
|
||||
MainPage::MainPage() |
||||
{ |
||||
InitializeComponent(); |
||||
|
||||
// This frame is hidden, meaning it is never shown. It is simply used to load
|
||||
// each scenario page and then pluck out the input and output sections and
|
||||
// place them into the UserControls on the main page.
|
||||
HiddenFrame = ref new Windows::UI::Xaml::Controls::Frame(); |
||||
HiddenFrame->Visibility = Windows::UI::Xaml::Visibility::Collapsed; |
||||
ContentRoot->Children->Append(HiddenFrame); |
||||
|
||||
FeatureName->Text = FEATURE_NAME; |
||||
|
||||
this->SizeChanged += ref new SizeChangedEventHandler(this, &MainPage::MainPage_SizeChanged); |
||||
Scenarios->SelectionChanged += ref new SelectionChangedEventHandler(this, &MainPage::Scenarios_SelectionChanged); |
||||
|
||||
MainPage::Current = this; |
||||
autoSizeInputSectionWhenSnapped = true; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// We need to handle SizeChanged so that we can make the sample layout property
|
||||
/// in the various layouts.
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
void MainPage::MainPage_SizeChanged(Object^ sender, SizeChangedEventArgs^ e) |
||||
{ |
||||
InvalidateSize(); |
||||
MainPageSizeChangedEventArgs^ args = ref new MainPageSizeChangedEventArgs(); |
||||
args->ViewState = ApplicationView::Value; |
||||
MainPageResized(this, args); |
||||
|
||||
} |
||||
|
||||
void MainPage::InvalidateSize() |
||||
{ |
||||
// Get the window width
|
||||
double windowWidth = this->ActualWidth; |
||||
|
||||
if (windowWidth != 0.0) |
||||
{ |
||||
// Get the width of the ListBox.
|
||||
double listBoxWidth = Scenarios->ActualWidth; |
||||
|
||||
// Is the ListBox using any margins that we need to consider?
|
||||
double listBoxMarginLeft = Scenarios->Margin.Left; |
||||
double listBoxMarginRight = Scenarios->Margin.Right; |
||||
|
||||
// Figure out how much room is left after considering the list box width
|
||||
double availableWidth = windowWidth - listBoxWidth; |
||||
|
||||
// Is the top most child using margins?
|
||||
double layoutRootMarginLeft = ContentRoot->Margin.Left; |
||||
double layoutRootMarginRight = ContentRoot->Margin.Right; |
||||
|
||||
// We have different widths to use depending on the view state
|
||||
if (ApplicationView::Value != ApplicationViewState::Snapped) |
||||
{ |
||||
// Make us as big as the the left over space, factoring in the ListBox width, the ListBox margins.
|
||||
// and the LayoutRoot's margins
|
||||
InputSection->Width = ((availableWidth) -
|
||||
(layoutRootMarginLeft + layoutRootMarginRight + listBoxMarginLeft + listBoxMarginRight)); |
||||
} |
||||
else |
||||
{ |
||||
// Make us as big as the left over space, factoring in just the LayoutRoot's margins.
|
||||
if (autoSizeInputSectionWhenSnapped) |
||||
{ |
||||
InputSection->Width = (windowWidth - (layoutRootMarginLeft + layoutRootMarginRight)); |
||||
} |
||||
} |
||||
} |
||||
InvalidateViewState(); |
||||
} |
||||
|
||||
void MainPage::InvalidateViewState() |
||||
{ |
||||
// Are we going to snapped mode?
|
||||
if (ApplicationView::Value == ApplicationViewState::Snapped) |
||||
{ |
||||
Grid::SetRow(DescriptionText, 3); |
||||
Grid::SetColumn(DescriptionText, 0); |
||||
|
||||
Grid::SetRow(InputSection, 4); |
||||
Grid::SetColumn(InputSection, 0); |
||||
|
||||
Grid::SetRow(FooterPanel, 2); |
||||
Grid::SetColumn(FooterPanel, 0); |
||||
} |
||||
else |
||||
{ |
||||
Grid::SetRow(DescriptionText, 1); |
||||
Grid::SetColumn(DescriptionText, 1); |
||||
|
||||
Grid::SetRow(InputSection, 2); |
||||
Grid::SetColumn(InputSection, 1); |
||||
|
||||
Grid::SetRow(FooterPanel, 1); |
||||
Grid::SetColumn(FooterPanel, 1); |
||||
} |
||||
|
||||
// Since we don't load the scenario page in the traditional manner (we just pluck out the
|
||||
// input and output sections from the page) we need to ensure that any VSM code used
|
||||
// by the scenario's input and output sections is fired.
|
||||
VisualStateManager::GoToState(InputSection, "Input" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false); |
||||
VisualStateManager::GoToState(OutputSection, "Output" + LayoutAwarePage::DetermineVisualState(ApplicationView::Value), false); |
||||
} |
||||
|
||||
void MainPage::PopulateScenarios() |
||||
{ |
||||
ScenarioList = ref new Platform::Collections::Vector<Object^>(); |
||||
|
||||
// Populate the ListBox with the list of scenarios as defined in Constants.cpp.
|
||||
for (unsigned int i = 0; i < scenarios->Length; ++i) |
||||
{ |
||||
Scenario s = scenarios[i]; |
||||
ListBoxItem^ item = ref new ListBoxItem(); |
||||
item->Name = s.ClassName; |
||||
item->Content = (i + 1).ToString() + ") " + s.Title; |
||||
ScenarioList->Append(item); |
||||
} |
||||
|
||||
// Bind the ListBox to the scenario list.
|
||||
Scenarios->ItemsSource = ScenarioList; |
||||
Scenarios->ScrollIntoView(Scenarios->SelectedItem); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// This method is responsible for loading the individual input and output sections for each scenario. This
|
||||
/// is based on navigating a hidden Frame to the ScenarioX.xaml page and then extracting out the input
|
||||
/// and output sections into the respective UserControl on the main page.
|
||||
/// </summary>
|
||||
/// <param name="scenarioName"></param>
|
||||
void MainPage::LoadScenario(String^ scenarioName) |
||||
{ |
||||
autoSizeInputSectionWhenSnapped = true; |
||||
|
||||
// Load the ScenarioX.xaml file into the Frame.
|
||||
TypeName scenarioType = {scenarioName, TypeKind::Custom}; |
||||
HiddenFrame->Navigate(scenarioType, this); |
||||
|
||||
// Get the top element, the Page, so we can look up the elements
|
||||
// that represent the input and output sections of the ScenarioX file.
|
||||
Page^ hiddenPage = safe_cast<Page^>(HiddenFrame->Content); |
||||
|
||||
// Get each element.
|
||||
UIElement^ input = safe_cast<UIElement^>(hiddenPage->FindName("Input")); |
||||
UIElement^ output = safe_cast<UIElement^>(hiddenPage->FindName("Output")); |
||||
|
||||
if (input == nullptr) |
||||
{ |
||||
// Malformed input section.
|
||||
NotifyUser("Cannot load scenario input section for " + scenarioName +
|
||||
" Make sure root of input section markup has x:Name of 'Input'", NotifyType::ErrorMessage); |
||||
return; |
||||
} |
||||
|
||||
if (output == nullptr) |
||||
{ |
||||
// Malformed output section.
|
||||
NotifyUser("Cannot load scenario output section for " + scenarioName +
|
||||
" Make sure root of output section markup has x:Name of 'Output'", NotifyType::ErrorMessage); |
||||
return; |
||||
} |
||||
|
||||
// Find the LayoutRoot which parents the input and output sections in the main page.
|
||||
Panel^ panel = safe_cast<Panel^>(hiddenPage->FindName("LayoutRoot")); |
||||
|
||||
if (panel != nullptr) |
||||
{ |
||||
unsigned int index = 0; |
||||
UIElementCollection^ collection = panel->Children; |
||||
|
||||
// Get rid of the content that is currently in the intput and output sections.
|
||||
collection->IndexOf(input, &index); |
||||
collection->RemoveAt(index); |
||||
|
||||
collection->IndexOf(output, &index); |
||||
collection->RemoveAt(index); |
||||
|
||||
// Populate the input and output sections with the newly loaded content.
|
||||
InputSection->Content = input; |
||||
OutputSection->Content = output; |
||||
|
||||
ScenarioLoaded(this, nullptr); |
||||
} |
||||
else |
||||
{ |
||||
// Malformed Scenario file.
|
||||
NotifyUser("Cannot load scenario: " + scenarioName + ". Make sure root tag in the '" +
|
||||
scenarioName + "' file has an x:Name of 'LayoutRoot'", NotifyType::ErrorMessage); |
||||
} |
||||
} |
||||
|
||||
void MainPage::Scenarios_SelectionChanged(Object^ sender, SelectionChangedEventArgs^ e) |
||||
{ |
||||
if (Scenarios->SelectedItem != nullptr) |
||||
{ |
||||
NotifyUser("", NotifyType::StatusMessage); |
||||
|
||||
LoadScenario((safe_cast<ListBoxItem^>(Scenarios->SelectedItem))->Name); |
||||
InvalidateSize(); |
||||
} |
||||
} |
||||
|
||||
void MainPage::NotifyUser(String^ strMessage, NotifyType type) |
||||
{ |
||||
switch (type) |
||||
{ |
||||
case NotifyType::StatusMessage: |
||||
// Use the status message style.
|
||||
StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("StatusStyle")); |
||||
break; |
||||
case NotifyType::ErrorMessage: |
||||
// Use the error message style.
|
||||
StatusBlock->Style = safe_cast<Windows::UI::Xaml::Style^>(this->Resources->Lookup("ErrorStyle")); |
||||
break; |
||||
default: |
||||
break; |
||||
} |
||||
StatusBlock->Text = strMessage; |
||||
|
||||
// Collapsed the StatusBlock if it has no text to conserve real estate.
|
||||
if (StatusBlock->Text != "") |
||||
{ |
||||
StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Visible; |
||||
} |
||||
else |
||||
{ |
||||
StatusBlock->Visibility = Windows::UI::Xaml::Visibility::Collapsed; |
||||
} |
||||
} |
||||
|
||||
void MainPage::Footer_Click(Object^ sender, RoutedEventArgs^ e) |
||||
{ |
||||
auto uri = ref new Uri((String^)((HyperlinkButton^)sender)->Tag); |
||||
Windows::System::Launcher::LaunchUriAsync(uri); |
||||
} |
||||
|
||||
|
||||
/// <summary>
|
||||
/// Populates the page with content passed during navigation. Any saved state is also
|
||||
/// provided when recreating a page from a prior session.
|
||||
/// </summary>
|
||||
/// <param name="navigationParameter">The parameter value passed to
|
||||
/// <see cref="Frame::Navigate(Type, Object)"/> when this page was initially requested.
|
||||
/// </param>
|
||||
/// <param name="pageState">A map of state preserved by this page during an earlier
|
||||
/// session. This will be null the first time a page is visited.</param>
|
||||
void MainPage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState) |
||||
{ |
||||
(void) navigationParameter; // Unused parameter
|
||||
|
||||
PopulateScenarios(); |
||||
|
||||
// Starting scenario is the first or based upon a previous state.
|
||||
ListBoxItem^ startingScenario = nullptr; |
||||
int startingScenarioIndex = -1; |
||||
|
||||
if (pageState != nullptr && pageState->HasKey("SelectedScenarioIndex")) |
||||
{ |
||||
startingScenarioIndex = safe_cast<int>(pageState->Lookup("SelectedScenarioIndex")); |
||||
} |
||||
|
||||
Scenarios->SelectedIndex = startingScenarioIndex != -1 ? startingScenarioIndex : 0; |
||||
|
||||
InvalidateViewState(); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Preserves state associated with this page in case the application is suspended or the
|
||||
/// page is discarded from the navigation cache. Values must conform to the serialization
|
||||
/// requirements of <see cref="SuspensionManager::SessionState"/>.
|
||||
/// </summary>
|
||||
/// <param name="pageState">An empty map to be populated with serializable state.</param>
|
||||
void MainPage::SaveState(IMap<String^, Object^>^ pageState) |
||||
{ |
||||
int selectedListBoxItemIndex = Scenarios->SelectedIndex; |
||||
pageState->Insert("SelectedScenarioIndex", selectedListBoxItemIndex); |
||||
} |
@ -0,0 +1,105 @@ |
||||
//*********************************************************
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
|
||||
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
|
||||
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
|
||||
//
|
||||
//*********************************************************
|
||||
|
||||
//
|
||||
// MainPage.xaml.h
|
||||
// Declaration of the MainPage.xaml class.
|
||||
//
|
||||
|
||||
#pragma once |
||||
|
||||
#include "pch.h" |
||||
#include "MainPage.g.h" |
||||
#include "Common\LayoutAwarePage.h" // Required by generated header |
||||
#include "Constants.h" |
||||
|
||||
namespace SDKSample |
||||
{ |
||||
public enum class NotifyType |
||||
{ |
||||
StatusMessage, |
||||
ErrorMessage |
||||
}; |
||||
|
||||
public ref class MainPageSizeChangedEventArgs sealed |
||||
{ |
||||
public: |
||||
property Windows::UI::ViewManagement::ApplicationViewState ViewState |
||||
{ |
||||
Windows::UI::ViewManagement::ApplicationViewState get() |
||||
{ |
||||
return viewState; |
||||
} |
||||
|
||||
void set(Windows::UI::ViewManagement::ApplicationViewState value) |
||||
{ |
||||
viewState = value; |
||||
} |
||||
} |
||||
|
||||
private: |
||||
Windows::UI::ViewManagement::ApplicationViewState viewState; |
||||
}; |
||||
|
||||
public ref class MainPage sealed |
||||
{ |
||||
public: |
||||
MainPage(); |
||||
|
||||
protected: |
||||
virtual void LoadState(Platform::Object^ navigationParameter, |
||||
Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override; |
||||
virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState) override; |
||||
|
||||
internal: |
||||
property bool AutoSizeInputSectionWhenSnapped |
||||
{ |
||||
bool get() |
||||
{ |
||||
return autoSizeInputSectionWhenSnapped; |
||||
} |
||||
|
||||
void set(bool value) |
||||
{ |
||||
autoSizeInputSectionWhenSnapped = value; |
||||
} |
||||
} |
||||
|
||||
property Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ LaunchArgs |
||||
{ |
||||
Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ get() |
||||
{ |
||||
return safe_cast<App^>(App::Current)->LaunchArgs; |
||||
} |
||||
} |
||||
|
||||
void NotifyUser(Platform::String^ strMessage, NotifyType type); |
||||
void LoadScenario(Platform::String^ scenarioName); |
||||
event Windows::Foundation::EventHandler<Platform::Object^>^ ScenarioLoaded; |
||||
event Windows::Foundation::EventHandler<MainPageSizeChangedEventArgs^>^ MainPageResized; |
||||
|
||||
private: |
||||
void PopulateScenarios(); |
||||
void InvalidateSize(); |
||||
void InvalidateViewState(); |
||||
|
||||
Platform::Collections::Vector<Object^>^ ScenarioList; |
||||
Windows::UI::Xaml::Controls::Frame^ HiddenFrame; |
||||
void Footer_Click(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); |
||||
bool autoSizeInputSectionWhenSnapped; |
||||
|
||||
void MainPage_SizeChanged(Object^ sender, Windows::UI::Xaml::SizeChangedEventArgs^ e); |
||||
void Scenarios_SelectionChanged(Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e); |
||||
|
||||
internal: |
||||
static MainPage^ Current; |
||||
|
||||
}; |
||||
} |
@ -0,0 +1,81 @@ |
||||
#pragma once |
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// AsyncCallback [template]
|
||||
//
|
||||
// Description:
|
||||
// Helper class that routes IMFAsyncCallback::Invoke calls to a class
|
||||
// method on the parent class.
|
||||
//
|
||||
// Usage:
|
||||
// Add this class as a member variable. In the parent class constructor,
|
||||
// initialize the AsyncCallback class like this:
|
||||
// m_cb(this, &CYourClass::OnInvoke)
|
||||
// where
|
||||
// m_cb = AsyncCallback object
|
||||
// CYourClass = parent class
|
||||
// OnInvoke = Method in the parent class to receive Invoke calls.
|
||||
//
|
||||
// The parent's OnInvoke method (you can name it anything you like) must
|
||||
// have a signature that matches the InvokeFn typedef below.
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// T: Type of the parent object
|
||||
template<class T> |
||||
class AsyncCallback : public IMFAsyncCallback |
||||
{ |
||||
public:
|
||||
typedef HRESULT (T::*InvokeFn)(IMFAsyncResult *pAsyncResult); |
||||
|
||||
AsyncCallback(T *pParent, InvokeFn fn) : m_pParent(pParent), m_pInvokeFn(fn) |
||||
{ |
||||
} |
||||
|
||||
// IUnknown
|
||||
STDMETHODIMP_(ULONG) AddRef() {
|
||||
// Delegate to parent class.
|
||||
return m_pParent->AddRef();
|
||||
} |
||||
STDMETHODIMP_(ULONG) Release() {
|
||||
// Delegate to parent class.
|
||||
return m_pParent->Release();
|
||||
} |
||||
STDMETHODIMP QueryInterface(REFIID iid, void** ppv) |
||||
{ |
||||
if (!ppv) |
||||
{ |
||||
return E_POINTER; |
||||
} |
||||
if (iid == __uuidof(IUnknown)) |
||||
{ |
||||
*ppv = static_cast<IUnknown*>(static_cast<IMFAsyncCallback*>(this)); |
||||
} |
||||
else if (iid == __uuidof(IMFAsyncCallback)) |
||||
{ |
||||
*ppv = static_cast<IMFAsyncCallback*>(this); |
||||
} |
||||
else |
||||
{ |
||||
*ppv = NULL; |
||||
return E_NOINTERFACE; |
||||
} |
||||
AddRef(); |
||||
return S_OK; |
||||
} |
||||
|
||||
|
||||
// IMFAsyncCallback methods
|
||||
STDMETHODIMP GetParameters(DWORD*, DWORD*) |
||||
{ |
||||
// Implementation of this method is optional.
|
||||
return E_NOTIMPL; |
||||
} |
||||
|
||||
STDMETHODIMP Invoke(IMFAsyncResult* pAsyncResult) |
||||
{ |
||||
return (m_pParent->*m_pInvokeFn)(pAsyncResult); |
||||
} |
||||
|
||||
T *m_pParent; |
||||
InvokeFn m_pInvokeFn; |
||||
}; |
@ -0,0 +1,102 @@ |
||||
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
|
||||
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
|
||||
// PARTICULAR PURPOSE.
|
||||
//
|
||||
// Copyright (c) Microsoft Corporation. All rights reserved
|
||||
|
||||
|
||||
#pragma once |
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// VideoBufferLock
|
||||
//
|
||||
// Description:
|
||||
// Locks a video buffer that might or might not support IMF2DBuffer.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
class VideoBufferLock |
||||
{ |
||||
public: |
||||
VideoBufferLock(IMFMediaBuffer *pBuffer) : m_p2DBuffer(NULL) |
||||
{ |
||||
m_pBuffer = pBuffer; |
||||
m_pBuffer->AddRef(); |
||||
|
||||
// Query for the 2-D buffer interface. OK if this fails.
|
||||
m_pBuffer->QueryInterface(IID_PPV_ARGS(&m_p2DBuffer)); |
||||
} |
||||
|
||||
~VideoBufferLock() |
||||
{ |
||||
UnlockBuffer(); |
||||
SafeRelease(&m_pBuffer); |
||||
SafeRelease(&m_p2DBuffer); |
||||
} |
||||
|
||||
// LockBuffer:
|
||||
// Locks the buffer. Returns a pointer to scan line 0 and returns the stride.
|
||||
|
||||
// The caller must provide the default stride as an input parameter, in case
|
||||
// the buffer does not expose IMF2DBuffer. You can calculate the default stride
|
||||
// from the media type.
|
||||
|
||||
HRESULT LockBuffer( |
||||
LONG lDefaultStride, // Minimum stride (with no padding).
|
||||
DWORD dwHeightInPixels, // Height of the image, in pixels.
|
||||
BYTE **ppbScanLine0, // Receives a pointer to the start of scan line 0.
|
||||
LONG *plStride // Receives the actual stride.
|
||||
) |
||||
{ |
||||
HRESULT hr = S_OK; |
||||
|
||||
// Use the 2-D version if available.
|
||||
if (m_p2DBuffer) |
||||
{ |
||||
hr = m_p2DBuffer->Lock2D(ppbScanLine0, plStride); |
||||
} |
||||
else |
||||
{ |
||||
// Use non-2D version.
|
||||
BYTE *pData = NULL; |
||||
|
||||
hr = m_pBuffer->Lock(&pData, NULL, NULL); |
||||
if (SUCCEEDED(hr)) |
||||
{ |
||||
*plStride = lDefaultStride; |
||||
if (lDefaultStride < 0) |
||||
{ |
||||
// Bottom-up orientation. Return a pointer to the start of the
|
||||
// last row *in memory* which is the top row of the image.
|
||||
*ppbScanLine0 = pData + abs(lDefaultStride) * (dwHeightInPixels - 1); |
||||
} |
||||
else |
||||
{ |
||||
// Top-down orientation. Return a pointer to the start of the
|
||||
// buffer.
|
||||
*ppbScanLine0 = pData; |
||||
} |
||||
} |
||||
} |
||||
return hr; |
||||
} |
||||
|
||||
HRESULT UnlockBuffer() |
||||
{ |
||||
if (m_p2DBuffer) |
||||
{ |
||||
return m_p2DBuffer->Unlock2D(); |
||||
} |
||||
else |
||||
{ |
||||
return m_pBuffer->Unlock(); |
||||
} |
||||
} |
||||
|
||||
private: |
||||
IMFMediaBuffer *m_pBuffer; |
||||
IMF2DBuffer *m_p2DBuffer; |
||||
}; |
||||
|
@ -0,0 +1,62 @@ |
||||
#pragma once |
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// CritSec
|
||||
// Description: Wraps a critical section.
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
class CritSec |
||||
{ |
||||
public: |
||||
CRITICAL_SECTION m_criticalSection; |
||||
public: |
||||
CritSec() |
||||
{ |
||||
InitializeCriticalSectionEx(&m_criticalSection, 100, 0); |
||||
} |
||||
|
||||
~CritSec() |
||||
{ |
||||
DeleteCriticalSection(&m_criticalSection); |
||||
} |
||||
|
||||
_Acquires_lock_(m_criticalSection) |
||||
void Lock() |
||||
{ |
||||
EnterCriticalSection(&m_criticalSection); |
||||
} |
||||
|
||||
_Releases_lock_(m_criticalSection) |
||||
void Unlock() |
||||
{ |
||||
LeaveCriticalSection(&m_criticalSection); |
||||
} |
||||
}; |
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// AutoLock
|
||||
// Description: Provides automatic locking and unlocking of a
|
||||
// of a critical section.
|
||||
//
|
||||
// Note: The AutoLock object must go out of scope before the CritSec.
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
class AutoLock |
||||
{ |
||||
private: |
||||
CritSec *m_pCriticalSection; |
||||
public: |
||||
_Acquires_lock_(m_pCriticalSection) |
||||
AutoLock(CritSec& crit) |
||||
{ |
||||
m_pCriticalSection = &crit; |
||||
m_pCriticalSection->Lock(); |
||||
} |
||||
|
||||
_Releases_lock_(m_pCriticalSection) |
||||
~AutoLock() |
||||
{ |
||||
m_pCriticalSection->Unlock(); |
||||
} |
||||
}; |
@ -0,0 +1,516 @@ |
||||
//-----------------------------------------------------------------------------
|
||||
// File: Linklist.h
|
||||
// Desc: Linked list class.
|
||||
//
|
||||
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
|
||||
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
|
||||
// PARTICULAR PURPOSE.
|
||||
//
|
||||
// Copyright (C) Microsoft Corporation. All rights reserved.
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
#pragma once |
||||
|
||||
// Notes:
|
||||
//
|
||||
// The List class template implements a simple double-linked list.
|
||||
// It uses STL's copy semantics.
|
||||
|
||||
// There are two versions of the Clear() method:
|
||||
// Clear(void) clears the list w/out cleaning up the object.
|
||||
// Clear(FN fn) takes a functor object that releases the objects, if they need cleanup.
|
||||
|
||||
// The List class supports enumeration. Example of usage:
|
||||
//
|
||||
// List<T>::POSIITON pos = list.GetFrontPosition();
|
||||
// while (pos != list.GetEndPosition())
|
||||
// {
|
||||
// T item;
|
||||
// hr = list.GetItemPos(&item);
|
||||
// pos = list.Next(pos);
|
||||
// }
|
||||
|
||||
// The ComPtrList class template derives from List<> and implements a list of COM pointers.
|
||||
|
||||
template <class T> |
||||
struct NoOp |
||||
{ |
||||
void operator()(T& t) |
||||
{ |
||||
} |
||||
}; |
||||
|
||||
template <class T> |
||||
class List |
||||
{ |
||||
protected: |
||||
|
||||
// Nodes in the linked list
|
||||
struct Node |
||||
{ |
||||
Node *prev; |
||||
Node *next; |
||||
T item; |
||||
|
||||
Node() : prev(nullptr), next(nullptr) |
||||
{ |
||||
} |
||||
|
||||
Node(T item) : prev(nullptr), next(nullptr) |
||||
{ |
||||
this->item = item; |
||||
} |
||||
|
||||
T Item() const { return item; } |
||||
}; |
||||
|
||||
public: |
||||
|
||||
// Object for enumerating the list.
|
||||
class POSITION |
||||
{ |
||||
friend class List<T>; |
||||
|
||||
public: |
||||
POSITION() : pNode(nullptr) |
||||
{ |
||||
} |
||||
|
||||
bool operator==(const POSITION &p) const |
||||
{ |
||||
return pNode == p.pNode; |
||||
} |
||||
|
||||
bool operator!=(const POSITION &p) const |
||||
{ |
||||
return pNode != p.pNode; |
||||
} |
||||
|
||||
private: |
||||
const Node *pNode; |
||||
|
||||
POSITION(Node *p) : pNode(p)
|
||||
{ |
||||
} |
||||
}; |
||||
|
||||
protected: |
||||
Node m_anchor; // Anchor node for the linked list.
|
||||
DWORD m_count; // Number of items in the list.
|
||||
|
||||
Node* Front() const |
||||
{ |
||||
return m_anchor.next; |
||||
} |
||||
|
||||
Node* Back() const |
||||
{ |
||||
return m_anchor.prev; |
||||
} |
||||
|
||||
virtual HRESULT InsertAfter(T item, Node *pBefore) |
||||
{ |
||||
if (pBefore == nullptr) |
||||
{ |
||||
return E_POINTER; |
||||
} |
||||
|
||||
Node *pNode = new Node(item); |
||||
if (pNode == nullptr) |
||||
{ |
||||
return E_OUTOFMEMORY; |
||||
} |
||||
|
||||
Node *pAfter = pBefore->next; |
||||
|
||||
pBefore->next = pNode; |
||||
pAfter->prev = pNode; |
||||
|
||||
pNode->prev = pBefore; |
||||
pNode->next = pAfter; |
||||
|
||||
m_count++; |
||||
|
||||
return S_OK; |
||||
} |
||||
|
||||
virtual HRESULT GetItem(const Node *pNode, T* ppItem) |
||||
{ |
||||
if (pNode == nullptr || ppItem == nullptr) |
||||
{ |
||||
return E_POINTER; |
||||
} |
||||
|
||||
*ppItem = pNode->item; |
||||
return S_OK; |
||||
} |
||||
|
||||
// RemoveItem:
|
||||
// Removes a node and optionally returns the item.
|
||||
// ppItem can be nullptr.
|
||||
virtual HRESULT RemoveItem(Node *pNode, T *ppItem) |
||||
{ |
||||
if (pNode == nullptr) |
||||
{ |
||||
return E_POINTER; |
||||
} |
||||
|
||||
assert(pNode != &m_anchor); // We should never try to remove the anchor node.
|
||||
if (pNode == &m_anchor) |
||||
{ |
||||
return E_INVALIDARG; |
||||
} |
||||
|
||||
|
||||
T item; |
||||
|
||||
// The next node's previous is this node's previous.
|
||||
pNode->next->prev = pNode->prev; |
||||
|
||||
// The previous node's next is this node's next.
|
||||
pNode->prev->next = pNode->next; |
||||
|
||||
item = pNode->item; |
||||
delete pNode; |
||||
|
||||
m_count--; |
||||
|
||||
if (ppItem) |
||||
{ |
||||
*ppItem = item; |
||||
} |
||||
|
||||
return S_OK; |
||||
} |
||||
|
||||
public: |
||||
|
||||
List() |
||||
{ |
||||
m_anchor.next = &m_anchor; |
||||
m_anchor.prev = &m_anchor; |
||||
|
||||
m_count = 0; |
||||
} |
||||
|
||||
virtual ~List() |
||||
{ |
||||
Clear(); |
||||
} |
||||
|
||||
// Insertion functions
|
||||
HRESULT InsertBack(T item) |
||||
{ |
||||
return InsertAfter(item, m_anchor.prev); |
||||
} |
||||
|
||||
|
||||
HRESULT InsertFront(T item) |
||||
{ |
||||
return InsertAfter(item, &m_anchor); |
||||
} |
||||
|
||||
HRESULT InsertPos(POSITION pos, T item) |
||||
{ |
||||
if (pos.pNode == nullptr) |
||||
{ |
||||
return InsertBack(item); |
||||
} |
||||
|
||||
return InsertAfter(item, pos.pNode->prev); |
||||
} |
||||
|
||||
// RemoveBack: Removes the tail of the list and returns the value.
|
||||
// ppItem can be nullptr if you don't want the item back. (But the method does not release the item.)
|
||||
HRESULT RemoveBack(T *ppItem) |
||||
{ |
||||
if (IsEmpty()) |
||||
{ |
||||
return E_FAIL; |
||||
} |
||||
else |
||||
{ |
||||
return RemoveItem(Back(), ppItem); |
||||
} |
||||
} |
||||
|
||||
// RemoveFront: Removes the head of the list and returns the value.
|
||||
// ppItem can be nullptr if you don't want the item back. (But the method does not release the item.)
|
||||
HRESULT RemoveFront(T *ppItem) |
||||
{ |
||||
if (IsEmpty()) |
||||
{ |
||||
return E_FAIL; |
||||
} |
||||
else |
||||
{ |
||||
return RemoveItem(Front(), ppItem); |
||||
} |
||||
} |
||||
|
||||
// GetBack: Gets the tail item.
|
||||
HRESULT GetBack(T *ppItem) |
||||
{ |
||||
if (IsEmpty()) |
||||
{ |
||||
return E_FAIL; |
||||
} |
||||
else |
||||
{ |
||||
return GetItem(Back(), ppItem); |
||||
} |
||||
} |
||||
|
||||
// GetFront: Gets the front item.
|
||||
HRESULT GetFront(T *ppItem) |
||||
{ |
||||
if (IsEmpty()) |
||||
{ |
||||
return E_FAIL; |
||||
} |
||||
else |
||||
{ |
||||
return GetItem(Front(), ppItem); |
||||
} |
||||
} |
||||
|
||||
|
||||
// GetCount: Returns the number of items in the list.
|
||||
DWORD GetCount() const { return m_count; } |
||||
|
||||
bool IsEmpty() const |
||||
{ |
||||
return (GetCount() == 0); |
||||
} |
||||
|
||||
// Clear: Takes a functor object whose operator()
|
||||
// frees the object on the list.
|
||||
template <class FN> |
||||
void Clear(FN& clear_fn) |
||||
{ |
||||
Node *n = m_anchor.next; |
||||
|
||||
// Delete the nodes
|
||||
while (n != &m_anchor) |
||||
{ |
||||
clear_fn(n->item); |
||||
|
||||
Node *tmp = n->next; |
||||
delete n; |
||||
n = tmp; |
||||
} |
||||
|
||||
// Reset the anchor to point at itself
|
||||
m_anchor.next = &m_anchor; |
||||
m_anchor.prev = &m_anchor; |
||||
|
||||
m_count = 0; |
||||
} |
||||
|
||||
// Clear: Clears the list. (Does not delete or release the list items.)
|
||||
virtual void Clear() |
||||
{ |
||||
NoOp<T> clearOp; |
||||
Clear<>(clearOp); |
||||
} |
||||
|
||||
|
||||
// Enumerator functions
|
||||
|
||||
POSITION FrontPosition() |
||||
{ |
||||
if (IsEmpty()) |
||||
{ |
||||
return POSITION(nullptr); |
||||
} |
||||
else |
||||
{ |
||||
return POSITION(Front()); |
||||
} |
||||
} |
||||
|
||||
POSITION EndPosition() const |
||||
{ |
||||
return POSITION(); |
||||
} |
||||
|
||||
HRESULT GetItemPos(POSITION pos, T *ppItem) |
||||
{
|
||||
if (pos.pNode) |
||||
{ |
||||
return GetItem(pos.pNode, ppItem); |
||||
} |
||||
else
|
||||
{ |
||||
return E_FAIL; |
||||
} |
||||
} |
||||
|
||||
POSITION Next(const POSITION pos) |
||||
{ |
||||
if (pos.pNode && (pos.pNode->next != &m_anchor)) |
||||
{ |
||||
return POSITION(pos.pNode->next); |
||||
} |
||||
else |
||||
{ |
||||
return POSITION(nullptr); |
||||
} |
||||
} |
||||
|
||||
// Remove an item at a position.
|
||||
// The item is returns in ppItem, unless ppItem is nullptr.
|
||||
// NOTE: This method invalidates the POSITION object.
|
||||
HRESULT Remove(POSITION& pos, T *ppItem) |
||||
{ |
||||
if (pos.pNode) |
||||
{ |
||||
// Remove const-ness temporarily...
|
||||
Node *pNode = const_cast<Node*>(pos.pNode); |
||||
|
||||
pos = POSITION(); |
||||
|
||||
return RemoveItem(pNode, ppItem); |
||||
} |
||||
else |
||||
{ |
||||
return E_INVALIDARG; |
||||
} |
||||
} |
||||
|
||||
}; |
||||
|
||||
|
||||
|
||||
// Typical functors for Clear method.
|
||||
|
||||
// ComAutoRelease: Releases COM pointers.
|
||||
// MemDelete: Deletes pointers to new'd memory.
|
||||
|
||||
class ComAutoRelease |
||||
{ |
||||
public:
|
||||
void operator()(IUnknown *p) |
||||
{ |
||||
if (p) |
||||
{ |
||||
p->Release(); |
||||
} |
||||
} |
||||
}; |
||||
|
||||
class MemDelete |
||||
{ |
||||
public:
|
||||
void operator()(void *p) |
||||
{ |
||||
if (p) |
||||
{ |
||||
delete p; |
||||
} |
||||
} |
||||
}; |
||||
|
||||
|
||||
// ComPtrList class
|
||||
// Derived class that makes it safer to store COM pointers in the List<> class.
|
||||
// It automatically AddRef's the pointers that are inserted onto the list
|
||||
// (unless the insertion method fails).
|
||||
//
|
||||
// T must be a COM interface type.
|
||||
// example: ComPtrList<IUnknown>
|
||||
//
|
||||
// NULLABLE: If true, client can insert nullptr pointers. This means GetItem can
|
||||
// succeed but return a nullptr pointer. By default, the list does not allow nullptr
|
||||
// pointers.
|
||||
|
||||
template <class T, bool NULLABLE = FALSE> |
||||
class ComPtrList : public List<T*> |
||||
{ |
||||
public: |
||||
|
||||
typedef T* Ptr; |
||||
|
||||
void Clear() |
||||
{ |
||||
ComAutoRelease car; |
||||
List<Ptr>::Clear(car); |
||||
} |
||||
|
||||
~ComPtrList() |
||||
{ |
||||
Clear(); |
||||
} |
||||
|
||||
protected: |
||||
HRESULT InsertAfter(Ptr item, Node *pBefore) |
||||
{ |
||||
// Do not allow nullptr item pointers unless NULLABLE is true.
|
||||
if (item == nullptr && !NULLABLE) |
||||
{ |
||||
return E_POINTER; |
||||
} |
||||
|
||||
if (item) |
||||
{ |
||||
item->AddRef(); |
||||
} |
||||
|
||||
HRESULT hr = List<Ptr>::InsertAfter(item, pBefore); |
||||
if (FAILED(hr) && item != nullptr) |
||||
{ |
||||
item->Release(); |
||||
} |
||||
return hr; |
||||
} |
||||
|
||||
HRESULT GetItem(const Node *pNode, Ptr* ppItem) |
||||
{ |
||||
Ptr pItem = nullptr; |
||||
|
||||
// The base class gives us the pointer without AddRef'ing it.
|
||||
// If we return the pointer to the caller, we must AddRef().
|
||||
HRESULT hr = List<Ptr>::GetItem(pNode, &pItem); |
||||
if (SUCCEEDED(hr)) |
||||
{ |
||||
assert(pItem || NULLABLE); |
||||
if (pItem) |
||||
{ |
||||
*ppItem = pItem; |
||||
(*ppItem)->AddRef(); |
||||
} |
||||
} |
||||
return hr; |
||||
} |
||||
|
||||
HRESULT RemoveItem(Node *pNode, Ptr *ppItem) |
||||
{ |
||||
// ppItem can be nullptr, but we need to get the
|
||||
// item so that we can release it.
|
||||
|
||||
// If ppItem is not nullptr, we will AddRef it on the way out.
|
||||
|
||||
Ptr pItem = nullptr; |
||||
|
||||
HRESULT hr = List<Ptr>::RemoveItem(pNode, &pItem); |
||||
|
||||
if (SUCCEEDED(hr)) |
||||
{ |
||||
assert(pItem || NULLABLE); |
||||
if (ppItem && pItem) |
||||
{ |
||||
*ppItem = pItem; |
||||
(*ppItem)->AddRef(); |
||||
} |
||||
|
||||
if (pItem) |
||||
{ |
||||
pItem->Release(); |
||||
pItem = nullptr; |
||||
} |
||||
} |
||||
|
||||
return hr; |
||||
} |
||||
}; |
@ -0,0 +1,222 @@ |
||||
//////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// OpQueue.h
|
||||
// Async operation queue.
|
||||
//
|
||||
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
|
||||
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
|
||||
// PARTICULAR PURPOSE.
|
||||
//
|
||||
// Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#pragma once |
||||
|
||||
#pragma warning( push ) |
||||
#pragma warning( disable : 4355 ) // 'this' used in base member initializer list
|
||||
|
||||
/*
|
||||
This header file defines an object to help queue and serialize |
||||
asynchronous operations. |
||||
|
||||
Background: |
||||
|
||||
To perform an operation asynchronously in Media Foundation, an object |
||||
does one of the following: |
||||
|
||||
1. Calls MFPutWorkItem(Ex), using either a standard work queue |
||||
identifier or a caller-allocated work queue. The work-queue |
||||
thread invokes the object's callback. |
||||
|
||||
2. Creates an async result object (IMFAsyncResult) and calls |
||||
MFInvokeCallback to invoke the object's callback. |
||||
|
||||
Ultimately, either of these cause the object's callback to be invoked |
||||
from a work-queue thread. The object can then complete the operation |
||||
inside the callback. |
||||
|
||||
However, the Media Foundation platform may dispatch async callbacks in |
||||
parallel on several threads. Putting an item on a work queue does NOT |
||||
guarantee that one operation will complete before the next one starts, |
||||
or even that work items will be dispatched in the same order they were |
||||
called. |
||||
|
||||
To serialize async operations that should not overlap, an object should |
||||
use a queue. While one operation is pending, subsequent operations are |
||||
put on the queue, and only dispatched after the previous operation is |
||||
complete. |
||||
|
||||
The granularity of a single "operation" depends on the requirements of |
||||
that particular object. A single operation might involve several |
||||
asynchronous calls before the object dispatches the next operation on |
||||
the queue. |
||||
|
||||
|
||||
*/ |
||||
|
||||
|
||||
|
||||
//-------------------------------------------------------------------
|
||||
// OpQueue class template
|
||||
//
|
||||
// Base class for an async operation queue.
|
||||
//
|
||||
// TOperation: The class used to describe operations. This class must
|
||||
// implement IUnknown.
|
||||
//
|
||||
// The OpQueue class is an abstract class. The derived class must
|
||||
// implement the following pure-virtual methods:
|
||||
//
|
||||
// - IUnknown methods (AddRef, Release, QI)
|
||||
//
|
||||
// - DispatchOperation:
|
||||
//
|
||||
// Performs the asynchronous operation specified by pOp.
|
||||
//
|
||||
// At the end of each operation, the derived class must call
|
||||
// ProcessQueue to process the next operation in the queue.
|
||||
//
|
||||
// NOTE: An operation is not required to complete inside the
|
||||
// DispatchOperation method. A single operation might consist
|
||||
// of several asynchronous method calls.
|
||||
//
|
||||
// - ValidateOperation:
|
||||
//
|
||||
// Checks whether the object can perform the operation specified
|
||||
// by pOp at this time.
|
||||
//
|
||||
// If the object cannot perform the operation now (e.g., because
|
||||
// another operation is still in progress) the method should
|
||||
// return MF_E_NOTACCEPTING.
|
||||
//
|
||||
//-------------------------------------------------------------------
|
||||
#include "linklist.h" |
||||
#include "AsyncCB.h" |
||||
|
||||
template <class T, class TOperation> |
||||
class OpQueue //: public IUnknown
|
||||
{ |
||||
public: |
||||
|
||||
typedef ComPtrList<TOperation> OpList; |
||||
|
||||
HRESULT QueueOperation(TOperation *pOp); |
||||
|
||||
protected: |
||||
|
||||
HRESULT ProcessQueue(); |
||||
HRESULT ProcessQueueAsync(IMFAsyncResult *pResult); |
||||
|
||||
virtual HRESULT DispatchOperation(TOperation *pOp) = 0; |
||||
virtual HRESULT ValidateOperation(TOperation *pOp) = 0; |
||||
|
||||
OpQueue(CRITICAL_SECTION& critsec) |
||||
: m_OnProcessQueue(static_cast<T *>(this), &OpQueue::ProcessQueueAsync), |
||||
m_critsec(critsec) |
||||
{ |
||||
} |
||||
|
||||
virtual ~OpQueue() |
||||
{ |
||||
} |
||||
|
||||
protected: |
||||
OpList m_OpQueue; // Queue of operations.
|
||||
CRITICAL_SECTION& m_critsec; // Protects the queue state.
|
||||
AsyncCallback<T> m_OnProcessQueue; // ProcessQueueAsync callback.
|
||||
}; |
||||
|
||||
|
||||
|
||||
//-------------------------------------------------------------------
|
||||
// Place an operation on the queue.
|
||||
// Public method.
|
||||
//-------------------------------------------------------------------
|
||||
|
||||
template <class T, class TOperation> |
||||
HRESULT OpQueue<T, TOperation>::QueueOperation(TOperation *pOp) |
||||
{ |
||||
HRESULT hr = S_OK; |
||||
|
||||
EnterCriticalSection(&m_critsec); |
||||
|
||||
hr = m_OpQueue.InsertBack(pOp); |
||||
if (SUCCEEDED(hr)) |
||||
{ |
||||
hr = ProcessQueue(); |
||||
} |
||||
|
||||
LeaveCriticalSection(&m_critsec); |
||||
return hr; |
||||
} |
||||
|
||||
|
||||
//-------------------------------------------------------------------
|
||||
// Process the next operation on the queue.
|
||||
// Protected method.
|
||||
//
|
||||
// Note: This method dispatches the operation to a work queue.
|
||||
//-------------------------------------------------------------------
|
||||
|
||||
template <class T, class TOperation> |
||||
HRESULT OpQueue<T, TOperation>::ProcessQueue() |
||||
{ |
||||
HRESULT hr = S_OK; |
||||
if (m_OpQueue.GetCount() > 0) |
||||
{ |
||||
hr = MFPutWorkItem2( |
||||
MFASYNC_CALLBACK_QUEUE_STANDARD, // Use the standard work queue.
|
||||
0, // Default priority
|
||||
&m_OnProcessQueue, // Callback method.
|
||||
nullptr // State object.
|
||||
); |
||||
} |
||||
return hr; |
||||
} |
||||
|
||||
|
||||
//-------------------------------------------------------------------
|
||||
// Process the next operation on the queue.
|
||||
// Protected method.
|
||||
//
|
||||
// Note: This method is called from a work-queue thread.
|
||||
//-------------------------------------------------------------------
|
||||
|
||||
template <class T, class TOperation> |
||||
HRESULT OpQueue<T, TOperation>::ProcessQueueAsync(IMFAsyncResult *pResult) |
||||
{ |
||||
HRESULT hr = S_OK; |
||||
TOperation *pOp = nullptr; |
||||
|
||||
EnterCriticalSection(&m_critsec); |
||||
|
||||
if (m_OpQueue.GetCount() > 0) |
||||
{ |
||||
hr = m_OpQueue.GetFront(&pOp); |
||||
|
||||
if (SUCCEEDED(hr)) |
||||
{ |
||||
hr = ValidateOperation(pOp); |
||||
} |
||||
if (SUCCEEDED(hr)) |
||||
{ |
||||
hr = m_OpQueue.RemoveFront(nullptr); |
||||
} |
||||
if (SUCCEEDED(hr)) |
||||
{ |
||||
(void)DispatchOperation(pOp); |
||||
} |
||||
} |
||||
|
||||
if (pOp != nullptr) |
||||
{ |
||||
pOp->Release(); |
||||
} |
||||
|
||||
LeaveCriticalSection(&m_critsec); |
||||
return hr; |
||||
} |
||||
|
||||
#pragma warning( pop ) |
@ -0,0 +1,4 @@ |
||||
EXPORTS |
||||
DllCanUnloadNow PRIVATE |
||||
DllGetActivationFactory PRIVATE |
||||
DllGetClassObject PRIVATE |
@ -0,0 +1,266 @@ |
||||
// Defines the transform class.
|
||||
//
|
||||
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
|
||||
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
|
||||
// PARTICULAR PURPOSE.
|
||||
//
|
||||
// Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
|
||||
#ifndef GRAYSCALE_H |
||||
#define GRAYSCALE_H |
||||
|
||||
#include <new> |
||||
#include <mfapi.h> |
||||
#include <mftransform.h> |
||||
#include <mfidl.h> |
||||
#include <mferror.h> |
||||
#include <strsafe.h> |
||||
#include <assert.h> |
||||
|
||||
// Note: The Direct2D helper library is included for its 2D matrix operations.
|
||||
#include <D2d1helper.h> |
||||
|
||||
#include <wrl\implements.h> |
||||
#include <wrl\module.h> |
||||
#include <windows.media.h> |
||||
|
||||
#include "GrayscaleTransform.h" |
||||
|
||||
// CLSID of the MFT.
|
||||
DEFINE_GUID(CLSID_GrayscaleMFT, |
||||
0x2f3dbc05, 0xc011, 0x4a8f, 0xb2, 0x64, 0xe4, 0x2e, 0x35, 0xc6, 0x7b, 0xf4); |
||||
|
||||
//
|
||||
// * IMPORTANT: If you implement your own MFT, create a new GUID for the CLSID. *
|
||||
//
|
||||
|
||||
|
||||
// Configuration attributes
|
||||
|
||||
// {7BBBB051-133B-41F5-B6AA-5AFF9B33A2CB}
|
||||
DEFINE_GUID(MFT_GRAYSCALE_DESTINATION_RECT,
|
||||
0x7bbbb051, 0x133b, 0x41f5, 0xb6, 0xaa, 0x5a, 0xff, 0x9b, 0x33, 0xa2, 0xcb); |
||||
|
||||
|
||||
// {14782342-93E8-4565-872C-D9A2973D5CBF}
|
||||
DEFINE_GUID(MFT_GRAYSCALE_SATURATION,
|
||||
0x14782342, 0x93e8, 0x4565, 0x87, 0x2c, 0xd9, 0xa2, 0x97, 0x3d, 0x5c, 0xbf); |
||||
|
||||
// {E0BADE5D-E4B9-4689-9DBA-E2F00D9CED0E}
|
||||
DEFINE_GUID(MFT_GRAYSCALE_CHROMA_ROTATION,
|
||||
0xe0bade5d, 0xe4b9, 0x4689, 0x9d, 0xba, 0xe2, 0xf0, 0xd, 0x9c, 0xed, 0xe); |
||||
|
||||
|
||||
template <class T> void SafeRelease(T **ppT) |
||||
{ |
||||
if (*ppT) |
||||
{ |
||||
(*ppT)->Release(); |
||||
*ppT = NULL; |
||||
} |
||||
} |
||||
|
||||
// Function pointer for the function that transforms the image.
|
||||
typedef void (*IMAGE_TRANSFORM_FN)( |
||||
const D2D1::Matrix3x2F& mat, // Chroma transform matrix.
|
||||
const D2D_RECT_U& rcDest, // Destination rectangle for the transformation.
|
||||
BYTE* pDest, // Destination buffer.
|
||||
LONG lDestStride, // Destination stride.
|
||||
const BYTE* pSrc, // Source buffer.
|
||||
LONG lSrcStride, // Source stride.
|
||||
DWORD dwWidthInPixels, // Image width in pixels.
|
||||
DWORD dwHeightInPixels // Image height in pixels.
|
||||
); |
||||
|
||||
// CGrayscale class:
|
||||
// Implements a grayscale video effect.
|
||||
|
||||
class CGrayscale
|
||||
: public Microsoft::WRL::RuntimeClass< |
||||
Microsoft::WRL::RuntimeClassFlags< Microsoft::WRL::RuntimeClassType::WinRtClassicComMix >,
|
||||
ABI::Windows::Media::IMediaExtension, |
||||
IMFTransform > |
||||
{ |
||||
InspectableClass(RuntimeClass_GrayscaleTransform_GrayscaleEffect, BaseTrust) |
||||
|
||||
public: |
||||
CGrayscale(); |
||||
|
||||
~CGrayscale(); |
||||
|
||||
STDMETHOD(RuntimeClassInitialize)(); |
||||
|
||||
// IMediaExtension
|
||||
STDMETHODIMP SetProperties(ABI::Windows::Foundation::Collections::IPropertySet *pConfiguration); |
||||
|
||||
// IMFTransform
|
||||
STDMETHODIMP GetStreamLimits( |
||||
DWORD *pdwInputMinimum, |
||||
DWORD *pdwInputMaximum, |
||||
DWORD *pdwOutputMinimum, |
||||
DWORD *pdwOutputMaximum |
||||
); |
||||
|
||||
STDMETHODIMP GetStreamCount( |
||||
DWORD *pcInputStreams, |
||||
DWORD *pcOutputStreams |
||||
); |
||||
|
||||
STDMETHODIMP GetStreamIDs( |
||||
DWORD dwInputIDArraySize, |
||||
DWORD *pdwInputIDs, |
||||
DWORD dwOutputIDArraySize, |
||||
DWORD *pdwOutputIDs |
||||
); |
||||
|
||||
STDMETHODIMP GetInputStreamInfo( |
||||
DWORD dwInputStreamID, |
||||
MFT_INPUT_STREAM_INFO * pStreamInfo |
||||
); |
||||
|
||||
STDMETHODIMP GetOutputStreamInfo( |
||||
DWORD dwOutputStreamID, |
||||
MFT_OUTPUT_STREAM_INFO * pStreamInfo |
||||
); |
||||
|
||||
STDMETHODIMP GetAttributes(IMFAttributes** pAttributes); |
||||
|
||||
STDMETHODIMP GetInputStreamAttributes( |
||||
DWORD dwInputStreamID, |
||||
IMFAttributes **ppAttributes |
||||
); |
||||
|
||||
STDMETHODIMP GetOutputStreamAttributes( |
||||
DWORD dwOutputStreamID, |
||||
IMFAttributes **ppAttributes |
||||
); |
||||
|
||||
STDMETHODIMP DeleteInputStream(DWORD dwStreamID); |
||||
|
||||
STDMETHODIMP AddInputStreams( |
||||
DWORD cStreams, |
||||
DWORD *adwStreamIDs |
||||
); |
||||
|
||||
STDMETHODIMP GetInputAvailableType( |
||||
DWORD dwInputStreamID, |
||||
DWORD dwTypeIndex, // 0-based
|
||||
IMFMediaType **ppType |
||||
); |
||||
|
||||
STDMETHODIMP GetOutputAvailableType( |
||||
DWORD dwOutputStreamID, |
||||
DWORD dwTypeIndex, // 0-based
|
||||
IMFMediaType **ppType |
||||
); |
||||
|
||||
STDMETHODIMP SetInputType( |
||||
DWORD dwInputStreamID, |
||||
IMFMediaType *pType, |
||||
DWORD dwFlags |
||||
); |
||||
|
||||
STDMETHODIMP SetOutputType( |
||||
DWORD dwOutputStreamID, |
||||
IMFMediaType *pType, |
||||
DWORD dwFlags |
||||
); |
||||
|
||||
STDMETHODIMP GetInputCurrentType( |
||||
DWORD dwInputStreamID, |
||||
IMFMediaType **ppType |
||||
); |
||||
|
||||
STDMETHODIMP GetOutputCurrentType( |
||||
DWORD dwOutputStreamID, |
||||
IMFMediaType **ppType |
||||
); |
||||
|
||||
STDMETHODIMP GetInputStatus( |
||||
DWORD dwInputStreamID, |
||||
DWORD *pdwFlags |
||||
); |
||||
|
||||
STDMETHODIMP GetOutputStatus(DWORD *pdwFlags); |
||||
|
||||
STDMETHODIMP SetOutputBounds( |
||||
LONGLONG hnsLowerBound, |
||||
LONGLONG hnsUpperBound |
||||
); |
||||
|
||||
STDMETHODIMP ProcessEvent( |
||||
DWORD dwInputStreamID, |
||||
IMFMediaEvent *pEvent |
||||
); |
||||
|
||||
STDMETHODIMP ProcessMessage( |
||||
MFT_MESSAGE_TYPE eMessage, |
||||
ULONG_PTR ulParam |
||||
); |
||||
|
||||
STDMETHODIMP ProcessInput( |
||||
DWORD dwInputStreamID, |
||||
IMFSample *pSample, |
||||
DWORD dwFlags |
||||
); |
||||
|
||||
STDMETHODIMP ProcessOutput( |
||||
DWORD dwFlags, |
||||
DWORD cOutputBufferCount, |
||||
MFT_OUTPUT_DATA_BUFFER *pOutputSamples, // one per stream
|
||||
DWORD *pdwStatus |
||||
); |
||||
|
||||
|
||||
private: |
||||
// HasPendingOutput: Returns TRUE if the MFT is holding an input sample.
|
||||
BOOL HasPendingOutput() const { return m_pSample != NULL; } |
||||
|
||||
// IsValidInputStream: Returns TRUE if dwInputStreamID is a valid input stream identifier.
|
||||
BOOL IsValidInputStream(DWORD dwInputStreamID) const |
||||
{ |
||||
return dwInputStreamID == 0; |
||||
} |
||||
|
||||
// IsValidOutputStream: Returns TRUE if dwOutputStreamID is a valid output stream identifier.
|
||||
BOOL IsValidOutputStream(DWORD dwOutputStreamID) const |
||||
{ |
||||
return dwOutputStreamID == 0; |
||||
} |
||||
|
||||
HRESULT OnGetPartialType(DWORD dwTypeIndex, IMFMediaType **ppmt); |
||||
HRESULT OnCheckInputType(IMFMediaType *pmt); |
||||
HRESULT OnCheckOutputType(IMFMediaType *pmt); |
||||
HRESULT OnCheckMediaType(IMFMediaType *pmt); |
||||
void OnSetInputType(IMFMediaType *pmt); |
||||
void OnSetOutputType(IMFMediaType *pmt); |
||||
HRESULT BeginStreaming(); |
||||
HRESULT EndStreaming(); |
||||
HRESULT OnProcessOutput(IMFMediaBuffer *pIn, IMFMediaBuffer *pOut); |
||||
HRESULT OnFlush(); |
||||
HRESULT UpdateFormatInfo(); |
||||
|
||||
CRITICAL_SECTION m_critSec; |
||||
|
||||
// Transformation parameters
|
||||
D2D1::Matrix3x2F m_transform; // Chroma transform matrix.
|
||||
D2D_RECT_U m_rcDest; // Destination rectangle for the effect.
|
||||
|
||||
// Streaming
|
||||
bool m_bStreamingInitialized; |
||||
IMFSample *m_pSample; // Input sample.
|
||||
IMFMediaType *m_pInputType; // Input media type.
|
||||
IMFMediaType *m_pOutputType; // Output media type.
|
||||
|
||||
// Fomat information
|
||||
UINT32 m_imageWidthInPixels; |
||||
UINT32 m_imageHeightInPixels; |
||||
DWORD m_cbImageSize; // Image size, in bytes.
|
||||
|
||||
IMFAttributes *m_pAttributes; |
||||
|
||||
// Image transform function. (Changes based on the media type.)
|
||||
IMAGE_TRANSFORM_FN m_pTransformFn; |
||||
}; |
||||
#endif |
@ -0,0 +1,11 @@ |
||||
import "Windows.Media.idl"; |
||||
|
||||
#include <sdkddkver.h> |
||||
|
||||
namespace GrayscaleTransform |
||||
{ |
||||
[version(NTDDI_WIN8)] |
||||
runtimeclass GrayscaleEffect |
||||
{ |
||||
} |
||||
} |
@ -0,0 +1,58 @@ |
||||
//////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// dllmain.cpp
|
||||
//
|
||||
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
|
||||
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
|
||||
// PARTICULAR PURPOSE.
|
||||
//
|
||||
// Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#include <initguid.h> |
||||
#include "Grayscale.h" |
||||
|
||||
using namespace Microsoft::WRL; |
||||
|
||||
namespace Microsoft { namespace Samples { |
||||
ActivatableClass(CGrayscale); |
||||
}} |
||||
|
||||
BOOL WINAPI DllMain( _In_ HINSTANCE hInstance, _In_ DWORD dwReason, _In_opt_ LPVOID lpReserved ) |
||||
{ |
||||
if( DLL_PROCESS_ATTACH == dwReason ) |
||||
{ |
||||
//
|
||||
// Don't need per-thread callbacks
|
||||
//
|
||||
DisableThreadLibraryCalls( hInstance ); |
||||
|
||||
Module<InProc>::GetModule().Create(); |
||||
} |
||||
else if( DLL_PROCESS_DETACH == dwReason ) |
||||
{ |
||||
Module<InProc>::GetModule().Terminate(); |
||||
} |
||||
|
||||
return TRUE; |
||||
} |
||||
|
||||
HRESULT WINAPI DllGetActivationFactory( _In_ HSTRING activatibleClassId, _Outptr_ IActivationFactory** factory ) |
||||
{ |
||||
auto &module = Microsoft::WRL::Module< Microsoft::WRL::InProc >::GetModule(); |
||||
return module.GetActivationFactory( activatibleClassId, factory ); |
||||
} |
||||
|
||||
HRESULT WINAPI DllCanUnloadNow() |
||||
{ |
||||
auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule();
|
||||
return (module.Terminate()) ? S_OK : S_FALSE; |
||||
} |
||||
|
||||
STDAPI DllGetClassObject( _In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID FAR* ppv ) |
||||
{ |
||||
auto &module = Microsoft::WRL::Module<Microsoft::WRL::InProc>::GetModule(); |
||||
return module.GetClassObject( rclsid, riid, ppv ); |
||||
} |
After Width: | Height: | Size: 1.5 KiB |
After Width: | Height: | Size: 8.8 KiB |
After Width: | Height: | Size: 1.2 KiB |
After Width: | Height: | Size: 4.9 KiB |
After Width: | Height: | Size: 2.4 KiB |
After Width: | Height: | Size: 1.5 KiB |
After Width: | Height: | Size: 2.6 KiB |
After Width: | Height: | Size: 2.9 KiB |
@ -0,0 +1,452 @@ |
||||
//*********************************************************
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
|
||||
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
|
||||
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
|
||||
//
|
||||
//*********************************************************
|
||||
|
||||
#include "pch.h" |
||||
#include "LayoutAwarePage.h" |
||||
#include "SuspensionManager.h" |
||||
|
||||
using namespace SDKSample::Common; |
||||
|
||||
using namespace Platform; |
||||
using namespace Platform::Collections; |
||||
using namespace Windows::Foundation; |
||||
using namespace Windows::Foundation::Collections; |
||||
using namespace Windows::System; |
||||
using namespace Windows::UI::Core; |
||||
using namespace Windows::UI::ViewManagement; |
||||
using namespace Windows::UI::Xaml; |
||||
using namespace Windows::UI::Xaml::Controls; |
||||
using namespace Windows::UI::Xaml::Interop; |
||||
using namespace Windows::UI::Xaml::Navigation; |
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LayoutAwarePage"/> class.
|
||||
/// </summary>
|
||||
LayoutAwarePage::LayoutAwarePage() |
||||
{ |
||||
if (Windows::ApplicationModel::DesignMode::DesignModeEnabled) |
||||
{ |
||||
return; |
||||
} |
||||
|
||||
// Create an empty default view model
|
||||
DefaultViewModel = ref new Map<String^, Object^>(std::less<String^>()); |
||||
|
||||
// When this page is part of the visual tree make two changes:
|
||||
// 1) Map application view state to visual state for the page
|
||||
// 2) Handle keyboard and mouse navigation requests
|
||||
Loaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnLoaded); |
||||
|
||||
// Undo the same changes when the page is no longer visible
|
||||
Unloaded += ref new RoutedEventHandler(this, &LayoutAwarePage::OnUnloaded); |
||||
} |
||||
|
||||
static DependencyProperty^ _defaultViewModelProperty = |
||||
DependencyProperty::Register("DefaultViewModel", |
||||
TypeName(IObservableMap<String^, Object^>::typeid), TypeName(LayoutAwarePage::typeid), nullptr); |
||||
|
||||
/// <summary>
|
||||
/// Identifies the <see cref="DefaultViewModel"/> dependency property.
|
||||
/// </summary>
|
||||
DependencyProperty^ LayoutAwarePage::DefaultViewModelProperty::get() |
||||
{ |
||||
return _defaultViewModelProperty; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Gets an implementation of <see cref="IObservableMap<String, Object>"/> designed to be
|
||||
/// used as a trivial view model.
|
||||
/// </summary>
|
||||
IObservableMap<String^, Object^>^ LayoutAwarePage::DefaultViewModel::get() |
||||
{ |
||||
return safe_cast<IObservableMap<String^, Object^>^>(GetValue(DefaultViewModelProperty)); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Sets an implementation of <see cref="IObservableMap<String, Object>"/> designed to be
|
||||
/// used as a trivial view model.
|
||||
/// </summary>
|
||||
void LayoutAwarePage::DefaultViewModel::set(IObservableMap<String^, Object^>^ value) |
||||
{ |
||||
SetValue(DefaultViewModelProperty, value); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Invoked when the page is part of the visual tree
|
||||
/// </summary>
|
||||
/// <param name="sender">Instance that triggered the event.</param>
|
||||
/// <param name="e">Event data describing the conditions that led to the event.</param>
|
||||
void LayoutAwarePage::OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) |
||||
{ |
||||
this->StartLayoutUpdates(sender, e); |
||||
|
||||
// Keyboard and mouse navigation only apply when occupying the entire window
|
||||
if (this->ActualHeight == Window::Current->Bounds.Height && |
||||
this->ActualWidth == Window::Current->Bounds.Width) |
||||
{ |
||||
// Listen to the window directly so focus isn't required
|
||||
_acceleratorKeyEventToken = Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated += |
||||
ref new TypedEventHandler<CoreDispatcher^, AcceleratorKeyEventArgs^>(this, |
||||
&LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated); |
||||
_pointerPressedEventToken = Window::Current->CoreWindow->PointerPressed += |
||||
ref new TypedEventHandler<CoreWindow^, PointerEventArgs^>(this, |
||||
&LayoutAwarePage::CoreWindow_PointerPressed); |
||||
_navigationShortcutsRegistered = true; |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Invoked when the page is removed from visual tree
|
||||
/// </summary>
|
||||
/// <param name="sender">Instance that triggered the event.</param>
|
||||
/// <param name="e">Event data describing the conditions that led to the event.</param>
|
||||
void LayoutAwarePage::OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) |
||||
{ |
||||
if (_navigationShortcutsRegistered) |
||||
{ |
||||
Window::Current->CoreWindow->Dispatcher->AcceleratorKeyActivated -= _acceleratorKeyEventToken; |
||||
Window::Current->CoreWindow->PointerPressed -= _pointerPressedEventToken; |
||||
_navigationShortcutsRegistered = false; |
||||
} |
||||
StopLayoutUpdates(sender, e); |
||||
} |
||||
|
||||
#pragma region Navigation support |
||||
|
||||
/// <summary>
|
||||
/// Invoked as an event handler to navigate backward in the page's associated <see cref="Frame"/>
|
||||
/// until it reaches the top of the navigation stack.
|
||||
/// </summary>
|
||||
/// <param name="sender">Instance that triggered the event.</param>
|
||||
/// <param name="e">Event data describing the conditions that led to the event.</param>
|
||||
void LayoutAwarePage::GoHome(Object^ sender, RoutedEventArgs^ e) |
||||
{ |
||||
(void) sender; // Unused parameter
|
||||
(void) e; // Unused parameter
|
||||
|
||||
// Use the navigation frame to return to the topmost page
|
||||
if (Frame != nullptr) |
||||
{ |
||||
while (Frame->CanGoBack) |
||||
{ |
||||
Frame->GoBack(); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Invoked as an event handler to navigate backward in the navigation stack
|
||||
/// associated with this page's <see cref="Frame"/>.
|
||||
/// </summary>
|
||||
/// <param name="sender">Instance that triggered the event.</param>
|
||||
/// <param name="e">Event data describing the conditions that led to the event.</param>
|
||||
void LayoutAwarePage::GoBack(Object^ sender, RoutedEventArgs^ e) |
||||
{ |
||||
(void) sender; // Unused parameter
|
||||
(void) e; // Unused parameter
|
||||
|
||||
// Use the navigation frame to return to the previous page
|
||||
if (Frame != nullptr && Frame->CanGoBack) |
||||
{ |
||||
Frame->GoBack(); |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Invoked as an event handler to navigate forward in the navigation stack
|
||||
/// associated with this page's <see cref="Frame"/>.
|
||||
/// </summary>
|
||||
/// <param name="sender">Instance that triggered the event.</param>
|
||||
/// <param name="e">Event data describing the conditions that led to the event.</param>
|
||||
void LayoutAwarePage::GoForward(Object^ sender, RoutedEventArgs^ e) |
||||
{ |
||||
(void) sender; // Unused parameter
|
||||
(void) e; // Unused parameter
|
||||
|
||||
// Use the navigation frame to advance to the next page
|
||||
if (Frame != nullptr && Frame->CanGoForward) |
||||
{ |
||||
Frame->GoForward(); |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Invoked on every keystroke, including system keys such as Alt key combinations, when
|
||||
/// this page is active and occupies the entire window. Used to detect keyboard navigation
|
||||
/// between pages even when the page itself doesn't have focus.
|
||||
/// </summary>
|
||||
/// <param name="sender">Instance that triggered the event.</param>
|
||||
/// <param name="args">Event data describing the conditions that led to the event.</param>
|
||||
void LayoutAwarePage::CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher^ sender, AcceleratorKeyEventArgs^ args) |
||||
{ |
||||
auto virtualKey = args->VirtualKey; |
||||
|
||||
// Only investigate further when Left, Right, or the dedicated Previous or Next keys
|
||||
// are pressed
|
||||
if ((args->EventType == CoreAcceleratorKeyEventType::SystemKeyDown || |
||||
args->EventType == CoreAcceleratorKeyEventType::KeyDown) && |
||||
(virtualKey == VirtualKey::Left || virtualKey == VirtualKey::Right || |
||||
(int)virtualKey == 166 || (int)virtualKey == 167)) |
||||
{ |
||||
auto coreWindow = Window::Current->CoreWindow; |
||||
auto downState = Windows::UI::Core::CoreVirtualKeyStates::Down; |
||||
bool menuKey = (coreWindow->GetKeyState(VirtualKey::Menu) & downState) == downState; |
||||
bool controlKey = (coreWindow->GetKeyState(VirtualKey::Control) & downState) == downState; |
||||
bool shiftKey = (coreWindow->GetKeyState(VirtualKey::Shift) & downState) == downState; |
||||
bool noModifiers = !menuKey && !controlKey && !shiftKey; |
||||
bool onlyAlt = menuKey && !controlKey && !shiftKey; |
||||
|
||||
if (((int)virtualKey == 166 && noModifiers) || |
||||
(virtualKey == VirtualKey::Left && onlyAlt)) |
||||
{ |
||||
// When the previous key or Alt+Left are pressed navigate back
|
||||
args->Handled = true; |
||||
GoBack(this, ref new RoutedEventArgs()); |
||||
} |
||||
else if (((int)virtualKey == 167 && noModifiers) || |
||||
(virtualKey == VirtualKey::Right && onlyAlt)) |
||||
{ |
||||
// When the next key or Alt+Right are pressed navigate forward
|
||||
args->Handled = true; |
||||
GoForward(this, ref new RoutedEventArgs()); |
||||
} |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
|
||||
/// page is active and occupies the entire window. Used to detect browser-style next and
|
||||
/// previous mouse button clicks to navigate between pages.
|
||||
/// </summary>
|
||||
/// <param name="sender">Instance that triggered the event.</param>
|
||||
/// <param name="args">Event data describing the conditions that led to the event.</param>
|
||||
void LayoutAwarePage::CoreWindow_PointerPressed(CoreWindow^ sender, PointerEventArgs^ args) |
||||
{ |
||||
auto properties = args->CurrentPoint->Properties; |
||||
|
||||
// Ignore button chords with the left, right, and middle buttons
|
||||
if (properties->IsLeftButtonPressed || properties->IsRightButtonPressed || |
||||
properties->IsMiddleButtonPressed) return; |
||||
|
||||
// If back or foward are pressed (but not both) navigate appropriately
|
||||
bool backPressed = properties->IsXButton1Pressed; |
||||
bool forwardPressed = properties->IsXButton2Pressed; |
||||
if (backPressed ^ forwardPressed) |
||||
{ |
||||
args->Handled = true; |
||||
if (backPressed) GoBack(this, ref new RoutedEventArgs()); |
||||
if (forwardPressed) GoForward(this, ref new RoutedEventArgs()); |
||||
} |
||||
} |
||||
|
||||
#pragma endregion |
||||
|
||||
#pragma region Visual state switching |
||||
|
||||
/// <summary>
|
||||
/// Invoked as an event handler, typically on the <see cref="Loaded"/> event of a
|
||||
/// <see cref="Control"/> within the page, to indicate that the sender should start receiving
|
||||
/// visual state management changes that correspond to application view state changes.
|
||||
/// </summary>
|
||||
/// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
|
||||
/// corresponding to view states.</param>
|
||||
/// <param name="e">Event data that describes how the request was made.</param>
|
||||
/// <remarks>The current view state will immediately be used to set the corresponding visual state
|
||||
/// when layout updates are requested. A corresponding <see cref="Unloaded"/> event handler
|
||||
/// connected to <see cref="StopLayoutUpdates"/> is strongly encouraged. Instances of
|
||||
/// <see cref="LayoutAwarePage"/> automatically invoke these handlers in their Loaded and Unloaded
|
||||
/// events.</remarks>
|
||||
/// <seealso cref="DetermineVisualState"/>
|
||||
/// <seealso cref="InvalidateVisualState"/>
|
||||
void LayoutAwarePage::StartLayoutUpdates(Object^ sender, RoutedEventArgs^ e) |
||||
{ |
||||
(void) e; // Unused parameter
|
||||
|
||||
auto control = safe_cast<Control^>(sender); |
||||
if (_layoutAwareControls == nullptr) |
||||
{ |
||||
// Start listening to view state changes when there are controls interested in updates
|
||||
_layoutAwareControls = ref new Vector<Control^>(); |
||||
_windowSizeEventToken = Window::Current->SizeChanged += ref new WindowSizeChangedEventHandler(this, &LayoutAwarePage::WindowSizeChanged); |
||||
|
||||
// Page receives notifications for children. Protect the page until we stopped layout updates for all controls.
|
||||
_this = this; |
||||
} |
||||
_layoutAwareControls->Append(control); |
||||
|
||||
// Set the initial visual state of the control
|
||||
VisualStateManager::GoToState(control, DetermineVisualState(ApplicationView::Value), false); |
||||
} |
||||
|
||||
void LayoutAwarePage::WindowSizeChanged(Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e) |
||||
{ |
||||
(void) sender; // Unused parameter
|
||||
(void) e; // Unused parameter
|
||||
|
||||
InvalidateVisualState(); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Invoked as an event handler, typically on the <see cref="Unloaded"/> event of a
|
||||
/// <see cref="Control"/>, to indicate that the sender should start receiving visual state
|
||||
/// management changes that correspond to application view state changes.
|
||||
/// </summary>
|
||||
/// <param name="sender">Instance of <see cref="Control"/> that supports visual state management
|
||||
/// corresponding to view states.</param>
|
||||
/// <param name="e">Event data that describes how the request was made.</param>
|
||||
/// <remarks>The current view state will immediately be used to set the corresponding visual state
|
||||
/// when layout updates are requested.</remarks>
|
||||
/// <seealso cref="StartLayoutUpdates"/>
|
||||
void LayoutAwarePage::StopLayoutUpdates(Object^ sender, RoutedEventArgs^ e) |
||||
{ |
||||
(void) e; // Unused parameter
|
||||
|
||||
auto control = safe_cast<Control^>(sender); |
||||
unsigned int index; |
||||
if (_layoutAwareControls != nullptr && _layoutAwareControls->IndexOf(control, &index)) |
||||
{ |
||||
_layoutAwareControls->RemoveAt(index); |
||||
if (_layoutAwareControls->Size == 0) |
||||
{ |
||||
// Stop listening to view state changes when no controls are interested in updates
|
||||
Window::Current->SizeChanged -= _windowSizeEventToken; |
||||
_layoutAwareControls = nullptr; |
||||
// Last control has received the Unload notification.
|
||||
_this = nullptr; |
||||
} |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Translates <see cref="ApplicationViewState"/> values into strings for visual state management
|
||||
/// within the page. The default implementation uses the names of enum values. Subclasses may
|
||||
/// override this method to control the mapping scheme used.
|
||||
/// </summary>
|
||||
/// <param name="viewState">View state for which a visual state is desired.</param>
|
||||
/// <returns>Visual state name used to drive the <see cref="VisualStateManager"/></returns>
|
||||
/// <seealso cref="InvalidateVisualState"/>
|
||||
String^ LayoutAwarePage::DetermineVisualState(ApplicationViewState viewState) |
||||
{ |
||||
switch (viewState) |
||||
{ |
||||
case ApplicationViewState::Filled: |
||||
return "Filled"; |
||||
case ApplicationViewState::Snapped: |
||||
return "Snapped"; |
||||
case ApplicationViewState::FullScreenPortrait: |
||||
return "FullScreenPortrait"; |
||||
case ApplicationViewState::FullScreenLandscape: |
||||
default: |
||||
return "FullScreenLandscape"; |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Updates all controls that are listening for visual state changes with the correct visual
|
||||
/// state.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Typically used in conjunction with overriding <see cref="DetermineVisualState"/> to
|
||||
/// signal that a different value may be returned even though the view state has not changed.
|
||||
/// </remarks>
|
||||
void LayoutAwarePage::InvalidateVisualState() |
||||
{ |
||||
if (_layoutAwareControls != nullptr) |
||||
{ |
||||
String^ visualState = DetermineVisualState(ApplicationView::Value); |
||||
auto controlIterator = _layoutAwareControls->First(); |
||||
while (controlIterator->HasCurrent) |
||||
{ |
||||
auto control = controlIterator->Current; |
||||
VisualStateManager::GoToState(control, visualState, false); |
||||
controlIterator->MoveNext(); |
||||
} |
||||
} |
||||
} |
||||
|
||||
#pragma endregion |
||||
|
||||
#pragma region Process lifetime management |
||||
|
||||
/// <summary>
|
||||
/// Invoked when this page is about to be displayed in a Frame.
|
||||
/// </summary>
|
||||
/// <param name="e">Event data that describes how this page was reached. The Parameter
|
||||
/// property provides the group to be displayed.</param>
|
||||
void LayoutAwarePage::OnNavigatedTo(NavigationEventArgs^ e) |
||||
{ |
||||
// Returning to a cached page through navigation shouldn't trigger state loading
|
||||
if (_pageKey != nullptr) return; |
||||
|
||||
auto frameState = SuspensionManager::SessionStateForFrame(Frame); |
||||
_pageKey = "Page-" + Frame->BackStackDepth; |
||||
|
||||
if (e->NavigationMode == NavigationMode::New) |
||||
{ |
||||
// Clear existing state for forward navigation when adding a new page to the
|
||||
// navigation stack
|
||||
auto nextPageKey = _pageKey; |
||||
int nextPageIndex = Frame->BackStackDepth; |
||||
while (frameState->HasKey(nextPageKey)) |
||||
{ |
||||
frameState->Remove(nextPageKey); |
||||
nextPageIndex++; |
||||
nextPageKey = "Page-" + nextPageIndex; |
||||
} |
||||
|
||||
// Pass the navigation parameter to the new page
|
||||
LoadState(e->Parameter, nullptr); |
||||
} |
||||
else |
||||
{ |
||||
// Pass the navigation parameter and preserved page state to the page, using
|
||||
// the same strategy for loading suspended state and recreating pages discarded
|
||||
// from cache
|
||||
LoadState(e->Parameter, safe_cast<IMap<String^, Object^>^>(frameState->Lookup(_pageKey))); |
||||
} |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Invoked when this page will no longer be displayed in a Frame.
|
||||
/// </summary>
|
||||
/// <param name="e">Event data that describes how this page was reached. The Parameter
|
||||
/// property provides the group to be displayed.</param>
|
||||
void LayoutAwarePage::OnNavigatedFrom(NavigationEventArgs^ e) |
||||
{ |
||||
auto frameState = SuspensionManager::SessionStateForFrame(Frame); |
||||
auto pageState = ref new Map<String^, Object^>(); |
||||
SaveState(pageState); |
||||
frameState->Insert(_pageKey, pageState); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Populates the page with content passed during navigation. Any saved state is also
|
||||
/// provided when recreating a page from a prior session.
|
||||
/// </summary>
|
||||
/// <param name="navigationParameter">The parameter value passed to
|
||||
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
|
||||
/// </param>
|
||||
/// <param name="pageState">A map of state preserved by this page during an earlier
|
||||
/// session. This will be null the first time a page is visited.</param>
|
||||
void LayoutAwarePage::LoadState(Object^ navigationParameter, IMap<String^, Object^>^ pageState) |
||||
{ |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Preserves state associated with this page in case the application is suspended or the
|
||||
/// page is discarded from the navigation cache. Values must conform to the serialization
|
||||
/// requirements of <see cref="SuspensionManager.SessionState"/>.
|
||||
/// </summary>
|
||||
/// <param name="pageState">An empty map to be populated with serializable state.</param>
|
||||
void LayoutAwarePage::SaveState(IMap<String^, Object^>^ pageState) |
||||
{ |
||||
} |
||||
|
||||
#pragma endregion |
@ -0,0 +1,88 @@ |
||||
//*********************************************************
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
|
||||
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
|
||||
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
|
||||
//
|
||||
//*********************************************************
|
||||
|
||||
#pragma once |
||||
|
||||
#include <collection.h> |
||||
|
||||
namespace SDKSample |
||||
{ |
||||
namespace Common |
||||
{ |
||||
/// <summary>
|
||||
/// Typical implementation of Page that provides several important conveniences:
|
||||
/// <list type="bullet">
|
||||
/// <item>
|
||||
/// <description>Application view state to visual state mapping</description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <description>GoBack, GoForward, and GoHome event handlers</description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <description>Mouse and keyboard shortcuts for navigation</description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <description>State management for navigation and process lifetime management</description>
|
||||
/// </item>
|
||||
/// <item>
|
||||
/// <description>A default view model</description>
|
||||
/// </item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
[Windows::Foundation::Metadata::WebHostHidden] |
||||
public ref class LayoutAwarePage : Windows::UI::Xaml::Controls::Page |
||||
{ |
||||
internal: |
||||
LayoutAwarePage(); |
||||
|
||||
public: |
||||
void StartLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); |
||||
void StopLayoutUpdates(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); |
||||
void InvalidateVisualState(); |
||||
static property Windows::UI::Xaml::DependencyProperty^ DefaultViewModelProperty |
||||
{ |
||||
Windows::UI::Xaml::DependencyProperty^ get(); |
||||
}; |
||||
property Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ DefaultViewModel |
||||
{ |
||||
Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ get(); |
||||
void set(Windows::Foundation::Collections::IObservableMap<Platform::String^, Platform::Object^>^ value); |
||||
} |
||||
|
||||
protected: |
||||
virtual void GoHome(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); |
||||
virtual void GoBack(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); |
||||
virtual void GoForward(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); |
||||
virtual Platform::String^ DetermineVisualState(Windows::UI::ViewManagement::ApplicationViewState viewState); |
||||
virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override; |
||||
virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override; |
||||
virtual void LoadState(Platform::Object^ navigationParameter, |
||||
Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState); |
||||
virtual void SaveState(Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ pageState); |
||||
|
||||
private: |
||||
Platform::String^ _pageKey; |
||||
bool _navigationShortcutsRegistered; |
||||
Platform::Collections::Map<Platform::String^, Platform::Object^>^ _defaultViewModel; |
||||
Windows::Foundation::EventRegistrationToken _windowSizeEventToken, |
||||
_acceleratorKeyEventToken, _pointerPressedEventToken; |
||||
Platform::Collections::Vector<Windows::UI::Xaml::Controls::Control^>^ _layoutAwareControls; |
||||
void WindowSizeChanged(Platform::Object^ sender, Windows::UI::Core::WindowSizeChangedEventArgs^ e); |
||||
void OnLoaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); |
||||
void OnUnloaded(Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); |
||||
|
||||
void CoreDispatcher_AcceleratorKeyActivated(Windows::UI::Core::CoreDispatcher^ sender, |
||||
Windows::UI::Core::AcceleratorKeyEventArgs^ args); |
||||
void CoreWindow_PointerPressed(Windows::UI::Core::CoreWindow^ sender, |
||||
Windows::UI::Core::PointerEventArgs^ args); |
||||
LayoutAwarePage^ _this; // Strong reference to self, cleaned up in OnUnload
|
||||
}; |
||||
} |
||||
} |
@ -0,0 +1,481 @@ |
||||
//*********************************************************
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
|
||||
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
|
||||
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
|
||||
//
|
||||
//*********************************************************
|
||||
|
||||
//
|
||||
// SuspensionManager.cpp
|
||||
// Implementation of the SuspensionManager class
|
||||
//
|
||||
|
||||
#include "pch.h" |
||||
#include "SuspensionManager.h" |
||||
|
||||
#include <collection.h> |
||||
#include <algorithm> |
||||
|
||||
using namespace SDKSample::Common; |
||||
|
||||
using namespace Concurrency; |
||||
using namespace Platform; |
||||
using namespace Platform::Collections; |
||||
using namespace Windows::Foundation; |
||||
using namespace Windows::Foundation::Collections; |
||||
using namespace Windows::Storage; |
||||
using namespace Windows::Storage::FileProperties; |
||||
using namespace Windows::Storage::Streams; |
||||
using namespace Windows::UI::Xaml; |
||||
using namespace Windows::UI::Xaml::Controls; |
||||
using namespace Windows::UI::Xaml::Interop; |
||||
|
||||
namespace |
||||
{ |
||||
Map<String^, Object^>^ _sessionState = ref new Map<String^, Object^>(); |
||||
String^ sessionStateFilename = "_sessionState.dat"; |
||||
|
||||
// Forward declarations for object object read / write support
|
||||
void WriteObject(Windows::Storage::Streams::DataWriter^ writer, Platform::Object^ object); |
||||
Platform::Object^ ReadObject(Windows::Storage::Streams::DataReader^ reader); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Provides access to global session state for the current session. This state is serialized by
|
||||
/// <see cref="SaveAsync"/> and restored by <see cref="RestoreAsync"/> which require values to be
|
||||
/// one of the following: boxed values including integers, floating-point singles and doubles,
|
||||
/// wide characters, boolean, Strings and Guids, or Map<String^, Object^> where map values are
|
||||
/// subject to the same constraints. Session state should be as compact as possible.
|
||||
/// </summary>
|
||||
IMap<String^, Object^>^ SuspensionManager::SessionState::get(void) |
||||
{ |
||||
return _sessionState; |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Wrap a WeakReference as a reference object for use in a collection.
|
||||
/// </summary>
|
||||
private ref class WeakFrame sealed |
||||
{ |
||||
private: |
||||
WeakReference _frameReference; |
||||
|
||||
internal: |
||||
WeakFrame(Frame^ frame) { _frameReference = frame; } |
||||
property Frame^ ResolvedFrame |
||||
{ |
||||
Frame^ get(void) { return _frameReference.Resolve<Frame>(); } |
||||
}; |
||||
}; |
||||
|
||||
namespace |
||||
{ |
||||
std::vector<WeakFrame^> _registeredFrames; |
||||
DependencyProperty^ FrameSessionStateKeyProperty = |
||||
DependencyProperty::RegisterAttached("_FrameSessionStateKeyProperty", |
||||
TypeName(String::typeid), TypeName(SuspensionManager::typeid), nullptr); |
||||
DependencyProperty^ FrameSessionStateProperty = |
||||
DependencyProperty::RegisterAttached("_FrameSessionStateProperty", |
||||
TypeName(IMap<String^, Object^>::typeid), TypeName(SuspensionManager::typeid), nullptr); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Registers a <see cref="Frame"/> instance to allow its navigation history to be saved to
|
||||
/// and restored from <see cref="SessionState"/>. Frames should be registered once
|
||||
/// immediately after creation if they will participate in session state management. Upon
|
||||
/// registration if state has already been restored for the specified key
|
||||
/// the navigation history will immediately be restored. Subsequent invocations of
|
||||
/// <see cref="RestoreAsync(String)"/> will also restore navigation history.
|
||||
/// </summary>
|
||||
/// <param name="frame">An instance whose navigation history should be managed by
|
||||
/// <see cref="SuspensionManager"/></param>
|
||||
/// <param name="sessionStateKey">A unique key into <see cref="SessionState"/> used to
|
||||
/// store navigation-related information.</param>
|
||||
void SuspensionManager::RegisterFrame(Frame^ frame, String^ sessionStateKey) |
||||
{ |
||||
if (frame->GetValue(FrameSessionStateKeyProperty) != nullptr) |
||||
{ |
||||
throw ref new FailureException("Frames can only be registered to one session state key"); |
||||
} |
||||
|
||||
if (frame->GetValue(FrameSessionStateProperty) != nullptr) |
||||
{ |
||||
throw ref new FailureException("Frames must be either be registered before accessing frame session state, or not registered at all"); |
||||
} |
||||
|
||||
// Use a dependency property to associate the session key with a frame, and keep a list of frames whose
|
||||
// navigation state should be managed
|
||||
frame->SetValue(FrameSessionStateKeyProperty, sessionStateKey); |
||||
_registeredFrames.insert(_registeredFrames.begin(), ref new WeakFrame(frame)); |
||||
|
||||
// Check to see if navigation state can be restored
|
||||
RestoreFrameNavigationState(frame); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Disassociates a <see cref="Frame"/> previously registered by <see cref="RegisterFrame"/>
|
||||
/// from <see cref="SessionState"/>. Any navigation state previously captured will be
|
||||
/// removed.
|
||||
/// </summary>
|
||||
/// <param name="frame">An instance whose navigation history should no longer be
|
||||
/// managed.</param>
|
||||
void SuspensionManager::UnregisterFrame(Frame^ frame) |
||||
{ |
||||
// Remove session state and remove the frame from the list of frames whose navigation
|
||||
// state will be saved (along with any weak references that are no longer reachable)
|
||||
auto key = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty)); |
||||
if (SessionState->HasKey(key)) SessionState->Remove(key); |
||||
_registeredFrames.erase( |
||||
std::remove_if(_registeredFrames.begin(), _registeredFrames.end(), [=](WeakFrame^& e) |
||||
{ |
||||
auto testFrame = e->ResolvedFrame; |
||||
return testFrame == nullptr || testFrame == frame; |
||||
}), |
||||
_registeredFrames.end() |
||||
); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Provides storage for session state associated with the specified <see cref="Frame"/>.
|
||||
/// Frames that have been previously registered with <see cref="RegisterFrame"/> have
|
||||
/// their session state saved and restored automatically as a part of the global
|
||||
/// <see cref="SessionState"/>. Frames that are not registered have transient state
|
||||
/// that can still be useful when restoring pages that have been discarded from the
|
||||
/// navigation cache.
|
||||
/// </summary>
|
||||
/// <remarks>Apps may choose to rely on <see cref="LayoutAwarePage"/> to manage
|
||||
/// page-specific state instead of working with frame session state directly.</remarks>
|
||||
/// <param name="frame">The instance for which session state is desired.</param>
|
||||
/// <returns>A collection of state subject to the same serialization mechanism as
|
||||
/// <see cref="SessionState"/>.</returns>
|
||||
IMap<String^, Object^>^ SuspensionManager::SessionStateForFrame(Frame^ frame) |
||||
{ |
||||
auto frameState = safe_cast<IMap<String^, Object^>^>(frame->GetValue(FrameSessionStateProperty)); |
||||
|
||||
if (frameState == nullptr) |
||||
{ |
||||
auto frameSessionKey = safe_cast<String^>(frame->GetValue(FrameSessionStateKeyProperty)); |
||||
if (frameSessionKey != nullptr) |
||||
{ |
||||
// Registered frames reflect the corresponding session state
|
||||
if (!_sessionState->HasKey(frameSessionKey)) |
||||
{ |
||||
_sessionState->Insert(frameSessionKey, ref new Map<String^, Object^>()); |
||||
} |
||||
frameState = safe_cast<IMap<String^, Object^>^>(_sessionState->Lookup(frameSessionKey)); |
||||
} |
||||
else |
||||
{ |
||||
// Frames that aren't registered have transient state
|
||||
frameState = ref new Map<String^, Object^>(); |
||||
} |
||||
frame->SetValue(FrameSessionStateProperty, frameState); |
||||
} |
||||
return frameState; |
||||
} |
||||
|
||||
void SuspensionManager::RestoreFrameNavigationState(Frame^ frame) |
||||
{ |
||||
auto frameState = SessionStateForFrame(frame); |
||||
if (frameState->HasKey("Navigation")) |
||||
{ |
||||
frame->SetNavigationState(safe_cast<String^>(frameState->Lookup("Navigation"))); |
||||
} |
||||
} |
||||
|
||||
void SuspensionManager::SaveFrameNavigationState(Frame^ frame) |
||||
{ |
||||
auto frameState = SessionStateForFrame(frame); |
||||
frameState->Insert("Navigation", frame->GetNavigationState()); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Save the current <see cref="SessionState"/>. Any <see cref="Frame"/> instances
|
||||
/// registered with <see cref="RegisterFrame"/> will also preserve their current
|
||||
/// navigation stack, which in turn gives their active <see cref="Page"/> an opportunity
|
||||
/// to save its state.
|
||||
/// </summary>
|
||||
/// <returns>An asynchronous task that reflects when session state has been saved.</returns>
|
||||
task<void> SuspensionManager::SaveAsync(void) |
||||
{ |
||||
// Save the navigation state for all registered frames
|
||||
for (auto&& weakFrame : _registeredFrames) |
||||
{ |
||||
auto frame = weakFrame->ResolvedFrame; |
||||
if (frame != nullptr) SaveFrameNavigationState(frame); |
||||
} |
||||
|
||||
// Serialize the session state synchronously to avoid asynchronous access to shared
|
||||
// state
|
||||
auto sessionData = ref new InMemoryRandomAccessStream(); |
||||
auto sessionDataWriter = ref new DataWriter(sessionData->GetOutputStreamAt(0)); |
||||
WriteObject(sessionDataWriter, _sessionState); |
||||
|
||||
// Once session state has been captured synchronously, begin the asynchronous process
|
||||
// of writing the result to disk
|
||||
return task<unsigned int>(sessionDataWriter->StoreAsync()).then([=](unsigned int) |
||||
{ |
||||
return sessionDataWriter->FlushAsync(); |
||||
}).then([=](bool flushSucceeded) |
||||
{ |
||||
(void)flushSucceeded; // Unused parameter
|
||||
return ApplicationData::Current->LocalFolder->CreateFileAsync(sessionStateFilename, |
||||
CreationCollisionOption::ReplaceExisting); |
||||
}).then([=](StorageFile^ createdFile) |
||||
{ |
||||
return createdFile->OpenAsync(FileAccessMode::ReadWrite); |
||||
}).then([=](IRandomAccessStream^ newStream) |
||||
{ |
||||
return RandomAccessStream::CopyAndCloseAsync( |
||||
sessionData->GetInputStreamAt(0), newStream->GetOutputStreamAt(0)); |
||||
}).then([=](UINT64 copiedBytes) |
||||
{ |
||||
(void)copiedBytes; // Unused parameter
|
||||
return; |
||||
}); |
||||
} |
||||
|
||||
/// <summary>
|
||||
/// Restores previously saved <see cref="SessionState"/>. Any <see cref="Frame"/> instances
|
||||
/// registered with <see cref="RegisterFrame"/> will also restore their prior navigation
|
||||
/// state, which in turn gives their active <see cref="Page"/> an opportunity restore its
|
||||
/// state.
|
||||
/// </summary>
|
||||
/// <param name="version">A version identifer compared to the session state to prevent
|
||||
/// incompatible versions of session state from reaching app code. Saved state with a
|
||||
/// different version will be ignored, resulting in an empty <see cref="SessionState"/>
|
||||
/// dictionary.</param>
|
||||
/// <returns>An asynchronous task that reflects when session state has been read. The
|
||||
/// content of <see cref="SessionState"/> should not be relied upon until this task
|
||||
/// completes.</returns>
|
||||
task<void> SuspensionManager::RestoreAsync(void) |
||||
{ |
||||
_sessionState->Clear(); |
||||
|
||||
task<StorageFile^> getFileTask(ApplicationData::Current->LocalFolder->GetFileAsync(sessionStateFilename)); |
||||
return getFileTask.then([=](StorageFile^ stateFile) |
||||
{ |
||||
task<BasicProperties^> getBasicPropertiesTask(stateFile->GetBasicPropertiesAsync()); |
||||
return getBasicPropertiesTask.then([=](BasicProperties^ stateFileProperties) |
||||
{ |
||||
auto size = unsigned int(stateFileProperties->Size); |
||||
if (size != stateFileProperties->Size) throw ref new FailureException("Session state larger than 4GB"); |
||||
task<IRandomAccessStreamWithContentType^> openReadTask(stateFile->OpenReadAsync()); |
||||
return openReadTask.then([=](IRandomAccessStreamWithContentType^ stateFileStream) |
||||
{ |
||||
auto stateReader = ref new DataReader(stateFileStream); |
||||
return task<unsigned int>(stateReader->LoadAsync(size)).then([=](unsigned int bytesRead) |
||||
{ |
||||
(void)bytesRead; // Unused parameter
|
||||
// Deserialize the Session State
|
||||
Object^ content = ReadObject(stateReader); |
||||
_sessionState = (Map<String^, Object^>^)content; |
||||
|
||||
// Restore any registered frames to their saved state
|
||||
for (auto&& weakFrame : _registeredFrames) |
||||
{ |
||||
auto frame = weakFrame->ResolvedFrame; |
||||
if (frame != nullptr) |
||||
{ |
||||
frame->ClearValue(FrameSessionStateProperty); |
||||
RestoreFrameNavigationState(frame); |
||||
} |
||||
} |
||||
}, task_continuation_context::use_current()); |
||||
}); |
||||
}); |
||||
}); |
||||
} |
||||
|
||||
#pragma region Object serialization for a known set of types |
||||
|
||||
namespace |
||||
{ |
||||
// Codes used for identifying serialized types
|
||||
enum StreamTypes { |
||||
NullPtrType = 0, |
||||
|
||||
// Supported IPropertyValue types
|
||||
UInt8Type, UInt16Type, UInt32Type, UInt64Type, Int16Type, Int32Type, Int64Type, |
||||
SingleType, DoubleType, BooleanType, Char16Type, GuidType, StringType, |
||||
|
||||
// Additional supported types
|
||||
StringToObjectMapType, |
||||
|
||||
// Marker values used to ensure stream integrity
|
||||
MapEndMarker |
||||
}; |
||||
|
||||
void WriteString(DataWriter^ writer, String^ string) |
||||
{ |
||||
writer->WriteByte(StringType); |
||||
writer->WriteUInt32(writer->MeasureString(string)); |
||||
writer->WriteString(string); |
||||
} |
||||
|
||||
void WriteProperty(DataWriter^ writer, IPropertyValue^ propertyValue) |
||||
{ |
||||
switch (propertyValue->Type) |
||||
{ |
||||
case PropertyType::UInt8: |
||||
writer->WriteByte(UInt8Type); |
||||
writer->WriteByte(propertyValue->GetUInt8()); |
||||
return; |
||||
case PropertyType::UInt16: |
||||
writer->WriteByte(UInt16Type); |
||||
writer->WriteUInt16(propertyValue->GetUInt16()); |
||||
return; |
||||
case PropertyType::UInt32: |
||||
writer->WriteByte(UInt32Type); |
||||
writer->WriteUInt32(propertyValue->GetUInt32()); |
||||
return; |
||||
case PropertyType::UInt64: |
||||
writer->WriteByte(UInt64Type); |
||||
writer->WriteUInt64(propertyValue->GetUInt64()); |
||||
return; |
||||
case PropertyType::Int16: |
||||
writer->WriteByte(Int16Type); |
||||
writer->WriteUInt16(propertyValue->GetInt16()); |
||||
return; |
||||
case PropertyType::Int32: |
||||
writer->WriteByte(Int32Type); |
||||
writer->WriteUInt32(propertyValue->GetInt32()); |
||||
return; |
||||
case PropertyType::Int64: |
||||
writer->WriteByte(Int64Type); |
||||
writer->WriteUInt64(propertyValue->GetInt64()); |
||||
return; |
||||
case PropertyType::Single: |
||||
writer->WriteByte(SingleType); |
||||
writer->WriteSingle(propertyValue->GetSingle()); |
||||
return; |
||||
case PropertyType::Double: |
||||
writer->WriteByte(DoubleType); |
||||
writer->WriteDouble(propertyValue->GetDouble()); |
||||
return; |
||||
case PropertyType::Boolean: |
||||
writer->WriteByte(BooleanType); |
||||
writer->WriteBoolean(propertyValue->GetBoolean()); |
||||
return; |
||||
case PropertyType::Char16: |
||||
writer->WriteByte(Char16Type); |
||||
writer->WriteUInt16(propertyValue->GetChar16()); |
||||
return; |
||||
case PropertyType::Guid: |
||||
writer->WriteByte(GuidType); |
||||
writer->WriteGuid(propertyValue->GetGuid()); |
||||
return; |
||||
case PropertyType::String: |
||||
WriteString(writer, propertyValue->GetString()); |
||||
return; |
||||
default: |
||||
throw ref new InvalidArgumentException("Unsupported property type"); |
||||
} |
||||
} |
||||
|
||||
void WriteStringToObjectMap(DataWriter^ writer, IMap<String^, Object^>^ map) |
||||
{ |
||||
writer->WriteByte(StringToObjectMapType); |
||||
writer->WriteUInt32(map->Size); |
||||
for (auto&& pair : map) |
||||
{ |
||||
WriteObject(writer, pair->Key); |
||||
WriteObject(writer, pair->Value); |
||||
} |
||||
writer->WriteByte(MapEndMarker); |
||||
} |
||||
|
||||
void WriteObject(DataWriter^ writer, Object^ object) |
||||
{ |
||||
if (object == nullptr) |
||||
{ |
||||
writer->WriteByte(NullPtrType); |
||||
return; |
||||
} |
||||
|
||||
auto propertyObject = dynamic_cast<IPropertyValue^>(object); |
||||
if (propertyObject != nullptr) |
||||
{ |
||||
WriteProperty(writer, propertyObject); |
||||
return; |
||||
} |
||||
|
||||
auto mapObject = dynamic_cast<IMap<String^, Object^>^>(object); |
||||
if (mapObject != nullptr) |
||||
{ |
||||
WriteStringToObjectMap(writer, mapObject); |
||||
return; |
||||
} |
||||
|
||||
throw ref new InvalidArgumentException("Unsupported data type"); |
||||
} |
||||
|
||||
String^ ReadString(DataReader^ reader) |
||||
{ |
||||
int length = reader->ReadUInt32(); |
||||
String^ string = reader->ReadString(length); |
||||
return string; |
||||
} |
||||
|
||||
IMap<String^, Object^>^ ReadStringToObjectMap(DataReader^ reader) |
||||
{ |
||||
auto map = ref new Map<String^, Object^>(); |
||||
auto size = reader->ReadUInt32(); |
||||
for (unsigned int index = 0; index < size; index++) |
||||
{ |
||||
auto key = safe_cast<String^>(ReadObject(reader)); |
||||
auto value = ReadObject(reader); |
||||
map->Insert(key, value); |
||||
} |
||||
if (reader->ReadByte() != MapEndMarker) |
||||
{ |
||||
throw ref new InvalidArgumentException("Invalid stream"); |
||||
} |
||||
return map; |
||||
} |
||||
|
||||
Object^ ReadObject(DataReader^ reader) |
||||
{ |
||||
auto type = reader->ReadByte(); |
||||
switch (type) |
||||
{ |
||||
case NullPtrType: |
||||
return nullptr; |
||||
case UInt8Type: |
||||
return reader->ReadByte(); |
||||
case UInt16Type: |
||||
return reader->ReadUInt16(); |
||||
case UInt32Type: |
||||
return reader->ReadUInt32(); |
||||
case UInt64Type: |
||||
return reader->ReadUInt64(); |
||||
case Int16Type: |
||||
return reader->ReadInt16(); |
||||
case Int32Type: |
||||
return reader->ReadInt32(); |
||||
case Int64Type: |
||||
return reader->ReadInt64(); |
||||
case SingleType: |
||||
return reader->ReadSingle(); |
||||
case DoubleType: |
||||
return reader->ReadDouble(); |
||||
case BooleanType: |
||||
return reader->ReadBoolean(); |
||||
case Char16Type: |
||||
return (char16_t)reader->ReadUInt16(); |
||||
case GuidType: |
||||
return reader->ReadGuid(); |
||||
case StringType: |
||||
return ReadString(reader); |
||||
case StringToObjectMapType: |
||||
return ReadStringToObjectMap(reader); |
||||
default: |
||||
throw ref new InvalidArgumentException("Unsupported property type"); |
||||
} |
||||
} |
||||
} |
||||
|
||||
#pragma endregion |
@ -0,0 +1,50 @@ |
||||
//*********************************************************
|
||||
//
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
|
||||
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
|
||||
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
|
||||
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
|
||||
//
|
||||
//*********************************************************
|
||||
|
||||
//
|
||||
// SuspensionManager.h
|
||||
// Declaration of the SuspensionManager class
|
||||
//
|
||||
|
||||
#pragma once |
||||
|
||||
#include <ppltasks.h> |
||||
|
||||
namespace SDKSample |
||||
{ |
||||
namespace Common |
||||
{ |
||||
/// <summary>
|
||||
/// SuspensionManager captures global session state to simplify process lifetime management
|
||||
/// for an application. Note that session state will be automatically cleared under a variety
|
||||
/// of conditions and should only be used to store information that would be convenient to
|
||||
/// carry across sessions, but that should be disacarded when an application crashes or is
|
||||
/// upgraded.
|
||||
/// </summary>
|
||||
ref class SuspensionManager sealed |
||||
{ |
||||
internal: |
||||
static void RegisterFrame(Windows::UI::Xaml::Controls::Frame^ frame, Platform::String^ sessionStateKey); |
||||
static void UnregisterFrame(Windows::UI::Xaml::Controls::Frame^ frame); |
||||
static Concurrency::task<void> SaveAsync(void); |
||||
static Concurrency::task<void> RestoreAsync(void); |
||||
static property Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionState |
||||
{ |
||||
Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ get(void); |
||||
}; |
||||
static Windows::Foundation::Collections::IMap<Platform::String^, Platform::Object^>^ SessionStateForFrame( |
||||
Windows::UI::Xaml::Controls::Frame^ frame); |
||||
|
||||
private: |
||||
static void RestoreFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame); |
||||
static void SaveFrameNavigationState(Windows::UI::Xaml::Controls::Frame^ frame); |
||||
}; |
||||
} |
||||
} |
@ -0,0 +1,238 @@ |
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> |
||||
<html> |
||||
<head><link rel="stylesheet" type="text/css" href="description/Combined.css,0:SearchBox,0:ImageSprite;/Areas/Epx/Themes/Metro/Content:0&amp;hashKey=E778FABBB649835AFE4E73BCAC4F643A" xmlns="http://www.w3.org/1999/xhtml" /> |
||||
<link rel="stylesheet" type="text/css" href="description/4ee0dda0-3e7e-46df-b80b-1692acc1c812Combined.css,0:ImageSprite;/Areas/Epx/Themes/Metro/Content:0&amp;hashKey=B88AD897C8197B762EA1BF0238A60A9F" xmlns="http://www.w3.org/1999/xhtml" /> |
||||
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> |
||||
<title>Media capture using capture device sample</title> |
||||
<link href="description/Galleries.css" type="text/css" rel="Stylesheet" /><link href="description/Layout.css" type="text/css" rel="Stylesheet" /><link href="description/Brand.css" type="text/css" rel="Stylesheet" /><link href="description/c2e69f54-1c43-4037-b90b-5f775f1d945fBrand.css" type="text/css" rel="Stylesheet" /> |
||||
<link href="description/iframedescription.css" rel="Stylesheet" type="text/css" /> |
||||
<script src="description/offline.js" type="text/javascript"></script> |
||||
<style type="text/css"> |
||||
#projectInfo { |
||||
overflow: auto; |
||||
} |
||||
#longDesc { |
||||
clear:both; |
||||
margin: 25px 0 10px 0; |
||||
} |
||||
|
||||
#SampleIndexList{ |
||||
margin-left: 15px; |
||||
} |
||||
</style> |
||||
</head> |
||||
<body> |
||||
<div id="offlineDescription"> |
||||
<h1>Media capture using capture device sample</h1> |
||||
<br/> |
||||
<div id="projectInfo"> |
||||
<div class="section"> |
||||
<div class="itemBarLong tagsContainer"> |
||||
<label for="Technologies">Technologies</label> |
||||
<div id="Technologies"> |
||||
Windows Runtime |
||||
</div> |
||||
</div> |
||||
<div class="itemBarLong tagsContainer"> |
||||
<label for="Topics">Topics</label> |
||||
<div id="Topics"> |
||||
Devices and sensors |
||||
</div> |
||||
</div> |
||||
<div class="itemBarLong"> |
||||
<label for="Platforms">Platforms</label> |
||||
<div id="Platforms"> |
||||
Windows RT |
||||
</div> |
||||
</div> |
||||
<div class="itemBarLong"> |
||||
<label for="Requirements">Requirements</label> |
||||
<div id="Requirements"> |
||||
|
||||
</div> |
||||
</div> |
||||
<div class="itemBar"> |
||||
<label for="LastUpdated">Primary Language</label> |
||||
<div id="LastUpdated">en-US</div> |
||||
</div> |
||||
<div class="itemBar"> |
||||
<label for="LastUpdated">Last Updated</label> |
||||
<div id="LastUpdated">4/9/2013</div> |
||||
</div> |
||||
<div class="itemBarLong"> |
||||
<label for="License">License</label> |
||||
<div id="License"> |
||||
<a href="license.rtf">MS-LPL</a></div> |
||||
</div> |
||||
<div class="itemBar"> |
||||
<div class="viewonlinecont"> |
||||
<a data-link="online" href="http://code.msdn.microsoft.com/windowsapps/Media-Capture-Sample-adf87622">View this sample online</a> |
||||
</div> |
||||
</div> |
||||
</div> |
||||
</div> |
||||
|
||||
|
||||
<script type="text/javascript"> |
||||
function initializePage() { |
||||
var otherTabClass = 'otherTab'; |
||||
var hiddenPreClass = 'hidden'; |
||||
|
||||
var htmlDecode = function(encodedData) { |
||||
var decodedData = ""; |
||||
if (encodedData) { |
||||
var div = document.createElement('div'); |
||||
div.innerHTML = encodedData; |
||||
decodedData = div.firstChild.nodeValue.replace( /\\r\\n/ig , '\r\n'); |
||||
} |
||||
return decodedData; |
||||
}; |
||||
|
||||
Galleries.iterateElem(Galleries.findElem(null, 'div', 'scriptcode'), function (index, scriptBlock) { |
||||
var titleElem = Galleries.findElem(scriptBlock, 'div', 'title')[0]; |
||||
var labelElems = Galleries.findElem(titleElem, 'span'); |
||||
if (labelElems.length == 0) { |
||||
labelElems = titleElem; |
||||
} |
||||
var languageSpans = Galleries.findElem(scriptBlock, 'span', 'hidden'); |
||||
var pres = Galleries.findElem(scriptBlock, 'pre'); |
||||
if (languageSpans.length > 0 && pres.length > 1) { |
||||
Galleries.iterateElem(labelElems, function(index, elem) { |
||||
var codePre = pres[index]; |
||||
var labelSpan = elem; |
||||
var languageSpan = languageSpans[index]; |
||||
|
||||
elem.code = codePre.innerHTML.replace( /(\r(\n)?)|((\r)?\n)/ig , '\\r\\n'); |
||||
|
||||
codePre.className = codePre.className.replace(hiddenPreClass, ''); |
||||
|
||||
languageSpan.parentNode.removeChild(languageSpan); |
||||
}); |
||||
|
||||
pres = Galleries.findElem(scriptBlock, 'pre'); |
||||
Galleries.iterateElem(labelElems, function(index, elem) { |
||||
var codePre = pres[index]; |
||||
var labelSpan = elem; |
||||
if (index == 0) { |
||||
scriptBlock.activeTab = 0; |
||||
} |
||||
else { |
||||
labelSpan.className += otherTabClass; |
||||
codePre.className += hiddenPreClass; |
||||
} |
||||
Galleries.attachEventHandler(labelSpan, 'click', function(e) { |
||||
var activeTab = scriptBlock.activeTab; |
||||
labelElems[activeTab].className += otherTabClass; |
||||
pres[activeTab].className += hiddenPreClass; |
||||
|
||||
codePre.className = codePre.className.replace(hiddenPreClass, ''); |
||||
labelSpan.className = labelSpan.className.replace(otherTabClass, ''); |
||||
scriptBlock.activeTab = index; |
||||
}); |
||||
}); |
||||
|
||||
var preview = Galleries.findElem(scriptBlock, 'div', 'preview'); |
||||
if (preview.length == 0) { |
||||
preview.push(pres[pres.length - 1]); |
||||
} |
||||
Galleries.iterateElem(preview, function(index, elem) { |
||||
elem.parentNode.removeChild(elem); |
||||
}); |
||||
|
||||
if (window.clipboardData && clipboardData.setData) { |
||||
var copyLink = document.createElement('a'); |
||||
copyLink.href = 'javascript:void(0);'; |
||||
copyLink.className = 'copyCode'; |
||||
copyLink.innerHTML = 'Copy Code'; |
||||
Galleries.attachEventHandler(copyLink, 'click', function (e) { |
||||
clipboardData.setData("Text", htmlDecode(labelElems[scriptBlock.activeTab].code)); |
||||
return false; |
||||
}); |
||||
scriptBlock.insertBefore(copyLink, scriptBlock.childNodes[0]); |
||||
} |
||||
} |
||||
}); |
||||
} |
||||
|
||||
Galleries.onWindowLoad(function(){ |
||||
initializePage(); |
||||
}); |
||||
|
||||
</script> |
||||
<div id="longDesc"> |
||||
|
||||
<div id="mainSection"> |
||||
<p>This sample demonstrates how to use the <a href="http://msdn.microsoft.com/library/windows/apps/BR241124"> |
||||
<b>MediaCapture</b> </a>API to capture video, audio, and pictures from a capture device, such as a webcam. |
||||
</p> |
||||
<p>Specifically, this sample covers: </p> |
||||
<ul> |
||||
<li>Previewing video from a capture device, such as a webcam, connected to the computer. |
||||
</li><li>Capturing video from a capture device, such as a webcam, connected to the computer. |
||||
</li><li>Taking a picture from a capture device, such as a webcam, connected to the computer. |
||||
</li><li>Enumerating cameras connected to the computer. </li><li>Adding a video effect to a video. </li><li>Recording audio from a capture device connected to the computer. </li></ul> |
||||
<p></p> |
||||
<p>For more information on capturing video in your app, see <a href="http://msdn.microsoft.com/library/windows/apps/Hh465152"> |
||||
Quickstart: capturing a photo or video using the camera dialog</a> and <a href="http://msdn.microsoft.com/library/windows/apps/Hh452791"> |
||||
Quickstart: capturing video using the MediaCapture API</a>.</p> |
||||
<p class="note"><b>Important</b> </p> |
||||
<p class="note">This sample uses the Media Extension feature of Windows 8 to add functionality to the Microsoft Media Foundation pipeline. A Media Extension consists of a hybrid object that implements both Component Object Model (COM) and Windows Runtime |
||||
interfaces. The COM interfaces interact with the Media Foundation pipeline. The Windows Runtime interfaces activate the component and interact with the Windows Store app. |
||||
</p> |
||||
<p class="note">In most situations, it is recommended that you use Visual C++ with Component Extensions (C++/CX ) to interact with the Windows Runtime. But in the case of hybrid components that implement both COM and Windows Runtime interfaces, such as Media |
||||
Extensions, this is not possible. C++/CX can only create Windows Runtime objects. So, for hybrid objects it is recommended that you use |
||||
<a href="http://go.microsoft.com/fwlink/p/?linkid=243149">Windows Runtime C++ Template Library</a> to interact with the Windows Runtime. Be aware that Windows Runtime C++ Template Library has limited support for implementing COM interfaces.</p> |
||||
<p></p> |
||||
<p>To obtain an evaluation copy of Windows 8, go to <a href="http://go.microsoft.com/fwlink/p/?linkid=241655"> |
||||
Windows 8</a>.</p> |
||||
<p>To obtain an evaluation copy of Microsoft Visual Studio 2012, go to <a href="http://go.microsoft.com/fwlink/p/?linkid=241656"> |
||||
Visual Studio 2012</a>.</p> |
||||
<h3><a id="related_topics"></a>Related topics</h3> |
||||
<dl><dt><a href="http://go.microsoft.com/fwlink/p/?LinkID=227694">Windows 8 app samples</a> |
||||
</dt><dt><b>Roadmaps</b> </dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh465134">Adding multimedia</a> |
||||
</dt><dt><a href="http://msdn.microsoft.com/library/windows/apps/Hh465156">Capturing or rendering audio, video, and images</a> |
||||
</dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh767284">Designing UX for apps</a> |
||||
</dt><dt><a href="http://msdn.microsoft.com/library/windows/apps/BR229583">Roadmap for apps using C# and Visual Basic</a> |
||||
</dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh700360">Roadmap for apps using C++</a> |
||||
</dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh465037">Roadmap for apps using JavaScript</a> |
||||
</dt><dt><b>Tasks</b> </dt><dt><a href="http://msdn.microsoft.com/library/windows/apps/Hh465152">Quickstart: capturing a photo or video using the camera dialog</a> |
||||
</dt><dt><a href="http://msdn.microsoft.com/library/windows/apps/Hh452791">Quickstart: capturing video using the MediaCapture API</a> |
||||
</dt><dt><b>Reference</b> </dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/BR211961"><b>AddEffectAsync</b> |
||||
</a></dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/BR226592"><b>ClearEffectsAsync</b> |
||||
</a></dt><dt><a href="http://msdn.microsoft.com/library/windows/apps/BR241124"><b>MediaCapture</b> |
||||
</a></dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/BR226581"><b>MediaCaptureSettings</b> |
||||
</a></dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh701026"><b>MediaEncodingProfile</b> |
||||
</a></dt><dt><a href="http://msdn.microsoft.com/en-us/library/windows/apps/Hh700863"><b>StartRecordToStorageFileAsync</b> |
||||
</a></dt><dt><b>Windows.Media.Capture</b> </dt></dl> |
||||
<h3>Operating system requirements</h3> |
||||
<table> |
||||
<tbody> |
||||
<tr> |
||||
<th>Client</th> |
||||
<td><dt>Windows 8 </dt></td> |
||||
</tr> |
||||
<tr> |
||||
<th>Server</th> |
||||
<td><dt>Windows Server 2012 </dt></td> |
||||
</tr> |
||||
</tbody> |
||||
</table> |
||||
<h3>Build the sample</h3> |
||||
<p></p> |
||||
<ol> |
||||
<li>Start Visual Studio Express 2012 for Windows 8 and select <b>File</b> > <b> |
||||
Open</b> > <b>Project/Solution</b>. </li><li>Go to the directory in which you unzipped the sample. Go to the directory named for the sample, and double-click the Visual Studio Express 2012 for Windows 8 Solution (.sln) file. |
||||
</li><li>Press F7 or use <b>Build</b> > <b>Build Solution</b> to build the sample. </li></ol> |
||||
<p></p> |
||||
<h3>Run the sample</h3> |
||||
<p>To debug the app and then run it, press F5 or use <b>Debug</b> > <b>Start Debugging</b>. To run the app without debugging, press Ctrl+F5 or use |
||||
<b>Debug</b> > <b>Start Without Debugging</b>.</p> |
||||
</div> |
||||
|
||||
</div> |
||||
|
||||
|
||||
</div> |
||||
</body> |
||||
</html> |
@ -0,0 +1,25 @@ |
||||
{\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff2{\fonttbl{\f0\fcharset0 Times New Roman;}{\f2\fcharset0 MS Shell Dlg;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs16\f2\cf0 \cf0\ql{\f2 \line \li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\fs40\f2 {\ltrch MICROSOFT LIMITED PUBLIC LICENSE version 1.1}\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 \line {\ltrch ----------------------}\line \li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 {\ltrch This license governs use of code marked as \ldblquote sample\rdblquote or \ldblquote example\rdblquote available on this web site without a license agreement, as provided under the section above titled \ldblquote NOTICE SPECIFIC TO SOFTWARE AVAILABLE ON THIS WEB SITE.\rdblquote If you use such code (the \ldblquote software\rdblquote ), you accept this license. If you do not accept the license, do not use the software.}\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 \line \li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 {\ltrch 1. Definitions}\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 {\ltrch The terms \ldblquote reproduce,\rdblquote \ldblquote reproduction,\rdblquote \ldblquote derivative works,\rdblquote and \ldblquote distribution\rdblquote have the same meaning here as under U.S. copyright law. }\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 {\ltrch A \ldblquote contribution\rdblquote is the original software, or any additions or changes to the software.}\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 {\ltrch A \ldblquote contributor\rdblquote is any person that distributes its contribution under this license.}\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 {\ltrch \ldblquote Licensed patents\rdblquote are a contributor\rquote s patent claims that read directly on its contribution.}\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 \line \li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 {\ltrch 2. Grant of Rights}\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 {\ltrch (A) Copyright Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.}\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 {\ltrch (B) Patent Grant - Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.}\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 \line \li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 {\ltrch 3. Conditions and Limitations}\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 {\ltrch (A) No Trademark License- This license does not grant you rights to use any contributors\rquote name, logo, or trademarks.}\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 {\ltrch (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.}\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 {\ltrch (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.}\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 {\ltrch (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.}\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 {\ltrch (E) The software is licensed \ldblquote as-is.\rdblquote You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.}\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 {\ltrch (F) Platform Limitation - The licenses granted in sections 2(A) and 2(B) extend only to the software or derivative works that you create that run directly on a Microsoft Windows operating system product, Microsoft run-time technology (such as the .NET Framework or Silverlight), or Microsoft application platform (such as Microsoft Office or Microsoft Dynamics).}\li0\ri0\sa0\sb0\fi0\ql\par} |
||||
{\f2 \line \li0\ri0\sa0\sb0\fi0\ql\par} |
||||
} |
||||
} |