Skip to content

Commit

Permalink
Reference commit
Browse files Browse the repository at this point in the history
  • Loading branch information
zadjii-msft committed Mar 13, 2023
1 parent 22c94bf commit 455407c
Show file tree
Hide file tree
Showing 3 changed files with 141 additions and 2 deletions.
5 changes: 5 additions & 0 deletions src/tools/scratch/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
## Narrator Buddy

This is a sample of how we might implement Narrator Buddy. This was an internal tool for taking what narrator would read aloud, and logging it to the console.

Currently this builds as a scratch project in the Terminal solution. It's provided as a reference implementation for how a real narrator buddy might be implemented in the future.
2 changes: 2 additions & 0 deletions src/tools/scratch/Scratch.vcxproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<ConfigurationType>Application</ConfigurationType>
</PropertyGroup>
<Import Project="..\..\common.build.pre.props" />
<Import Project="..\..\common.nugetversions.props" />
<ItemGroup>
<ClCompile Include="main.cpp" />
</ItemGroup>
Expand All @@ -32,4 +33,5 @@
<!-- Careful reordering these. Some default props (contained in these files) are order sensitive. -->
<Import Project="..\..\common.build.post.props" />
<Import Project="..\..\common.build.tests.props" />
<Import Project="..\..\common.nugetversions.targets" />
</Project>
136 changes: 134 additions & 2 deletions src/tools/scratch/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,141 @@
// Licensed under the MIT license.

#include <windows.h>
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <thread>
#include <sstream>

// This wmain exists for help in writing scratch programs while debugging.
int __cdecl wmain(int /*argc*/, WCHAR* /*argv[]*/)
#include <wil\result.h>
#include <wil\resource.h>
#include <wil\com.h>

#include <evntcons.h>
#include <evntrace.h>

namespace
{
wil::unique_event g_stopEvent{ wil::EventOptions::None };

} // namespace anonymous

void WINAPI ProcessEtwEvent(_In_ PEVENT_RECORD rawEvent)
{
// This is the task id from srh.man (with the same name).
constexpr auto InitiateSpeaking = 5;

auto data = rawEvent->UserData;
auto dataLen = rawEvent->UserDataLength;
auto processId = rawEvent->EventHeader.ProcessId;
auto task = rawEvent->EventHeader.EventDescriptor.Task;

if (task == InitiateSpeaking)
{
// The payload first has an int32 representing the channel we're writing to. This is basically always writing to the
// default channel, so just skip over those bytes... the rest is the string payload we want to speak,
// as a null terminated string.
if (dataLen <= 4)
{
return;
}

const auto stringPayloadSize = (dataLen - 4) / sizeof(wchar_t);
// We don't need the null terminator, because wstring intends to handle that on its own.
const auto stringLen = stringPayloadSize - 1;
const auto payload = std::wstring(reinterpret_cast<wchar_t*>(static_cast<char*>(data) + 4), stringLen);

wprintf(L"[Narrator pid=%d]: %s\n", processId, payload.c_str());
fflush(stdout);

if (payload == L"Exiting Narrator")
{
g_stopEvent.SetEvent();
}
}
}

int __cdecl wmain(int argc, wchar_t* argv[])
{
const bool runForever = (argc == 2) &&
std::wstring{ argv[1] } == L"-forever";

GUID sessionGuid;
FAIL_FAST_IF_FAILED(::CoCreateGuid(&sessionGuid));

std::array<wchar_t, 64> traceSessionName{};
FAIL_FAST_IF_FAILED(StringCchPrintf(traceSessionName.data(), static_cast<DWORD>(traceSessionName.size()), L"NarratorTraceSession_%d", ::GetCurrentProcessId()));

unsigned int traceSessionNameBytes = static_cast<unsigned int>((wcslen(traceSessionName.data()) + 1) * sizeof(wchar_t));

// Now, to get tracing. Most settings below are defaults from MSDN, except where noted.
// First, set up a session (StartTrace) - which requires a PROPERTIES struct. This has to have
// the session name after it in the same block of memory...
const unsigned int propertiesByteSize = sizeof(EVENT_TRACE_PROPERTIES) + traceSessionNameBytes;
std::vector<char> eventTracePropertiesBuffer(propertiesByteSize);
auto properties = reinterpret_cast<EVENT_TRACE_PROPERTIES*>(eventTracePropertiesBuffer.data());

// Set up properties struct for a real-time session...
properties->Wnode.BufferSize = propertiesByteSize;
properties->Wnode.Guid = sessionGuid;
properties->Wnode.ClientContext = 1;
properties->Wnode.Flags = WNODE_FLAG_TRACED_GUID;
properties->LogFileMode = EVENT_TRACE_REAL_TIME_MODE | EVENT_TRACE_USE_PAGED_MEMORY;
properties->LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES);
properties->FlushTimer = 1;
// Finally, copy the session name...
memcpy(properties + 1, traceSessionName.data(), traceSessionNameBytes);

std::thread traceThread;
auto joinTraceThread = wil::scope_exit([&]() {
if (traceThread.joinable())
{
traceThread.join();
}
});

TRACEHANDLE session{};
const auto rc = ::StartTrace(&session, traceSessionName.data(), properties);
FAIL_FAST_IF(rc != ERROR_SUCCESS);
auto stopTrace = wil::scope_exit([&]() {
EVENT_TRACE_PROPERTIES properties{};
properties.Wnode.BufferSize = sizeof(properties);
properties.Wnode.Guid = sessionGuid;
properties.Wnode.Flags = WNODE_FLAG_TRACED_GUID;

::ControlTrace(session, nullptr, &properties, EVENT_TRACE_CONTROL_STOP);
});

constexpr GUID narratorProviderGuid = { 0x835b79e2, 0xe76a, 0x44c4, 0x98, 0x85, 0x26, 0xad, 0x12, 0x2d, 0x3b, 0x4d };
FAIL_FAST_IF(ERROR_SUCCESS != ::EnableTrace(TRUE /* enable */, 0 /* enableFlag */, TRACE_LEVEL_VERBOSE, &narratorProviderGuid, session));
auto disableTrace = wil::scope_exit([&]() {
::EnableTrace(FALSE /* enable */, 0 /* enableFlag */, TRACE_LEVEL_VERBOSE, &narratorProviderGuid, session);
});

// Finally, start listening (OpenTrace/ProcessTrace/CloseTrace)...
EVENT_TRACE_LOGFILE trace{};
trace.LoggerName = traceSessionName.data();
trace.ProcessTraceMode = PROCESS_TRACE_MODE_EVENT_RECORD | PROCESS_TRACE_MODE_REAL_TIME;
trace.EventRecordCallback = ProcessEtwEvent;

using unique_tracehandle = wil::unique_any<TRACEHANDLE, decltype(::CloseTrace), ::CloseTrace>;
unique_tracehandle traceHandle{ ::OpenTrace(&trace) };

// Since the actual call to ProcessTrace blocks while it's working,
// we spin up a separate thread to do that.
traceThread = std::thread([traceHandle(std::move(traceHandle))]() mutable {
::ProcessTrace(traceHandle.addressof(), 1 /* handleCount */, nullptr /* startTime */, nullptr /* endTime */);
});

if (runForever)
{
::Sleep(INFINITE);
}
else
{
g_stopEvent.wait(INFINITE);
}

return 0;
}

1 comment on commit 455407c

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@check-spelling-bot Report

🔴 Please review

See the 📜action log for details.

Unrecognized words (6)

evntcons
evntrace
PEVENT
srh
tracehandle
wnode

Previously acknowledged words that are now absent CLA cpprest demoable DUMMYUNIONNAME everytime Hirots inthread ntsubauth NTWIN OPENIF OPENLINK PCLIENT PCOBJECT PCUNICODE PNTSTATUS pplx PPROCESS PUNICODE reingest unmark websockets :arrow_right:
To accept ✔️ these unrecognized words as correct and remove the previously acknowledged and now absent words, run the following commands

... in a clone of the git@github.com:microsoft/terminal.git repository
on the dev/migrie/f/narrator-buddy branch (ℹ️ how do I use this?):

curl -s -S -L 'https://github.com/raw/check-spelling/check-spelling/v0.0.21/apply.pl' |
perl - 'https://github.com/microsoft/terminal/actions/runs/4408337905/attempts/1'
✏️ Contributor please read this

By default the command suggestion will generate a file named based on your commit. That's generally ok as long as you add the file to your commit. Someone can reorganize it later.

⚠️ The command is written for posix shells. If it doesn't work for you, you can manually add (one word per line) / remove items to expect.txt and the excludes.txt files.

If the listed items are:

  • ... misspelled, then please correct them instead of using the command.
  • ... names, please add them to .github/actions/spelling/allow/names.txt.
  • ... APIs, you can add them to a file in .github/actions/spelling/allow/.
  • ... just things you're using, please add them to an appropriate file in .github/actions/spelling/expect/.
  • ... tokens you only need in one place and shouldn't generally be used, you can add an item in an appropriate file in .github/actions/spelling/patterns/.

See the README.md in each directory for more information.

🔬 You can test your commits without appending to a PR by creating a new branch with that extra change and pushing it to your fork. The check-spelling action will run in response to your push -- it doesn't require an open pull request. By using such a branch, you can limit the number of typos your peers see you make. 😉

If the flagged items are 🤯 false positives

If items relate to a ...

  • binary file (or some other file you wouldn't want to check at all).

    Please add a file path to the excludes.txt file matching the containing file.

    File paths are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your files.

    ^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude README.md (on whichever branch you're using).

  • well-formed pattern.

    If you can write a pattern that would match it,
    try adding it to the patterns.txt file.

    Patterns are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your lines.

    Note that patterns can't match multiline strings.

Please sign in to comment.