1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
|
/**********************************************************************
Audacity: A Digital Audio Editor
Journal.cpp
Paul Licameli
*******************************************************************//*!
\namespace Journal
\brief Facilities for recording and playback of sequences of user interaction
*//*******************************************************************/
#include "Journal.h"
#include "JournalOutput.h"
#include "JournalRegistry.h"
#include <algorithm>
#include <wx/app.h>
#include <wx/filename.h>
#include <wx/ffile.h>
#include <string>
#include <string_view>
#include "MemoryX.h"
#include "Prefs.h"
#include "FileNames.h"
namespace Journal {
namespace {
wxString sFileNameIn;
wxTextFile sFileIn;
wxString sLine;
// Invariant: the input file has not been opened, or else sLineNumber counts
// the number of lines consumed by the tokenizer
int sLineNumber = -1;
BoolSetting JournalEnabled{ L"/Journal/Enabled", false };
class JournalLogger final
{
public:
JournalLogger()
{
wxFileName logFile(FileNames::DataDir(), L"journallog.txt");
mLogFile.Open(logFile.GetFullPath(wxPATH_NATIVE), L"w");
}
void WriteString(std::string_view str)
{
mLogFile.Write(str.data(), str.size());
}
void FinalizeMessge()
{
mLogFile.Write("\n");
mLogFile.Flush();
}
private:
wxFFile mLogFile;
};
JournalLogger& GetLogger()
{
static JournalLogger logger;
return logger;
}
std::string ToString(const wxString& str)
{
return str.ToStdString();
}
template<typename T>
std::string ToString(const T& arg)
{
return std::to_string(arg);
}
template<typename... Args>
void Log( std::string_view message, const Args&... args )
{
if (message.empty())
return;
constexpr auto n = sizeof...(Args);
std::string strings[n];
std::size_t i = 0;
((strings[i++] = ToString(args)), ...);
i = 0;
auto& logger = GetLogger();
while (!message.empty())
{
const auto placeholderPos = message.find("{}");
if (placeholderPos == std::string_view::npos || i == n)
{
logger.WriteString(message);
break;
}
std::string_view arg = strings[i++];
logger.WriteString(message.substr(0, placeholderPos));
logger.WriteString(arg);
message = message.substr(placeholderPos + 2);
}
logger.FinalizeMessge();
}
inline void NextIn()
{
if ( !sFileIn.Eof() ) {
sLine = sFileIn.GetNextLine();
++sLineNumber;
Log("Journal: line {} is '{}'", sLineNumber, sLine);
}
}
wxArrayStringEx PeekTokens()
{
wxArrayStringEx tokens;
if ( Journal::IsReplaying() )
for ( ; !sFileIn.Eof(); NextIn() ) {
if ( sLine.StartsWith( CommentCharacter ) )
continue;
tokens = wxSplit( sLine, SeparatorCharacter, EscapeCharacter );
if ( tokens.empty() )
// Ignore blank lines
continue;
break;
}
return tokens;
}
constexpr auto VersionToken = wxT("Version");
// Numbers identifying the journal format version
int journalVersionNumbers[] = {
1
};
wxString VersionString()
{
wxString result;
for ( auto number : journalVersionNumbers ) {
auto str = wxString::Format( "%d", number );
result += ( result.empty() ? str : ( '.' + str ) );
}
return result;
}
//! True if value is an acceptable journal version number to be rerun
bool VersionCheck( const wxString &value )
{
auto strings = wxSplit( value, '.' );
std::vector<int> numbers;
for ( auto &string : strings ) {
long value;
if ( !string.ToCLong( &value ) )
return false;
numbers.push_back( value );
}
// OK if the static version number is not less than the given value
// Maybe in the future there will be a compatibility break
return !std::lexicographical_compare(
std::begin( journalVersionNumbers ), std::end( journalVersionNumbers ),
numbers.begin(), numbers.end() );
}
}
SyncException::SyncException(const wxString& string)
{
// If the exception is ever constructed, cause nonzero program exit code
SetError();
Log("Journal sync failed: {}", string);
}
SyncException::~SyncException() {}
void SyncException::DelayedHandlerAction()
{
// Simulate the application Exit menu item
wxCommandEvent evt{ wxEVT_MENU, wxID_EXIT };
wxTheApp->AddPendingEvent( evt );
}
bool RecordEnabled()
{
return JournalEnabled.Read();
}
bool SetRecordEnabled(bool value)
{
auto result = JournalEnabled.Write(value);
gPrefs->Flush();
return result;
}
bool IsReplaying()
{
return sFileIn.IsOpened();
}
void SetInputFileName(const wxString &path)
{
sFileNameIn = path;
}
bool Begin( const FilePath &dataDir )
{
if ( !GetError() && !sFileNameIn.empty() ) {
wxFileName fName{ sFileNameIn };
fName.MakeAbsolute( dataDir );
const auto path = fName.GetFullPath();
sFileIn.Open( path );
if (!sFileIn.IsOpened())
{
Log("Journal: failed to open journal file \"{}\"", path);
SetError();
}
else {
sLine = sFileIn.GetFirstLine();
sLineNumber = 0;
auto tokens = PeekTokens();
NextIn();
if (!(tokens.size() == 2 && tokens[0] == VersionToken &&
VersionCheck(tokens[1])))
{
Log("Journal: invalid journal version: \"{}\"", tokens[1]);
SetError();
}
}
}
if ( !GetError() && RecordEnabled() ) {
wxFileName fName{ dataDir, "journal", "txt" };
const auto path = fName.GetFullPath();
if ( !OpenOut( path ) )
SetError();
else {
// Generate a header
Comment( wxString::Format(
wxT("Journal recorded by %s on %s")
, wxGetUserName()
, wxDateTime::Now().Format()
) );
Output({ VersionToken, VersionString() });
}
}
// Call other registered initialization steps
for (auto &initializer : GetInitializers()) {
if (initializer && !initializer()) {
SetError();
break;
}
}
return !GetError();
}
wxArrayStringEx GetTokens()
{
auto result = PeekTokens();
if ( !result.empty() ) {
NextIn();
return result;
}
throw SyncException("unexpected end of stream");
}
bool Dispatch()
{
if ( GetError() )
// Don't repeatedly indicate error
// Do nothing
return false;
if ( !IsReplaying() )
return false;
// This will throw if no lines remain. A proper journal should exit the
// program before that happens.
auto words = GetTokens();
// Lookup dispatch function by the first field of the line
auto &table = GetDictionary();
auto &name = words[0];
auto iter = table.find( name );
if (iter == table.end())
throw SyncException(
wxString::Format("unknown command: %s", name.ToStdString().c_str()));
// Pass all the fields including the command name to the function
if (!iter->second(words))
throw SyncException(wxString::Format(
"command '%s' has failed", wxJoin(words, ',').ToStdString().c_str()));
return true;
}
void Sync( const wxString &string )
{
if ( IsRecording() || IsReplaying() ) {
if ( IsRecording() )
Output( string );
if ( IsReplaying() ) {
if (sFileIn.Eof() || sLine != string)
{
throw SyncException(wxString::Format(
"sync failed. Expected '%s', got '%s'",
string.ToStdString().c_str(), sLine.ToStdString().c_str()));
}
NextIn();
}
}
}
void Sync( const wxArrayString &strings )
{
if ( IsRecording() || IsReplaying() ) {
auto string = ::wxJoin( strings, SeparatorCharacter, EscapeCharacter );
Sync( string );
}
}
void Sync( std::initializer_list< const wxString > strings )
{
return Sync( wxArrayStringEx( strings ) );
}
int IfNotPlaying(
const wxString &string, const InteractiveAction &action )
{
// Special journal word
Sync(string);
// Then read or write the return value on another journal line
if ( IsReplaying() ) {
auto tokens = GetTokens();
if ( tokens.size() == 1 ) {
try {
std::wstring str{ tokens[0].wc_str() };
size_t length = 0;
auto result = std::stoi(str, &length);
if (length == str.length()) {
if (IsRecording())
Journal::Output( std::to_wstring(result) );
return result;
}
}
catch ( const std::exception& ) {}
}
throw SyncException(wxString::Format(
"unexpected tokens: %s", wxJoin(tokens, ',').ToStdString().c_str()));
}
else {
auto result = action ? action() : 0;
if ( IsRecording() )
Output( std::to_wstring( result ) );
return result;
}
}
int GetExitCode()
{
// Unconsumed commands remaining in the input file is also an error condition.
if( !GetError() && !PeekTokens().empty() ) {
NextIn();
SetError();
}
if ( GetError() ) {
// Return nonzero
// Returning the (1-based) line number at which the script failed is a
// simple way to communicate that information to the test driver script.
return sLineNumber ? sLineNumber : -1;
}
// Return zero to mean all is well, the convention for command-line tools
return 0;
}
}
|