Publish VCC Plus OSS source distribution for 3.6.2 build 60

This commit is contained in:
Brian Holman committed 2026-11-13 00:14:03 -07:00
commit c652a5276d
1192 files changed
+272368

No files matched your search

@@ -0,0 +1,309 @@
////////////////////////////////////////////////////////////////////////////////
// Copyright 2015 by Joseph Forgione
// This file is part of VCC (Virtual Color Computer).
//
// VCC (Virtual Color Computer) is free software: you can redistribute itand/or
// modify it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// VCC (Virtual Color Computer) is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// VCC (Virtual Color Computer). If not, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////////////
#include <vcc/util/DialogOps.h>
#include <vcc/util/logger.h>
#include <vcc/util/fileutil.h>
#include <vcc/util/textutil.h>
#include <string>
#include <filesystem>
#ifndef _LEGACY_VCC
#include <shobjidl.h>
#endif
//-------------------------------------------------------------------------------------------
// FileDialog class shows a dialog for user to select a file for open or save.
//
// There is an effort to standardize VCC using slashes as directory seperators
// but GetSaveFileName() and GetOpenFileName() are old windows functions that
// do not play well with slashes so there is a bit of converting in and out;
//
// "path" refers to reverse slash path
//
//-------------------------------------------------------------------------------------------
using namespace VCC::Util;
FileDialog::FileDialog()
{
init();
}
void FileDialog::init()
{
ZeroMemory(&ofn_, sizeof(ofn_));
ofn_.lStructSize = sizeof(ofn_);
flags_ = OFN_HIDEREADONLY;
}
void FileDialog::setDefExt(const char* DefExt)
{
sDefext_.assign(DefExt ? DefExt : "");
}
void FileDialog::setInitialDir(const char* InitialDir)
{
sInitDir_.assign(InitialDir ? InitialDir : "");
}
void FileDialog::setInitialDir(const std::string& InitialDir)
{
sInitDir_ = InitialDir;
}
void FileDialog::setFilter(const char* Filter)
{
sFilter_.clear();
if (!Filter) return;
const char* p = Filter;
while (*p) p += std::strlen(p) + 1;
sFilter_.assign(Filter, p + 1 - Filter);
}
void FileDialog::setFlags(unsigned int Flags)
{
flags_ = Flags | OFN_HIDEREADONLY;
}
void FileDialog::setTitle(const char* Title)
{
sTitle_.assign(Title ? Title : "");
}
void FileDialog::setpath(const char* File)
{
sFile_.assign(File ? File : "");
}
const std::string& FileDialog::getpath() const
{
return sFile_;
}
std::string FileDialog::getdir() const
{
return GetDirectoryPart(sFile_);
}
std::string FileDialog::gettype() const
{
std::string s = sFile_;
size_t pos = s.rfind('.');
if (pos == std::string::npos || pos == s.size() - 1) return {};
return s.substr(pos + 1);
}
void FileDialog::getpath(char* PathCopy, int maxsize) const
{
if (!PathCopy) return;
strncpy(PathCopy, sFile_.c_str(), maxsize - 1);
PathCopy[maxsize - 1] = 0;
}
void FileDialog::getupath(char* PathCopy, int maxsize) const
{
if (!PathCopy) return;
strncpy(PathCopy, sFile_.c_str(), maxsize - 1);
PathCopy[maxsize - 1] = 0;
}
void FileDialog::getdir(char* Dir, int maxsize) const
{
if (!Dir) return;
std::string d = getdir();
strncpy(Dir, d.c_str(), maxsize - 1);
Dir[maxsize - 1] = 0;
}
void FileDialog::gettype(char* Type, int maxsize) const
{
if (!Type) return;
std::string t = gettype();
strncpy(Type, t.c_str(), maxsize - 1);
Type[maxsize - 1] = 0;
}
const char* FileDialog::path() const
{
return sFile_.c_str();
}
const char* FileDialog::upath() const
{
return sFile_.c_str();
}
//=============================================
// FileDialog::show calls GetOpenFileName() or GetSaveFileName()
//=============================================
bool FileDialog::show(BOOL Save, HWND Owner) {
char file[MAX_PATH];
::VCC::Util::copy_to_char(sFile_,file,sizeof(file));
::VCC::Util::RevDirSlashes(file);
ofn_.nMaxFile = sizeof(file);
ofn_.lpstrFile = file;
char idir[MAX_PATH];
::VCC::Util::copy_to_char(sInitDir_,idir,sizeof(idir));
::VCC::Util::RevDirSlashes(idir);
ofn_.lpstrInitialDir = idir;
// instance is that of the current module
ofn_.hInstance = GetModuleHandle(nullptr);
// use active window if owner is null
if (Owner != nullptr) {
ofn_.hwndOwner = Owner;
} else {
ofn_.hwndOwner = GetActiveWindow();
}
ofn_.lpstrDefExt = sDefext_.c_str();
ofn_.lpstrFilter = sFilter_.c_str();
ofn_.lpstrTitle = sTitle_.c_str();
ofn_.Flags |= flags_;
// Call Save or Open per boolean
int rc;
if (Save) {
rc = GetSaveFileName(&ofn_);
} else {
rc = GetOpenFileName(&ofn_) ;
}
// Copy file selected back
if ((rc == 1) && (*file != '\0')) {
sFile_.assign(file ? file : "");
VCC::Util::FixDirSlashes(sFile_);
return true;
};
return false;
}
//==================================================
// FileDialog::show_folder is defined if not legacy
//==================================================
#ifndef _LEGACY_VCC
bool FileDialog::show_folder(HWND Owner)
{
HRESULT hr = CoInitializeEx(nullptr,
COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
if (FAILED(hr))
return false;
IFileOpenDialog* dlg = nullptr;
hr = CoCreateInstance(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&dlg));
if (FAILED(hr)) {
CoUninitialize();
return false;
}
DWORD opts = 0;
dlg->GetOptions(&opts);
dlg->SetOptions(opts | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM);
if (!sTitle_.empty()) {
dlg->SetTitle(UTF8ToWide(sTitle_).c_str());
}
if (!sInitDir_.empty()) {
IShellItem* folder = nullptr;
std::wstring w = UTF8ToWide(sInitDir_);
RevDirSlashes(w);
if (SUCCEEDED(SHCreateItemFromParsingName(w.c_str(), nullptr,
IID_PPV_ARGS(&folder)))) {
dlg->SetFolder(folder);
folder->Release();
}
}
hr = dlg->Show(Owner);
if (hr == HRESULT_FROM_WIN32(ERROR_CANCELLED)) {
dlg->Release();
CoUninitialize();
return false;
}
if (FAILED(hr)) {
dlg->Release();
CoUninitialize();
return false;
}
IShellItem* item = nullptr;
hr = dlg->GetResult(&item);
if (SUCCEEDED(hr)) {
PWSTR pszPath = nullptr;
if (SUCCEEDED(item->GetDisplayName(SIGDN_FILESYSPATH, &pszPath))) {
sFile_ = WideToUTF8(pszPath);
CoTaskMemFree(pszPath);
}
item->Release();
}
dlg->Release();
CoUninitialize();
return !sFile_.empty();
}
#endif
//------------------------------------------------------------
// Center a dialog box in parent window
//------------------------------------------------------------
void CenterDialog(HWND hDlg)
{
RECT rPar;
GetWindowRect(GetParent(hDlg), &rPar);
RECT rDlg;
GetWindowRect(hDlg, &rDlg);
const auto x = rPar.left + (rPar.right - rPar.left - (rDlg.right - rDlg.left)) / 2;
const auto y = rPar.top + (rPar.bottom - rPar.top - (rDlg.bottom - rDlg.top)) / 2;
SetWindowPos(hDlg, nullptr, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
}
//-------------------------------------------------------------------------------------------
// CloseCartDialog should be called by cartridge DLL's when they are unloaded.
//-------------------------------------------------------------------------------------------
void CloseCartDialog(HWND hDlg)
{
// Send a close message to a cart configuration dialog if it is Enabled. If the dialog
// is disabled it is assumed that VCC must be terminated to avoid a crash. A common
// reason a configuration dialog is disabled is it has a modal dialog window open.
if (hDlg) {
if (IsWindowEnabled(hDlg)) {
SendMessage(hDlg,WM_CLOSE,0,0);
} else {
MessageBox(nullptr,"A system dialog was left open. VCC will close",
"Unload Cartridge Error",MB_ICONEXCLAMATION);
DWORD pid = GetCurrentProcessId();
HANDLE h = OpenProcess(PROCESS_TERMINATE,FALSE,pid);
TerminateProcess(h,0);
}
}
}
@@ -0,0 +1,92 @@
////////////////////////////////////////////////////////////////////////////////
// Copyright 2015 by Joseph Forgione
// This file is part of VCC (Virtual Color Computer).
//
// VCC (Virtual Color Computer) is free software: you can redistribute itand/or
// modify it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// VCC (Virtual Color Computer) is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// VCC (Virtual Color Computer). If not, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <vcc/util/fileutil.h>
#include <vcc/util/logger.h>
#include <Windows.h>
#include <string>
//#ifndef LEGACY_BUILD
#include <shobjidl.h>
//#endif
//-------------------------------------------------------------------------------------------
// CloseCartDialog closes DLL dialog or force exits Vcc if it can not be.
// It should be called by cartridge DLL's when they are unloaded.
//-------------------------------------------------------------------------------------------
void CloseCartDialog(HWND hDlg);
void CenterDialog(HWND hDlg);
//-------------------------------------------------------------------------------------------
// FileDialog wraps dialogs for users to select files.
//
// show() displays the dialog. If Save is TRUE the save dialog is shown
// otherwise the open dialog is shown. If "Owner" is NULL GetActiveWindow() is used.
// The selected filename is placed in "Path"
//
//-------------------------------------------------------------------------------------------
class FileDialog
{
public:
FileDialog();
void init();
// File selection
bool show(BOOL Save = FALSE, HWND Owner = nullptr);
#ifndef _LEGACY_VCC
// Folder selection (Win8+ only)
bool show_folder(HWND Owner = nullptr);
#endif
void setDefExt(const char* DefExt);
void setInitialDir(const char* InitialDir);
void setInitialDir(const std::string& InitialDir);
void setFilter(const char* Filter);
void setFlags(unsigned int Flags);
void setTitle(const char* Title);
void setpath(const char* File);
const std::string& getpath() const;
std::string getdir() const;
std::string gettype() const;
void getpath(char* pathCopy, int maxsize) const;
void getupath(char* pathCopy, int maxsize) const;
void getdir(char* dir, int maxsize) const;
void gettype(char* type, int maxsize) const;
template <size_t S> void getpath(char (&pathCopy)[S]) const { getpath(pathCopy, S); }
template <size_t S> void getupath(char (&pathCopy)[S]) const { getupath(pathCopy, S); }
template <size_t S> void getdir(char (&dir)[S]) const { getdir(dir, S); }
template <size_t S> void gettype(char (&type)[S]) const { gettype(type, S); }
const char* path() const;
const char* upath() const;
private:
OPENFILENAME ofn_;
std::string sFile_;
std::string sInitDir_;
std::string sTitle_;
std::string sFilter_;
std::string sDefext_;
DWORD flags_;
};
@@ -0,0 +1,130 @@
////////////////////////////////////////////////////////////////////////////////
// Copyright 2015 by Joseph Forgione
// This file is part of VCC (Virtual Color Computer).
//
// VCC (Virtual Color Computer) is free software: you can redistribute itand/or
// modify it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// VCC (Virtual Color Computer) is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// VCC (Virtual Color Computer). If not, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////////////
// TODO: FileOps should be depreciated and functions moved to fileutil.cpp
#include <Windows.h>
#include <stdio.h>
#include <stdbool.h>
#include <vcc/util/FileOps.h>
void ValidatePath(char *Path)
{
char FullExePath[MAX_PATH]="";
char TempPath[MAX_PATH]="";
GetModuleFileName(nullptr,FullExePath,MAX_PATH);
PathRemoveFileSpec(FullExePath); //Get path to executable
strcpy(TempPath,Path);
PathRemoveFileSpec(TempPath); //Get path to Incomming file
if (!strcmp(TempPath,FullExePath)) // If they match remove the Path
PathStripPath(Path);
return;
}
int CheckPath( char *Path) //Return 1 on Error
{
char TempPath[MAX_PATH]="";
HANDLE hr=nullptr;
if ((strlen(Path)==0) || (strlen(Path) > MAX_PATH))
return 1;
hr=CreateFile(Path,0,FILE_SHARE_READ,nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
if (hr==INVALID_HANDLE_VALUE) //File Doesn't exist
{
GetModuleFileName(nullptr,TempPath,MAX_PATH);
PathRemoveFileSpec(TempPath);
if ( (strlen(TempPath)) + (strlen(Path)) > MAX_PATH) //Resulting path is to large Bail.
return 1;
strcat(TempPath,Path);
hr=CreateFile(TempPath,0,FILE_SHARE_READ,nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr);
if (hr ==INVALID_HANDLE_VALUE)
return 1;
strcpy(Path,TempPath);
}
CloseHandle(hr);
return 0;
}
// These are here to remove dependance on shlwapi.dll. ASCII only
void PathStripPath ( char *TextBuffer)
{
char TempBuffer[MAX_PATH] = "";
short Index = (short)strlen(TextBuffer);
if ((Index > MAX_PATH) || (Index==0)) //Test for overflow
return;
for (; Index >= 0; Index--)
if (TextBuffer[Index] == '\\' || TextBuffer[Index] == '/')
break;
if (Index < 0) //delimiter not found
return;
strcpy(TempBuffer, &TextBuffer[Index + 1]);
strcpy(TextBuffer, TempBuffer);
}
BOOL PathRemoveFileSpec(char *Path)
{
size_t Index=strlen(Path),Lenth=Index;
if ( (Index==0) || (Index > MAX_PATH))
return false;
while ( (Index>0) && (Path[Index] != '\\') )
Index--;
while ( (Index>0) && (Path[Index] == '\\') )
Index--;
if (Index==0)
return false;
Path[Index+2]=0;
return( !(strlen(Path) == Lenth));
}
BOOL PathRemoveExtension(char *Path)
{
size_t Index=strlen(Path),Lenth=Index;
if ( (Index==0) || (Index > MAX_PATH))
return false;
while ( (Index>0) && (Path[Index--] != '.') );
Path[Index+1]=0;
return( !(strlen(Path) == Lenth));
}
char* PathFindExtension(char *Path)
{
size_t Index=strlen(Path);
if ( (Index==0) || (Index > MAX_PATH))
return(&Path[strlen(Path)+1]);
while ( (Index>0) && (Path[Index--] != '.') );
return(&Path[Index+1]);
}
BOOL FilePrintf(HANDLE hFile, const char* fmt, ...)
{
DWORD dummy;
va_list args;
char msg[512];
va_start(args, fmt);
vsnprintf(msg, 512, fmt, args);
va_end(args);
return WriteFile(hFile,msg,strlen(msg),&dummy,nullptr);
}
@@ -0,0 +1,28 @@
////////////////////////////////////////////////////////////////////////////////
// Copyright 2015 by Joseph Forgione
// This file is part of VCC (Virtual Color Computer).
//
// VCC (Virtual Color Computer) is free software: you can redistribute itand/or
// modify it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// VCC (Virtual Color Computer) is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// VCC (Virtual Color Computer). If not, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <Windows.h>
void PathStripPath(char*);
void ValidatePath(char* Path);
int CheckPath(char*);
BOOL PathRemoveFileSpec(char*);
BOOL PathRemoveExtension(char*);
char* PathFindExtension(char*);
BOOL FilePrintf(HANDLE, const char*, ...);
@@ -0,0 +1,54 @@
////////////////////////////////////////////////////////////////////////////////
// Copyright 2015 by Joseph Forgione
// This file is part of VCC (Virtual Color Computer).
//
// VCC (Virtual Color Computer) is free software: you can redistribute itand/or
// modify it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// VCC (Virtual Color Computer) is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// VCC (Virtual Color Computer). If not, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////////////
#include <vcc/util/coreutil.h>
#include <string>
#include <windows.h>
namespace VCC::Util
{
//--------------------------------------------
// Load a resource string into a utf8
//--------------------------------------------
std::string load_string(HINSTANCE instance, UINT id)
{
const wchar_t* buffer_ptr;
// Get len of string to load
const int length = LoadStringW(instance, id, reinterpret_cast<LPWSTR>(&buffer_ptr), 0);
if (length == 0)
return {};
// Copy load string to wide_str
const std::wstring wide_str(buffer_ptr, length);
// Get len of string when converted
const int utf8_len = WideCharToMultiByte(CP_UTF8, 0, wide_str.data(), wide_str.size(), nullptr, 0, nullptr, nullptr);
if (utf8_len == 0)
{
return {};
}
// Convert string from wide_str to utf8_str
std::string utf8_str(utf8_len, '\0');
WideCharToMultiByte(CP_UTF8, 0, wide_str.data(), wide_str.size(), utf8_str.data(), utf8_len, nullptr, nullptr);
return utf8_str;
}
}
@@ -0,0 +1,37 @@
////////////////////////////////////////////////////////////////////////////////
// Copyright 2015 by Joseph Forgione
// This file is part of VCC (Virtual Color Computer).
//
// VCC (Virtual Color Computer) is free software: you can redistribute itand/or
// modify it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// VCC (Virtual Color Computer) is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// VCC (Virtual Color Computer). If not, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <Windows.h>
#include <string>
namespace VCC::Util
{
//--------------------------------------------
// Load resource string into utf8 string
//--------------------------------------------
std::string load_string(HINSTANCE instance, UINT id);
//--------------------------------------------
// Compatible min function that works with legacy compilers
//--------------------------------------------
template <typename T>
inline constexpr const T& min_compat(const T& a, const T& b)
{
return (b < a) ? b : a;
}
}
@@ -0,0 +1,82 @@
////////////////////////////////////////////////////////////////////////////////
// Copyright 2015 by Joseph Forgione
// This file is part of VCC (Virtual Color Computer).
//
// VCC (Virtual Color Computer) is free software: you can redistribute itand/or
// modify it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// VCC (Virtual Color Computer) is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// VCC (Virtual Color Computer). If not, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <Windows.h>
namespace VCC::Util
{
class critical_section
{
public:
critical_section()
{
InitializeCriticalSection(&section_);
}
~critical_section()
{
DeleteCriticalSection(&section_);
}
critical_section(const critical_section&) = delete;
critical_section& operator=(const critical_section&) = delete;
void lock() const
{
EnterCriticalSection(&section_);
}
void unlock() const
{
LeaveCriticalSection(&section_);
}
private:
mutable CRITICAL_SECTION section_;
};
class section_locker
{
public:
explicit section_locker(const critical_section& section)
: section_(section)
{
section_.lock();
}
~section_locker()
{
section_.unlock();
}
section_locker& operator=(const section_locker&) = delete;
section_locker& operator=(section_locker&&) = delete;
private:
const critical_section& section_;
};
}
@@ -0,0 +1,32 @@
#include <vcc/util/fileutil.h>
#include <vcc/util/filesystem.h>
//TODO filesystem.cpp is depreciated
//TODO move this it is used only in mpi/multipak_cartridge.cpp:
namespace VCC::Util
{
std::string find_pak_module_path(std::string path)
{
if (path.empty())
{
return path;
}
auto file_handle(CreateFile(path.c_str(), 0, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr));
if (file_handle == INVALID_HANDLE_VALUE)
{
const auto application_path = ::VCC::Util::GetDirectoryPart(::VCC::Util::ModulePath(NULL));
const auto alternate_path = application_path + path;
file_handle = CreateFile(alternate_path.c_str(), 0, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (file_handle == INVALID_HANDLE_VALUE)
{
path = alternate_path;
}
}
CloseHandle(file_handle);
return path;
}
}
@@ -0,0 +1,9 @@
#pragma once
#include <string>
#include <Windows.h>
//TODO: depreciate this - it is used only in mpi/multipak_cartridge.cpp:
namespace VCC::Util
{
std::string find_pak_module_path(std::string path);
}
@@ -0,0 +1,151 @@
//#define USE_LOGGING
//======================================================================
// General purpose Host file utilities. EJ Jaquay 2026
//
// This file is part of VCC (Virtual Color Computer).
// Vcc is Copyright 2015 by Joseph Forgione
//
// VCC (Virtual Color Computer) is free software, you can redistribute
// and/or modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// VCC (Virtual Color Computer) is distributed in the hope that it will
// be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with VCC (Virtual Color Computer). If not, see
// <http://www.gnu.org/licenses/>.
//
//======================================================================
#include <string>
#include <vector>
#include <filesystem>
#include <Shlwapi.h>
#include <algorithm>
#include <cctype>
#include <vcc/util/logger.h>
#include <vcc/util/fileutil.h>
#include <vcc/util/textutil.h>
#include <Windows.h>
namespace VCC::Util
{
//----------------------------------------------------------------------
// Get most recent windows error text
//----------------------------------------------------------------------
std::string LastErrorString()
{
DWORD error_code = GetLastError();
char msg[256];
DWORD len = FormatMessageA(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
msg, sizeof(msg), nullptr
);
if (len == 0) return "Unknown error";
return std::string(msg, len);
}
// Only use this overload as argument to debug logger (DLOG)
const char* LastErrorTxt()
{
thread_local static std::string buffer;
buffer = LastErrorString();
return buffer.c_str();
}
//-------------------------------------------------------------------
// Get the file path of a loaded module
// Current exe path is returned if module_handle is null
//-------------------------------------------------------------------
std::string ModulePath(HMODULE module_handle)
{
std::string text(MAX_PATH, '\0');
for (;;) {
DWORD ret = GetModuleFileName(module_handle, &text[0], text.size());
if (ret == 0)
return {}; // error
if (ret < text.size() - 1) {
text.resize(ret);
return text;
}
// truncated grow and retry
text.resize(text.size() * 2);
}
}
//-------------------------------------------------------------------
// If file directory matches application directory strip directory
//-------------------------------------------------------------------
std::string StripModPath(const std::string file)
{
// Strip path from file if it matches the exe or dll path
auto app_dir = GetDirectoryPart(ModulePath(nullptr));
auto file_dir = GetDirectoryPart(file);
std::error_code ec;
if (std::filesystem::equivalent(app_dir, file_dir, ec)) {
return GetFileNamePart(file);
}
return file;
}
//---------------------------------------------------------------
// Fully qualify a file based on current execution directory
// Undoes the effect of StripModPath() unless path absolute
//---------------------------------------------------------------
std::string QualifyModPath(const std::string& path)
{
if (path.empty()) return {};
// convert to string and normalize slashes
std::string mod = path;
FixDirSlashes(mod);
// Quit if path is absolute
if (mod.find('/') != std::string::npos) return mod;
return GetExecutableDir() + '/' + mod;
}
//---------------------------------------------------------------
// Get Version infomation from exe or dll file
// Common keys: (these are defined in the .rc file)
// "FileVersion" Version infomation
// "FileDescription" Short description
// "Comments" Detailed description
//---------------------------------------------------------------
std::string GetVersionInfo(const char* filename, const char* key)
{
DWORD size = GetFileVersionInfoSizeA(filename, nullptr);
if (size == 0) return "";
std::vector<char> data(size);
if (!GetFileVersionInfoA(filename, 0, size, data.data())) return "";
// Get Translation table (language + codepage)
LPVOID trans = nullptr;
UINT transLen = 0;
if (!VerQueryValueA(data.data(), "\\VarFileInfo\\Translation", &trans, &transLen))
return "";
// Build the complete query for key
DWORD langCode = *(DWORD*)trans;
WORD lang = LOWORD(langCode);
WORD code = HIWORD(langCode);
char query[256];
sprintf_s(query, "\\StringFileInfo\\%04X%04X\\%s", lang, code, key);
// Query the key
LPVOID value = nullptr;
UINT valueLen = 0;
if (!VerQueryValueA(data.data(), query, &value, &valueLen)) return "";
return std::string((char*)value);
}
}
@@ -0,0 +1,188 @@
//======================================================================
// General purpose Host file utilities. EJ Jaquay 2026
//
// This file is part of VCC (Virtual Color Computer).
// Vcc is Copyright 2015 by Joseph Forgione
//
// VCC (Virtual Color Computer) is free software, you can redistribute
// and/or modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// VCC (Virtual Color Computer) is distributed in the hope that it will
// be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with VCC (Virtual Color Computer). If not, see
// <http://www.gnu.org/licenses/>.
//
//======================================================================
#pragma once
// following pragma could be avoided by adjusting project files
#pragma comment(lib, "version.lib")
#include <string>
#include <filesystem>
#include <algorithm>
#include <Windows.h>
//#include <vcc/util/textutil.h>
//=========================================================================
// Host file utilities. Most of these are general purpose
//=========================================================================
namespace VCC::Util {
// Get most recent windows error text
std::string LastErrorString();
const char* LastErrorTxt();
// Get path of loaded module or current application
std::string ModulePath(HMODULE module_handle);
// If path is in the application directory strip directory
std::string StripModPath(std::string path);
// Fully qualify a file based on execution directory
std::string QualifyModPath(const std::string& path);
// Get version information from EXE or DLL
std::string GetVersionInfo(const char* filename, const char* key);
//------------------------------------------------------------------------
// In line functions
//------------------------------------------------------------------------
// Return copy of string with spaces trimmed from end of a string
inline std::string trim_right_spaces(const std::string& s)
{
size_t end = s.find_last_not_of(' ');
if (end == std::string::npos) return {};
return s.substr(0, end + 1);
}
// Return filename part of a path
inline std::string GetFileNamePart(const std::string& input)
{
std::filesystem::path p(input);
return p.filename().string();
}
// Determine if path is a direcory
inline bool IsDirectory(const std::string& path)
{
std::error_code ec;
return std::filesystem::is_directory(path, ec) && !ec;
}
// Verify that a file can be opened for read/write
inline bool ValidateRWFile(const std::string& path)
{
HANDLE h = CreateFile
(path.c_str(), GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ, nullptr, OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL, nullptr);
if (h==INVALID_HANDLE_VALUE) return false;
CloseHandle(h);
return true;
}
// Verify that a file can be opened for read
inline bool ValidateRDFile(const std::string& path)
{
HANDLE h = CreateFile
(path.c_str(), GENERIC_READ,
FILE_SHARE_READ, nullptr, OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL, nullptr);
if (h==INVALID_HANDLE_VALUE) return false;
CloseHandle(h);
return true;
}
// Convert backslashes to slashes within string
inline void FixDirSlashes(std::string& dir)
{
if (dir.empty()) return;
std::replace(dir.begin(), dir.end(), '\\', '/');
if (dir.back() == '/') dir.pop_back();
}
// Convert backslashes to slashes within char *
inline void FixDirSlashes(char* dir)
{
if (!dir || !*dir) return;
for (char* p = dir; *p; ++p)
if (*p == '\\') *p = '/';
}
// Convert slashes to backslashes within char * (for legacy win calls)
inline void RevDirSlashes(char* dir)
{
if (!dir || !*dir) return;
for (char* p = dir; *p; ++p)
if (*p == '/') *p = '\\';
}
// Overrides for std::string and wstring
inline void RevDirSlashes(std::string& dir)
{
std::replace(dir.begin(), dir.end(), '/', '\\');
}
inline void RevDirSlashes(std::wstring& dir)
{
std::replace(dir.begin(), dir.end(), L'/', L'\\');
}
// Return copy of path with backslashes converterd
inline std::string FixDirSlashes(const std::string& dir)
{
std::string s = dir;
FixDirSlashes(s);
return s;
}
// Strip trailing backslash from directory or path
inline void StripTrailingSlash(std::string& dir)
{
if (dir.back() == '/') dir.pop_back();
}
// Return copy with trailing backslash stripped
inline std::string StripTrailingSlash(const std::string& dir)
{
std::string s = dir;
StripTrailingSlash(s);
return s;
}
// Conditionally append trailing backslash to directory
inline void AppendTrailingSlash(std::string dir)
{
if (dir.back() != '/') dir += '/';
}
// Return slash normalized directory part of a path
inline std::string GetDirectoryPart(const std::string& input)
{
std::filesystem::path p(input);
std::string out = p.parent_path().string();
FixDirSlashes(out);
return out;
}
// Return slash normalized user directory
inline std::string GetUserDir()
{
const char* p = getenv("USERPROFILE");
return p ? FixDirSlashes(std::string(p)) : std::string();
}
// Return slash normaized executable directory
inline std::string GetExecutableDir()
{
return GetDirectoryPart(ModulePath(nullptr));
}
}
@@ -0,0 +1,21 @@
////////////////////////////////////////////////////////////////////////////////
// Copyright 2015 by Joseph Forgione
// This file is part of VCC (Virtual Color Computer).
//
// VCC (Virtual Color Computer) is free software: you can redistribute itand/or
// modify it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// VCC (Virtual Color Computer) is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// VCC (Virtual Color Computer). If not, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////////////
#pragma once
constexpr auto MAX_LOADSTRING = 400u;
@@ -0,0 +1,73 @@
////////////////////////////////////////////////////////////////////////////////
// Copyright 2015 by Joseph Forgione
// This file is part of VCC (Virtual Color Computer).
//
// VCC (Virtual Color Computer) is free software: you can redistribute itand/or
// modify it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// VCC (Virtual Color Computer) is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// VCC (Virtual Color Computer). If not, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////////////
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <vcc/util/logger.h>
static HANDLE hLog_Out = nullptr;
static const auto LogFileName = "VccLog.txt";
// PrintLogC - Put a formatted debug string to the screen
void PrintLogC(const char* fmt, ...)
{
va_list args;
char msg[512];
va_start(args, fmt);
vsnprintf(msg, 512, fmt, args);
va_end(args);
// If running under a debugger use it.
if (IsDebuggerPresent()) {
OutputDebugStringA(msg);
return;
}
// If not running debugger use console
if (hLog_Out == nullptr) {
AllocConsole();
hLog_Out = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTitle("Logging Window");
if (hLog_Out == NULL || hLog_Out == INVALID_HANDLE_VALUE) {
OutputDebugStringA(msg);
return;
}
}
WriteFile(hLog_Out,msg,strlen(msg),nullptr,nullptr);
}
// PrintLogF - Put formatted string to the log file
void PrintLogF(const char* fmt, ...)
{
va_list args;
char msg[512];
va_start(args, fmt);
vsnprintf(msg, 512, fmt, args);
va_end(args);
int oflag = _O_CREAT | _O_APPEND | _O_RDWR;
int pmode = _S_IREAD | _S_IWRITE;
int flog = _open(LogFileName,oflag,pmode);
_write(flog, msg, strlen(msg));
_close(flog);
}
@@ -0,0 +1,31 @@
////////////////////////////////////////////////////////////////////////////////
// Copyright 2015 by Joseph Forgione
// This file is part of VCC (Virtual Color Computer).
//
// VCC (Virtual Color Computer) is free software: you can redistribute itand/or
// modify it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// VCC (Virtual Color Computer) is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// VCC (Virtual Color Computer). If not, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////////////
#pragma once
// Print to Console or File
void PrintLogC(const char* fmt, ...);
void PrintLogF(const char* fmt, ...);
// Debug logging if USE_LOGGING is defined
#ifdef USE_LOGGING
#define DLOG_C(...) PrintLogC(__VA_ARGS__)
#define DLOG_F(...) PrintLogF(__VA_ARGS__)
#else
#define DLOG_C(...) ((void)0)
#define DLOG_F(...) ((void)0)
#endif
@@ -0,0 +1,106 @@
//#define USE_LOGGING
////////////////////////////////////////////////////////////////////////////////
// Copyright 2015 by Joseph Forgione
// This file is part of VCC (Virtual Color Computer).
//
// VCC (Virtual Color Computer) is free software: you can redistribute itand/or
// modify it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// VCC (Virtual Color Computer) is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// VCC (Virtual Color Computer). If not, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////////////
#include <vcc/util/settings.h>
#include <vcc/util/logger.h>
#include <Windows.h>
namespace VCC::Util
{
settings::settings(path_type path)
: path_(move(path))
{}
// save string value
bool settings::write(
const std::string& section,
const std::string& key,
const std::string& value) const
{
return ::WritePrivateProfileString(
section.c_str(),
key.c_str(),
value.c_str(),
path_.c_str());
}
// save int value
bool settings::write
(const std::string& section,
const std::string& key,
int value) const
{
return ::WritePrivateProfileString(
section.c_str(),
key.c_str(),
std::to_string(value).c_str(),
path_.c_str());
}
// save bool value
bool settings::write_bool
(const std::string& section,
const std::string& key,
bool value) const
{
int ival = value ? 1 : 0;
return write(section, key, ival);
}
// get char * value
bool settings::read
(const std::string& section,
const std::string& key,
const std::string& default_value,
char* buffer,
size_t buffer_size) const
{
return ::GetPrivateProfileStringA(
section.c_str(),
key.c_str(),
default_value.c_str(),
buffer,
static_cast<DWORD>(buffer_size),
path_.c_str());
}
// get string value
std::string settings::read
(const std::string& section,
const std::string& key,
const std::string& default_value) const
{
char buffer[MAX_PATH] = {};
read(section, key, default_value, buffer, sizeof(buffer));
return std::string(buffer);
}
// get int value
int settings::read
(const std::string& section,
const std::string& key,
int default_value) const
{
return ::GetPrivateProfileInt(
section.c_str(),
key.c_str(),
default_value,
path_.c_str());
}
}
@@ -0,0 +1,97 @@
////////////////////////////////////////////////////////////////////////////////
// Copyright 2015 by Joseph Forgione
// This file is part of VCC (Virtual Color Computer).
//
// VCC (Virtual Color Computer) is free software: you can redistribute itand/or
// modify it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// VCC (Virtual Color Computer) is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// VCC (Virtual Color Computer). If not, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <string>
#include <Windows.h>
namespace VCC::Util
{
class settings
{
public:
using path_type = std::string;
public:
explicit settings(path_type path);
// write string value
bool write
(const std::string& section,
const std::string& key,
const std::string& value) const;
// write int value
bool write
(const std::string& section,
const std::string& key,
int value) const;
// write bool value
bool write_bool
(const std::string& section,
const std::string& key,
bool value) const;
// get char * value
bool read
(const std::string& section,
const std::string& key,
const std::string& default_value,
char* buffer,
size_t buffer_size) const;
// get string value
std::string read
(const std::string& section,
const std::string& key,
const std::string& default_value = {}) const;
// get int value
int read
(const std::string& section,
const std::string& key,
int default_value) const;
// delete key
bool delete_key
(const std::string& section,
const std::string& key) const
{
return ::WritePrivateProfileString
(section.c_str(), key.c_str(), NULL, path_.c_str());
}
// delete section
bool delete_section
(const std::string& section) const
{
return ::WritePrivateProfileString
(section.c_str(), NULL, NULL, path_.c_str());
}
// flush cache
bool flush () const
{
return ::WritePrivateProfileString
(NULL, NULL, NULL, path_.c_str());
}
private:
const path_type path_;
};
}
@@ -0,0 +1,122 @@
//======================================================================
// General purpose string utilities. EJ Jaquay 2026
//
// This file is part of VCC (Virtual Color Computer).
// Vcc is Copyright 2015 by Joseph Forgione
//
// VCC (Virtual Color Computer) is free software, you can redistribute
// and/or modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// VCC (Virtual Color Computer) is distributed in the hope that it will
// be useful, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with VCC (Virtual Color Computer). If not, see
// <http://www.gnu.org/licenses/>.
//
//======================================================================
#pragma once
#include <string>
#include <algorithm>
#include <Windows.h>
//=========================================================================
// Text utilities. Most of these are general purpose
//=========================================================================
namespace VCC::Util {
// Return string with case conversion
inline std::string to_lower(std::string s) {
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) {
return static_cast<char>(::tolower(c));
});
return s;
}
inline std::string to_upper(std::string s) {
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) {
return static_cast<char>(::toupper(c));
});
return s;
}
inline void make_lower(std::string& s) {
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) {
return static_cast<char>(::tolower(c));
});
}
inline void make_lower(char* s) {
if (!s) return;
for (char* p = s; *p; ++p)
*p = static_cast<char>(::tolower(static_cast<unsigned char>(*p)));
}
inline void make_upper(std::string& s) {
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) {
return static_cast<char>(::toupper(c));
});
}
inline void make_upper(char* s) {
if (!s) return;
for (char* p = s; *p; ++p)
*p = static_cast<char>(::toupper(static_cast<unsigned char>(*p)));
}
inline bool is_null_or_empty(const char* s) {
return s == nullptr || *s == '\0';
}
inline bool is_null_or_empty(const std::string& s) {
return s.empty();
}
inline void copy_to_char(const std::string& src, char* dst, size_t dst_size)
{
if (dst_size == 0) return;
const size_t n = std::min(src.size(), dst_size - 1);
memcpy(dst, src.data(), n);
dst[n] = '\0';
}
inline std::string WideToUTF8(const wchar_t* w)
{
if (!w) return {};
int len = WideCharToMultiByte(CP_UTF8, 0, w, -1, nullptr, 0, nullptr, nullptr);
if (len <= 1) return {};
std::string out(len - 1, 0);
WideCharToMultiByte(CP_UTF8, 0, w, -1, out.data(), len, nullptr, nullptr);
return out;
}
inline std::string WideToUTF8(const std::wstring& ws)
{
return WideToUTF8(ws.c_str());
}
inline std::wstring UTF8ToWide(const std::string& s)
{
if (s.empty()) return std::wstring();
int len = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, nullptr, 0);
if (len <= 1) return std::wstring();
std::wstring out(len - 1, 0);
MultiByteToWideChar(CP_UTF8, 0, s.c_str(), -1, out.data(), len);
return out;
}
}