Sort out sample apps

This commit is contained in:
Caelan Sayler
2024-02-26 14:39:48 +00:00
parent d40eb92295
commit 4084661851
39 changed files with 13 additions and 2025 deletions

View File

@@ -17,7 +17,9 @@
- name: C# WPF / .Net Framework - name: C# WPF / .Net Framework
href: https://github.com/velopack/velopack/tree/master/examples/VeloWpfSample href: https://github.com/velopack/velopack/tree/master/examples/VeloWpfSample
- name: C++ / MSVC / Win32 - name: C++ / MSVC / Win32
href: https://github.com/velopack/velopack/tree/master/examples/VeloCppWinSample href: https://github.com/velopack/velopack.fusion/tree/master/for-cpp/samples/win32
- name: Rust / iced-rs
href: https://github.com/velopack/velopack.fusion/tree/master/for-rust/samples/iced
- name: Essentials - name: Essentials

View File

@@ -1,232 +0,0 @@
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <shellapi.h>
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
#include "constants.h"
#include "velopack.hpp"
#pragma comment(linker, \
"\"/manifestdependency:type='Win32' "\
"name='Microsoft.Windows.Common-Controls' "\
"version='6.0.0.0' "\
"processorArchitecture='*' "\
"publicKeyToken='6595b64144ccf1df' "\
"language='*'\"")
#pragma comment(lib, "ComCtl32.lib")
HINSTANCE hInst;
const WCHAR szTitle[] = L"Velopack C++ Sample App";
const WCHAR szWindowClass[] = L"VeloCppWinSample";
velo_update_info updInfo = velo_update_info();
std::string updPath = "";
std::string currentVersion = "";
// Forward declarations of functions included in this code module:
int MessageBoxCentered(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType);
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
// the first thing we need to do in our app is initialise the velopack sdk
int pNumArgs = 0;
wchar_t** args = CommandLineToArgvW(lpCmdLine, &pNumArgs);
velo_startup(args, pNumArgs);
currentVersion = velo_get_version();
MyRegisterClass(hInstance);
if (!InitInstance(hInstance, nCmdShow))
{
return FALSE;
}
MSG msg;
// Main message loop:
while (GetMessage(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszClassName = szWindowClass;
wcex.hIcon = 0;
wcex.hIconSm = 0;
wcex.lpszMenuName = 0;
return RegisterClassExW(&wcex);
}
HWND hCheckButton;
HWND hDownloadButton;
HWND hRestartButton;
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // Store instance handle in our global variable
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, 300, 260, nullptr, nullptr, hInstance, nullptr);
hCheckButton = CreateWindowW(L"BUTTON", L"Check for updates",
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
40, 50, 200, 40,
hWnd, NULL, (HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE), NULL);
hDownloadButton = CreateWindowW(L"BUTTON", L"Download update",
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
40, 100, 200, 40,
hWnd, NULL, (HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE), NULL);
hRestartButton = CreateWindowW(L"BUTTON", L"Apply / Restart",
WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
40, 150, 200, 40,
hWnd, NULL, (HINSTANCE)GetWindowLongPtr(hWnd, GWLP_HINSTANCE), NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_COMMAND:
{
if (LOWORD(wParam) == BN_CLICKED)
{
if ((HWND)lParam == hCheckButton)
{
try {
velo_update_info info = velo_check_for_updates(UPDATE_URL);
if (info.is_update_available) {
// this is a hack to convert ascii to wide string
std::wstring message = L"Update available: " + std::wstring(info.version.begin(), info.version.end());
MessageBoxCentered(hWnd, message.c_str(), szTitle, MB_OK);
updInfo = info;
}
else {
MessageBoxCentered(hWnd, L"No updates available.", szTitle, MB_OK);
}
}
catch (std::exception& e) {
std::string what = e.what();
std::wstring wideWhat(what.begin(), what.end());
MessageBoxCentered(hWnd, wideWhat.c_str(), szTitle, MB_OK | MB_ICONERROR);
}
}
else if ((HWND)lParam == hDownloadButton)
{
if (updInfo.is_update_available) {
try {
velo_download_updates(UPDATE_URL, updInfo.file_name.c_str(), [](int x) {}, [&hWnd](std::string path)
{
updPath = path;
std::wstring message = L"Downloaded successfully to: " + std::wstring(path.begin(), path.end());
MessageBoxCentered(hWnd, message.c_str(), szTitle, MB_OK);
});
}
catch (std::exception& e) {
std::string what = e.what();
std::wstring wideWhat(what.begin(), what.end());
MessageBoxCentered(hWnd, wideWhat.c_str(), szTitle, MB_OK | MB_ICONERROR);
}
}
else {
MessageBoxCentered(hWnd, L"Check for updates first.", szTitle, MB_OK);
}
}
else if ((HWND)lParam == hRestartButton)
{
if (updPath.empty()) {
MessageBoxCentered(hWnd, L"Download an update first.", szTitle, MB_OK);
}
else {
velo_apply_updates(true, updPath.c_str());
}
}
}
break;
}
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
RECT r{ 0, 5, ps.rcPaint.right, ps.rcPaint.bottom };
auto ver = std::wstring(currentVersion.begin(), currentVersion.end());
std::wstring text = L"Welcome to v" + ver + L" of the\nVelopack C++ Sample App.";
DrawText(hdc, text.c_str(), -1, &r, DT_BOTTOM | DT_CENTER);
EndPaint(hWnd, &ps);
break;
}
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
int MessageBoxCentered(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType)
{
// Center message box at its parent window
static HHOOK hHookCBT{};
hHookCBT = SetWindowsHookEx(WH_CBT,
[](int nCode, WPARAM wParam, LPARAM lParam) -> LRESULT
{
if (nCode == HCBT_CREATEWND)
{
if (((LPCBT_CREATEWND)lParam)->lpcs->lpszClass == (LPWSTR)(ATOM)32770) // #32770 = dialog box class
{
RECT rcParent{};
GetWindowRect(((LPCBT_CREATEWND)lParam)->lpcs->hwndParent, &rcParent);
((LPCBT_CREATEWND)lParam)->lpcs->x = rcParent.left + ((rcParent.right - rcParent.left) - ((LPCBT_CREATEWND)lParam)->lpcs->cx) / 2;
((LPCBT_CREATEWND)lParam)->lpcs->y = rcParent.top + ((rcParent.bottom - rcParent.top) - ((LPCBT_CREATEWND)lParam)->lpcs->cy) / 2;
}
}
return CallNextHookEx(hHookCBT, nCode, wParam, lParam);
},
0, GetCurrentThreadId());
int iRet{ MessageBox(hWnd, lpText, lpCaption, uType) };
UnhookWindowsHookEx(hHookCBT);
return iRet;
}

View File

@@ -1,31 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34525.116
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "VeloCppWinSample", "VeloCppWinSample.vcxproj", "{F9BB1F11-3827-4745-B11B-77FA5DBE1195}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F9BB1F11-3827-4745-B11B-77FA5DBE1195}.Debug|x64.ActiveCfg = Debug|x64
{F9BB1F11-3827-4745-B11B-77FA5DBE1195}.Debug|x64.Build.0 = Debug|x64
{F9BB1F11-3827-4745-B11B-77FA5DBE1195}.Debug|x86.ActiveCfg = Debug|Win32
{F9BB1F11-3827-4745-B11B-77FA5DBE1195}.Debug|x86.Build.0 = Debug|Win32
{F9BB1F11-3827-4745-B11B-77FA5DBE1195}.Release|x64.ActiveCfg = Release|x64
{F9BB1F11-3827-4745-B11B-77FA5DBE1195}.Release|x64.Build.0 = Release|x64
{F9BB1F11-3827-4745-B11B-77FA5DBE1195}.Release|x86.ActiveCfg = Release|Win32
{F9BB1F11-3827-4745-B11B-77FA5DBE1195}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {BE15ADBD-1862-47E7-8704-0721D758269F}
EndGlobalSection
EndGlobal

View File

@@ -1,144 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{f9bb1f11-3827-4745-b11b-77fa5dbe1195}</ProjectGuid>
<RootNamespace>VeloCppWinSample</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="VeloCppWinSample.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="constants.h" />
<ClInclude Include="subprocess.h" />
<ClInclude Include="velopack.hpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -1,29 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="VeloCppWinSample.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="velopack.hpp">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="subprocess.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="constants.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@@ -1 +0,0 @@
#define UPDATE_URL "REPLACE_ME"

View File

@@ -1,53 +0,0 @@
@echo off
REM This script requires several tools to be installed for it to work:
REM cargo (rust): winget install Rustlang.Rustup
REM Nerdbank.GitVersioning (nbgv): dotnet tool install --global nbgv
REM C++ Build Tools, typically installed via "Desktop development with C++" workload.
setlocal enabledelayedexpansion
if "%~1"=="" (
echo Version number is required.
echo Usage: build.bat [version] [extra_args...]
exit /b 1
)
echo.
echo Building Velopack Rust
cd %~dp0..\..\src\Rust
cargo build --features windows,extendedcli
echo.
echo Building Velopack Vpk
cd %~dp0..\..\
dotnet build src/Velopack.Vpk/Velopack.Vpk.csproj
cd %~dp0
set VSWHERE_PATH="%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe"
echo.
echo Locating MSBuild using vswhere
for /f "usebackq tokens=*" %%i in (`%VSWHERE_PATH% -latest -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe`) do (
set "MSBUILD_PATH=%%i"
goto :buildCpp
)
:buildCpp
if not defined MSBUILD_PATH (
echo MSBuild not found, make sure Visual Studio is installed with C++ Build Tools.
exit /b 1
)
echo #define UPDATE_URL R"(%~dp0releases)" > constants.h
echo.
echo Building VeloCppWinSample
cd %~dp0
"%MSBUILD_PATH%" VeloCppWinSample.sln /p:Configuration=Release
echo #define UPDATE_URL "REPLACE_ME" > constants.h
echo.
echo Building Velopack Release v%~1
%~dp0..\..\build\Debug\net8.0\vpk pack -u VeloCppWinSample -o releases -p x64\Release -f net8-x64-desktop -v %*

View File

@@ -1,8 +0,0 @@
# VeloCppWinSample
_Prerequisites: Rust/Cargo, Dotnet, Msbuild_
This app is purely a proof of concept at this time, `velopack.hpp` currently only works on windows and needs testing / fixes for other operating systems, and probably also needs fixing for unicode/strings. This sample is made up of a simple Win32 desktop app, generated via a Visual Studio template, and it includes `velopack.hpp` and [`subprocess.h`](https://github.com/sheredom/subprocess.h).
Also, this is using command line features not currently exposed in the main Velopack releases, so you can only build releases from source by using the `dev-build.bat [version]` script. Trying to build/use this sample with the mainstream `vpk` tool is not guarenteed to work at this time.
If you are interested in using Velopack for your C++ project and are willing to help with the design of `velopack.hpp` (either with suggestions, or code), please drop in our Discord and I would be happy to discuss / work with you to polish this up.

File diff suppressed because it is too large Load Diff

View File

@@ -1,306 +0,0 @@
// This header assumes all strings will be in UTF-8. If you are using wstring's on Windows,
// you will need to convert them to UTF-8 before using any of the functions in this header.
// Additionally, if you are on Windows, to enable unicode you will need to specify the UTF-8
// codepage in your application's manifest file.
// https://learn.microsoft.com/en-us/windows/apps/design/globalizing/use-utf8-code-page
#pragma once
#ifndef VELOPACKSDK_H
#define VELOPACKSDK_H
#include <string>
#include <functional>
#include <stdexcept>
#include <filesystem>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
// https://github.com/sheredom/subprocess.h
#include "subprocess.h"
// import windows header only if we are using MSVC
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#define PATH_MAX MAX_PATH
#include <windows.h>
#endif // VELO_MSVC
struct velo_update_info {
bool is_update_available;
std::string version;
std::string sha1;
std::string file_name;
uint64_t file_size;
velo_update_info()
: is_update_available(false), version(""), sha1(""), file_name(""), file_size(0) {}
velo_update_info(std::string version, std::string sha1, std::string file_name, uint64_t file_size)
: is_update_available(true), version(version), sha1(sha1), file_name(file_name), file_size(file_size) {}
};
#if UNICODE
void velo_startup(wchar_t** args, size_t c_args) {
for (size_t i = 0; i < c_args; ++i) {
if (std::wstring(args[i]) == L"--veloapp-install") {
exit(0);
}
if (std::wstring(args[i]) == L"--veloapp-updated") {
exit(0);
}
if (std::wstring(args[i]) == L"--veloapp-obsolete") {
exit(0);
}
if (std::wstring(args[i]) == L"--veloapp-uninstall") {
exit(0);
}
}
}
#endif // UNICODE
void velo_startup(char** args, size_t c_args) {
for (size_t i = 0; i < c_args; ++i) {
if (std::string(args[i]) == "--veloapp-install") {
exit(0);
}
if (std::string(args[i]) == "--veloapp-updated") {
exit(0);
}
if (std::string(args[i]) == "--veloapp-obsolete") {
exit(0);
}
if (std::string(args[i]) == "--veloapp-uninstall") {
exit(0);
}
}
}
std::string velo_get_own_exe_path() {
const size_t buf_size = PATH_MAX;
char path_buf[buf_size];
size_t bytes_read = buf_size;
#ifdef __APPLE__
if (_NSGetExecutablePath(path_buf, &bytes_read) != 0) {
throw std::runtime_error("Buffer size is too small for executable path.");
}
#elif defined(_WIN32)
HMODULE hMod = GetModuleHandleA(NULL);
bytes_read = GetModuleFileNameA(hMod, path_buf, buf_size);
#else
bytes_read = readlink("/proc/self/exe", path_buf, bufSize);
if ((int)bytes_read == -1) {
throw std::runtime_error("Permission denied to /proc/self/exe.");
}
#endif
return std::string(path_buf, bytes_read);
}
std::string velo_get_update_exe_path() {
return "C:\\Users\\Caelan\\AppData\\Local\\VeloCppWinSample\\Update.exe";
std::string own_path = velo_get_own_exe_path();
std::filesystem::path p(own_path);
#ifdef __APPLE__
p = p.parent_path() / "UpdateMac";
#elif defined(_WIN32)
p = p.parent_path().parent_path() / "Update.exe";
#else
p = p.parent_path() / "UpdateNix";
#endif
if (!std::filesystem::exists(p)) {
throw std::runtime_error("Update executable not found. Is this an installed app?");
}
return p.string();
}
subprocess_s velo_start_subprocess(const std::vector<std::string>& command_line, int options) {
const char** command_line_array = new const char* [command_line.size() + 1];
for (size_t i = 0; i < command_line.size(); ++i) {
command_line_array[i] = command_line[i].c_str();
}
command_line_array[command_line.size()] = NULL; // last element must be NULL
struct subprocess_s subprocess;
int result = subprocess_create(command_line_array, options, &subprocess);
delete[] command_line_array; // clean up the array
if (result != 0) {
throw std::runtime_error("Unable to start Update process.");
}
return subprocess;
}
std::string velo_get_version() {
std::string update_exe = velo_get_update_exe_path();
std::vector<std::string> command_line;
command_line.push_back(update_exe);
command_line.push_back("get-version");
subprocess_s subprocess = velo_start_subprocess(command_line, subprocess_option_no_window);
// read all stdout from the process
FILE* p_stdout = subprocess_stdout(&subprocess);
std::filebuf buf = std::basic_filebuf<char>(p_stdout);
std::istream is(&buf);
std::stringstream buffer;
buffer << is.rdbuf();
std::string output = buffer.str();
const char* ws = " \t\n\r\f\v";
output.erase(0, output.find_first_not_of(ws));
output.erase(output.find_last_not_of(ws) + 1);
return output;
}
velo_update_info velo_check_for_updates(const char* url_or_path, bool allow_downgrade = false, char* explicit_channel = 0) {
std::string update_exe = velo_get_update_exe_path();
std::vector<std::string> command_line;
command_line.push_back(update_exe);
command_line.push_back("check");
command_line.push_back("--url");
command_line.push_back(url_or_path);
command_line.push_back("--format");
command_line.push_back("text");
if (allow_downgrade) {
command_line.push_back("--downgrade");
}
if (explicit_channel != NULL) {
command_line.push_back("--channel");
command_line.push_back(explicit_channel);
}
subprocess_s subprocess = velo_start_subprocess(command_line, subprocess_option_no_window);
int process_return;
if (subprocess_join(&subprocess, &process_return) != 0) {
throw std::runtime_error("Unable to join Update process.");
}
// read all stdout from the process
FILE* p_stdout = subprocess_stdout(&subprocess);
std::filebuf buf = std::basic_filebuf<char>(p_stdout);
std::istream is(&buf);
std::stringstream buffer;
buffer << is.rdbuf();
std::string output = buffer.str();
if (output.empty() || output.rfind("null", 0) == 0) {
return velo_update_info();
}
// split the output into whitespace-delimited tokens
std::istringstream iss(output);
std::vector<std::string> tokens;
std::string token;
while (iss >> token) {
tokens.push_back(token);
}
// parse the tokens into an update_info struct
velo_update_info info(tokens[0], tokens[1], tokens[2], std::stoull(tokens[3]));
return info;
}
void velo_download_updates(const char* url_or_path, const char* release_name,
std::function<void(uint8_t)> progress_fn, std::function<void(std::string)> complete_fn) {
std::string update_exe = velo_get_update_exe_path();
std::vector<std::string> command_line;
command_line.push_back(update_exe);
command_line.push_back("download");
command_line.push_back("--clean");
command_line.push_back("--url");
command_line.push_back(url_or_path);
command_line.push_back("--format");
command_line.push_back("text");
command_line.push_back("--name");
command_line.push_back(release_name);
subprocess_s subprocess = velo_start_subprocess(command_line, subprocess_option_no_window | subprocess_option_enable_async);
const unsigned BUFFER_SIZE = 1024;
char readBuffer[BUFFER_SIZE];
std::string accumulatedData;
const char* ws = " \t\n\r\f\v";
auto handle_line = [&ws, &progress_fn, &complete_fn](std::string& line)
{
line.erase(0, line.find_first_not_of(ws));
line.erase(line.find_last_not_of(ws) + 1);
if (line.rfind("complete:", 0) == 0) {
std::string pkg_path = line.substr(9);
pkg_path.erase(0, pkg_path.find_first_not_of(ws));
pkg_path.erase(pkg_path.find_last_not_of(ws) + 1);
complete_fn(pkg_path);
return true;
}
if (line.rfind("err:", 0) == 0) {
throw new std::runtime_error("Error downloading update: " + line);
}
try {
uint8_t progress = static_cast<uint8_t>(std::stoi(line));
progress_fn(progress);
}
catch (const std::exception&) {
}
return false;
};
// read all stdout from the process one line at a time
while (true) {
unsigned bytesRead = subprocess_read_stdout(&subprocess, readBuffer, BUFFER_SIZE - 1);
if (bytesRead == 0) {
// bytesRead is 0, indicating the process has completed
// Process any remaining data in accumulatedData as the last line if needed
if (!accumulatedData.empty()) {
handle_line(accumulatedData);
}
return;
}
readBuffer[bytesRead] = '\0';
accumulatedData += readBuffer;
// Process accumulated data for lines
size_t pos;
while ((pos = accumulatedData.find('\n')) != std::string::npos) {
std::string line = accumulatedData.substr(0, pos);
if (handle_line(line)) {
return; // complete or err
}
accumulatedData.erase(0, pos + 1);
}
}
}
void velo_apply_updates(bool restart, const char* package_path = 0) {
std::string update_exe = velo_get_update_exe_path();
std::vector<std::string> command_line;
command_line.push_back(update_exe);
command_line.push_back("apply");
if (package_path != NULL) {
command_line.push_back("--package");
command_line.push_back(package_path);
}
if (restart) {
command_line.push_back("--restart");
}
subprocess_s subprocess = velo_start_subprocess(command_line, subprocess_option_no_window);
exit(0);
}
#endif // VELOPACKSDK_H

View File

@@ -1,7 +0,0 @@
# Velopack Examples
- [**AvaloniaCrossPlat**](AvaloniaCrossPlat) - uses Avalonia to provide a desktop UI, installer, and updates for Mac, Linux, and Windows.
- [**VeloWpfSample**](VeloWpfSample) - demonstrates how to use Velopack effectively with WPF.
- [**VeloCppWinSample**](VeloCppWinSample) - a minimal proof of concept using Velopack with C++ / Win32 on Windows.

View File

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

10
samples/readme.md Normal file
View File

@@ -0,0 +1,10 @@
# Velopack Examples
- [**AvaloniaCrossPlat**](AvaloniaCrossPlat) - uses Avalonia to provide a desktop UI, installer, and updates for Mac, Linux, and Windows.
- [**VeloWpfSample**](VeloWpfSample) - demonstrates how to use Velopack effectively with WPF.
## Other Languages
Note that only sample apps written in C# using the core reference library are available here.
For other programming languages (Rust, C++, JS, etc) please visit the [Velopack Fusion](https://github.com/velopack/velopack.fusion) repository.