Skip to content

Commit 8ec466e

Browse files
authored
Visual Studio version: -pvs -t2026 | -t2022 | -t2019, GUI version dropdown (#704)
The platform is always vs, only the base template changes (templates/vs, vs2019, vs2026). Addon libs in lib/vs were lost when vs2026 / vs2019 were their own platform. An existing project keeps its version on update, the old -pvs2026 / -pvs2019 still work. Replaces #647. GUI: Visual Studio version dropdown, defaults to the newest installed; Open in IDE finds every installed version.
1 parent 3ca7f70 commit 8ec466e

16 files changed

Lines changed: 212 additions & 17 deletions

File tree

‎commandLine/src/main.cpp‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ constexpr option::Descriptor usage[] = {
5252
{ ADDONS, 0, "a", "addons", option::Arg::Optional, " --addons, -a \taddon list (such as ofxOpenCv, ofxGui, ofxXmlSettings)" },
5353
{ OFPATH, 0, "o", "ofPath", option::Arg::Optional, " --ofPath, -o \tpath to openframeworks (relative or absolute). This *must* be set, or you can also alternatively use an environment variable PG_OF_PATH and if this isn't set, it will use that value instead" },
5454
{ VERBOSE, 0, "v", "verbose", option::Arg::None, " --verbose, -v \trun verbose" },
55-
{ TEMPLATE, 0, "t", "template", option::Arg::Optional, " --template, -t \tproject template" },
55+
{ TEMPLATE, 0, "t", "template", option::Arg::Optional, " --template, -t \tproject template, or the Visual Studio version for -pvs: 2026 | 2022 (default) | 2019 (such as -pvs -t2026). An existing project keeps its version" },
5656
{ DRYRUN, 0, "d", "dryrun", option::Arg::None, " --dryrun, -d \tdry run, don't change files" },
5757
{ SRCEXTERNAL, 0, "s", "source", option::Arg::Optional, " --source, -s \trelative or absolute path to source or include folders external to the project (such as ../../../../common_utils/" },
5858
{ VERSION, 0, "w", "version", option::Arg::None, " --version, -w \treturn the current version" },
@@ -115,6 +115,7 @@ string appBundleId; // empty keeps the project's value
115115
string ofPathEnv;
116116
string templateName;
117117
string msys2Env = "ucrt64";
118+
string vsVersion; // from -t2026 etc, empty keeps the project's
118119

119120
bool busingEnvVar;
120121
bool bVerbose;
@@ -283,6 +284,7 @@ void updateProject(const fs::path & path, const string & target, bool bConsiderP
283284
if (!bDryRun) {
284285
auto project = getTargetProject(target);
285286
project->setMsys2Environment(msys2Env);
287+
project->setVsVersion(vsVersion);
286288
project->setEmscriptenWasm(emscriptenWasm);
287289
project->setAppVersion(appVersion, appBuild);
288290
project->setAppBundleId(appBundleId);
@@ -627,6 +629,44 @@ int pgMain(int argc, char ** argv) {
627629
}
628630
}
629631

632+
// Visual Studio version: -pvs -t2026. The platform is always vs, only the base template changes.
633+
// -tvs2026 and the old -pvs2026 / -pvs2019 mean the same
634+
{
635+
auto vsVersionFrom = [](string name) {
636+
if (name.rfind("vs", 0) == 0) name = name.substr(2);
637+
return (name == "2019" || name == "2022" || name == "2026") ? name : string();
638+
};
639+
vector<string> platformNames;
640+
for (auto & t : targets) {
641+
string platform = t;
642+
if (t.rfind("vs", 0) == 0 && !vsVersionFrom(t).empty()) {
643+
vsVersion = vsVersionFrom(t);
644+
platform = "vs";
645+
}
646+
if (std::find(platformNames.begin(), platformNames.end(), platform) == platformNames.end()) {
647+
platformNames.emplace_back(platform);
648+
}
649+
}
650+
targets = platformNames;
651+
652+
vector<string> templateNames;
653+
for (auto & name : ofSplitString(templateName, ",", true, true)) {
654+
if (vsVersionFrom(name).empty()) {
655+
templateNames.emplace_back(name);
656+
} else {
657+
vsVersion = vsVersionFrom(name); // -t wins over -p
658+
}
659+
}
660+
templateName = ofJoinString(templateNames, ",");
661+
662+
if (!vsVersion.empty()) {
663+
ofLogNotice() << "{ \"VisualStudioVersion\": \"" << vsVersion << "\" }";
664+
if (std::find(targets.begin(), targets.end(), "vs") == targets.end()) {
665+
ofLogWarning() << "Visual Studio version " << vsVersion << " has no effect without the vs platform";
666+
}
667+
}
668+
}
669+
630670
// getTargetProject has no project for these, which crashed (-p bogus, or no host platform)
631671
for (auto & t : targets) {
632672
if (!getTargetProject(t)) {
@@ -894,6 +934,7 @@ int pgMain(int argc, char ** argv) {
894934
ofLogNotice() << "project path is: [" << projectPath << "]";
895935
auto project = getTargetProject(t);
896936
project->setMsys2Environment(msys2Env);
937+
project->setVsVersion(vsVersion);
897938
project->setEmscriptenWasm(emscriptenWasm);
898939
project->setAppVersion(appVersion, appBuild);
899940
project->setAppBundleId(appBundleId);

‎commandLine/src/projects/baseProject.cpp‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,14 @@ baseProject::baseProject(const string & _target) : target(_target) {
2626
fs::path baseProject::getPlatformTemplateDir() {
2727
// always the platform's own base template - extra templates are overlaid later via recursiveTemplateCopy (#8479)
2828
string folder { target };
29+
// Visual Studio 2022 is templates/vs, the other versions have their own template (toolset and .sln version)
30+
if (target == "vs" && (vsVersion == "2019" || vsVersion == "2026")) {
31+
fs::path versioned { getOFRoot() / templatesFolder / ("vs" + vsVersion) };
32+
if (fs::exists(versioned)) {
33+
return fs::weakly_canonical(versioned);
34+
}
35+
ofLogWarning() << "no scripts/templates/vs" << vsVersion << " in this openFrameworks, using the Visual Studio 2022 template";
36+
}
2937
if ( target == "msys2"
3038
|| target == "linux"
3139
|| target == "linux64"
@@ -112,6 +120,22 @@ vector<baseProject::Template> baseProject::listAvailableTemplates(string target)
112120
return templates;
113121
}
114122

123+
// Visual Studio version of an existing project from its toolset. An update recopies the project files
124+
// from the template, so without this a 2026 project would silently go back to 2022
125+
static std::string readVsVersion(const fs::path & path) {
126+
std::error_code ec;
127+
auto folder = fs::weakly_canonical(fs::current_path() / path, ec);
128+
if (ec) return {};
129+
auto project = folder / (folder.filename().string() + ".vcxproj");
130+
if (!fs::exists(project, ec)) return {};
131+
for (auto & line : fileToStrings(project)) {
132+
if (line.find("<PlatformToolset>v142") != std::string::npos) return "2019";
133+
if (line.find("<PlatformToolset>v143") != std::string::npos) return "2022";
134+
if (line.find("<PlatformToolset>v145") != std::string::npos) return "2026";
135+
}
136+
return {};
137+
}
138+
115139
// PROJECT_EMSCRIPTEN_WASM from config.make; the old EMSCRIPTEN_MEMORY64=1 also means 64
116140
static std::string readEmscriptenWasm(const fs::path & configMake) {
117141
std::string bits;
@@ -324,6 +348,9 @@ bool baseProject::create(const fs::path & _path, string templateName){
324348

325349
addons.clear();
326350
extSrcPaths.clear();
351+
if (target == "vs" && vsVersion.empty()) {
352+
vsVersion = readVsVersion(path);
353+
}
327354
auto pathTemplate = getPlatformTemplateDir();
328355
if (fs::exists(pathTemplate)) {
329356
templatePath = normalizePath(pathTemplate);

‎commandLine/src/projects/baseProject.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,8 @@ class baseProject {
118118
// MSYS2 environment (ucrt64 | mingw64 | clang64) - only meaningful for VSCodeProject,
119119
// a no-op everywhere else so callers don't need to know which target this applies to
120120
virtual void setMsys2Environment(const std::string & env) {}
121+
// Visual Studio version (-t2026 / -t2022 / -t2019): the platform stays vs, only the base template changes; empty keeps the project's version
122+
void setVsVersion(const std::string & version) { vsVersion = version; }
121123
// emscripten wasm32 / wasm64 (-W/--emscripten-wasm), written to config.make PROJECT_EMSCRIPTEN_WASM; empty keeps the project's value
122124
void setEmscriptenWasm(const std::string & bits) { emscriptenWasmOption = bits; }
123125
void setAppVersion(const std::string & version, const std::string & build) { appVersionOption = version; appBuildOption = build; }
@@ -200,6 +202,7 @@ class baseProject {
200202
std::vector<std::string> systemFrameworksOption, systemLibsOption; // from the CLI
201203
bool systemFrameworksPassed = false, systemLibsPassed = false; // false = keep the project's
202204
std::string emscriptenWasmOption; // from the CLI, empty = keep
205+
std::string vsVersion; // 2026 | 2022 | 2019, empty = the project's, or 2022 for a new project
203206
std::string emscriptenWasm; // value for this project: "", "32" or "64"
204207
void saveCMakeLists();
205208
void saveAppVersionFiles();

‎frontend/app.js‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,8 @@ ipcRenderer.on('setup', (event, arg) => {
171171
// this is called from main when defaults are loaded in:
172172
ipcRenderer.on('setDefaults', (event, arg) => {
173173
defaultSettings = arg;
174+
$('#vsVersionDropdown').dropdown();
175+
$('#vsVersionDropdown').dropdown('set exactly', arg.defaultVsVersion || '2022');
174176
setOFPath(defaultSettings.defaultOfPath);
175177
$("#emsdkPath").val(defaultSettings.emsdkPath || '');
176178
enableAdvancedMode(defaultSettings.advancedMode);
@@ -248,6 +250,11 @@ ipcRenderer.on('setEmscriptenWasm', (event, bits) => {
248250
$('#wasmNote').toggle(bits === '64');
249251
});
250252

253+
// an existing project's Visual Studio version, it stays on that version unless another one is picked
254+
ipcRenderer.on('setVsVersion', (event, version) => {
255+
$('#vsVersionDropdown').dropdown('set exactly', version);
256+
});
257+
251258
ipcRenderer.on('importProjectSettings', (event, settings) => {
252259
$("#projectPath").val(settings.projectPath);
253260
$("#projectName").val(settings.projectName).trigger('change'); // change triggers addon scanning
@@ -1282,7 +1289,8 @@ function generate() {
12821289
projectPath: $("#projectPath").val(),
12831290
sourcePath: srcExtraList,
12841291
platformList: platformValueArray,
1285-
templateList: templateValueArray,
1292+
// -pvs -t2026: the Visual Studio version goes with the templates
1293+
templateList: $('#vsVersionField').css('display') !== 'none' ? [...templateValueArray, $('#vsVersionDropdown').dropdown('get value')] : templateValueArray,
12861294
addonList: addonValueArray, //$("#addonsDropdown").val();
12871295
ofPath: $("#ofPath").val(),
12881296
verbose: bVerbose,
@@ -1505,6 +1513,7 @@ function updateRendererFieldVisibility() {
15051513
if (gl !== 'default' && parseFloat(gl) > maxGL) $('#glDropdown').dropdown('set selected', 'default');
15061514

15071515
$('#msys2EnvField').toggle(selectedPlatforms.some((p) => ['vscode', 'msys2'].includes(p)));
1516+
$('#vsVersionField').toggle(vs);
15081517
}
15091518

15101519
//----------------------------------------

‎frontend/index.html‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,19 @@
242242
</div>
243243
<div id="test"></div>
244244
</div>
245+
<div class="field" id="vsVersionField" style="display: none">
246+
<label data-i18n="field.vsVersion">Visual Studio version:</label>
247+
<div class="ui selection dropdown" id="vsVersionDropdown">
248+
<input type="hidden" id="vsVersionValue" value="2022">
249+
<i class="dropdown icon"></i>
250+
<div class="text">2022</div>
251+
<div class="menu">
252+
<div class="item" data-value="2026">2026</div>
253+
<div class="item" data-value="2022">2022</div>
254+
<div class="item" data-value="2019">2019</div>
255+
</div>
256+
</div>
257+
</div>
245258
<div class="field" id="rendererField" style="display: none">
246259
<label>Renderer:</label>
247260
<div class="ui selection dropdown" id="rendererDropdown">

‎frontend/index.js‎

Lines changed: 59 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ const templateSettings = {
5656
emsdkPath: "",
5757
advancedMode: false,
5858
defaultPlatform: '',
59+
defaultVsVersion: '',
5960
showConsole: false,
6061
detachConsole: false,
6162
showDeveloperTools: false,
@@ -284,7 +285,6 @@ function getDefaultTemplateForPlatform(platformId) {
284285
"linuxaarch64": "Linux arm64 (VS Code/Make)",
285286
"vscode": "VS Code",
286287
"emscripten": "Emscripten (Web) (Make)",
287-
"vs2019": "Windows (Visual Studio 2019)",
288288
};
289289

290290
return defaultTemplates[platformId] || "Unknown Template";
@@ -340,6 +340,13 @@ try {
340340
};
341341
}
342342

343+
// vs2019 / vs2026 are not platforms: the platform is vs, the version is its own setting
344+
const savedVsPlatform = /^vs(\d{4})$/.exec(settings.defaultPlatform || '');
345+
if (savedVsPlatform) {
346+
settings.defaultPlatform = 'vs';
347+
settings.defaultVsVersion = savedVsPlatform[1];
348+
}
349+
343350
for(const key in templateSettings) {
344351
if(!settings.hasOwnProperty(key)) {
345352
settings[key] = templateSettings[key];
@@ -471,8 +478,6 @@ const templates = {
471478
"tvOS": "Apple tvOS template",
472479
"unittest": "Unit test no window application",
473480
"vscode": "Visual Studio Code",
474-
"vs2019": "Visual Studio 2019",
475-
476481
};
477482

478483
let defaultOfPath = settings["defaultOfPath"];
@@ -622,10 +627,13 @@ function toLetters(num) {
622627
//-------------------------------------------------------- window
623628
// This method will be called when Electron has finished
624629
// initialization and is ready to create browser windows.
625-
app.on('ready', () => {
630+
app.on('ready', async () => {
626631
if (needsLanguageDetection) {
627632
settings.language = matchOSLocale(app.getLocale());
628633
}
634+
if (hostplatform === 'windows' && !settings.defaultVsVersion) {
635+
settings.defaultVsVersion = await detectVsVersion();
636+
}
629637

630638
// Create the browser window.
631639
mainWindow = new BrowserWindow({
@@ -837,6 +845,8 @@ function refreshPlatformList(event, ofPathValue) {
837845
// check all folder name under /scripts/templates
838846
for (const id in folders) {
839847
const key = folders[id];
848+
// vs2019 / vs2026: Visual Studio versions, picked in their own dropdown
849+
if (/^vs\d{4}$/.test(key)) continue;
840850
if (platforms[key]) {
841851
// this folder is for platform
842852
console.log("Found platform, key " + key + " has value " + platforms[key]);
@@ -959,6 +969,11 @@ ipcMain.on('isOFProjectFolder', (event, project) => {
959969
} = project;
960970
const folder = path.join(projectPath, projectName);
961971

972+
const projectVsVersion = readProjectVsVersion(folder, projectName);
973+
if (projectVsVersion) {
974+
event.sender.send('setVsVersion', projectVsVersion);
975+
}
976+
962977
try {
963978
const tmpFiles = fs.readdirSync(folder);
964979
if (!tmpFiles || tmpFiles.length <= 1) {
@@ -2125,10 +2140,41 @@ ipcMain.on('checkMultiUpdatePath', (event, arg) => {
21252140
}
21262141
});
21272142

2143+
/**
2144+
* Visual Studio version of an existing project, from its toolset like the commandLine does.
2145+
* @param {string} folder - The project folder.
2146+
* @param {string} projectName
2147+
* @returns {string} 2026, 2022, 2019 or '' when it isn't a Visual Studio project.
2148+
*/
2149+
function readProjectVsVersion(folder, projectName) {
2150+
try {
2151+
const match = /<PlatformToolset>(v14[235])/.exec(fs.readFileSync(path.join(folder, projectName + '.vcxproj'), 'utf8'));
2152+
return match ? { v142: '2019', v143: '2022', v145: '2026' }[match[1]] : '';
2153+
} catch (e) {
2154+
return '';
2155+
}
2156+
}
2157+
2158+
/**
2159+
* The newest installed Visual Studio, for the version dropdown's default.
2160+
* @returns {Promise<string>} 2026, 2022 or 2019; 2022 when none is found.
2161+
*/
2162+
async function detectVsVersion() {
2163+
for (const [major, version] of [['18', '2026'], ['17', '2022'], ['16', '2019']]) {
2164+
try {
2165+
await getVisualStudioPath(major);
2166+
return version;
2167+
} catch (e) {
2168+
// not installed, try the next one
2169+
}
2170+
}
2171+
return '2022';
2172+
}
2173+
21282174
function getVisualStudioPath(version) {
21292175
return new Promise((resolve, reject) => {
21302176
const vswherePath = "C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\vswhere.exe";
2131-
execFile(vswherePath, ['-latest', '-prerelease', '-format', 'json'], (error, stdout, stderr) => {
2177+
execFile(vswherePath, ['-all', '-prerelease', '-format', 'json'], (error, stdout, stderr) => {
21322178
if (error) {
21332179
reject("vswhere.exe not found. Ensure Visual Studio is installed.");
21342180
return;
@@ -2168,28 +2214,26 @@ async function openVisualStudio(windowsPath) {
21682214
return;
21692215
}
21702216

2171-
let isVS2019Project = false;
2217+
let vsMajor = "17";
21722218
const solutionFile = path.resolve(windowsPath);
21732219
console.log("VS Solution File Content: " + solutionFile);
21742220
if (fs.existsSync(solutionFile)) {
21752221
const fileContent = fs.readFileSync(solutionFile, 'utf8');
2176-
if (fileContent.match(/VisualStudioVersion = 16\.\d+/)) {
2177-
console.log("Detected VS2019!");
2178-
isVS2019Project = true;
2179-
} else {
2180-
console.log("VS2019 Not Detected.");
2222+
const solutionVersion = fileContent.match(/VisualStudioVersion = (16|17|18)\.\d+/);
2223+
if (solutionVersion) {
2224+
vsMajor = solutionVersion[1];
21812225
}
2226+
console.log("Detected Visual Studio major version: " + vsMajor);
21822227
} else {
21832228
console.error("Error: Solution file does not exist: " + solutionFile);
21842229
}
21852230

21862231
try {
2187-
const vsVersion = isVS2019Project ? "16" : "17";
2188-
console.log(`Opening in VS${isVS2019Project ? "2019" : "2022"}...`);
2189-
const vsPath = await getVisualStudioPath(vsVersion);
2232+
console.log(`Opening in Visual Studio ${vsMajor}...`);
2233+
const vsPath = await getVisualStudioPath(vsMajor);
21902234
execFile(vsPath, [windowsPath], (error) => {
21912235
if (error) {
2192-
console.error(`Error opening in VS${isVS2019Project ? "2019" : "2022"}:`, error.message);
2236+
console.error(`Error opening in Visual Studio ${vsMajor}:`, error.message);
21932237
}
21942238
});
21952239
} catch (error) {

‎frontend/locales/de.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@
154154
"field.postBuild": "Post-Build-Skript:",
155155
"placeholder.postBuild": "Läuft nach dem Kompilieren des Projekts - Xcode Run Script / VS-Postbuildereignis",
156156
"downloads.wasm64Confirm": "WASM64-Bibliotheken ersetzen die installierten lib/emscripten-Bibliotheken (die 32-Bit-Versionen werden entfernt). Fortfahren?",
157+
"field.vsVersion": "Visual-Studio-Version:",
157158
"field.msys2Env": "MSYS2-Umgebung (msys2 / VS Code):",
158159
"option.msys2Ucrt64": "UCRT64 (Standard)",
159160
"option.msys2Mingw64": "MINGW64 (veraltet)",

‎frontend/locales/en.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@
154154
"field.postBuild": "Post-build script:",
155155
"placeholder.postBuild": "Runs after the project compiles - Xcode run script / VS post-build event",
156156
"downloads.wasm64Confirm": "WASM64 libraries replace the installed lib/emscripten libraries (the 32-bit ones are removed). Continue?",
157+
"field.vsVersion": "Visual Studio version:",
157158
"field.msys2Env": "MSYS2 environment (msys2 / VS Code):",
158159
"option.msys2Ucrt64": "UCRT64 (default)",
159160
"option.msys2Mingw64": "MINGW64 (legacy)",

‎frontend/locales/es.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@
154154
"field.postBuild": "Script posterior a la compilación:",
155155
"placeholder.postBuild": "Se ejecuta después de compilar el proyecto - run script de Xcode / evento posterior a la compilación de VS",
156156
"downloads.wasm64Confirm": "Las bibliotecas WASM64 reemplazan las bibliotecas lib/emscripten instaladas (se eliminan las de 32 bits). ¿Continuar?",
157+
"field.vsVersion": "Versión de Visual Studio:",
157158
"field.msys2Env": "Entorno MSYS2 (msys2 / VS Code):",
158159
"option.msys2Ucrt64": "UCRT64 (predeterminado)",
159160
"option.msys2Mingw64": "MINGW64 (heredado)",

‎frontend/locales/fr.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,7 @@
154154
"field.postBuild": "Script post-compilation :",
155155
"placeholder.postBuild": "S'exécute après la compilation du projet - run script Xcode / événement post-build VS",
156156
"downloads.wasm64Confirm": "Les bibliothèques WASM64 remplacent les bibliothèques lib/emscripten installées (les versions 32 bits sont supprimées). Continuer ?",
157+
"field.vsVersion": "Version de Visual Studio :",
157158
"field.msys2Env": "Environnement MSYS2 (msys2 / VS Code) :",
158159
"option.msys2Ucrt64": "UCRT64 (par défaut)",
159160
"option.msys2Mingw64": "MINGW64 (ancien)",

0 commit comments

Comments
 (0)