Files
SimpleRemoter/common/UnixPath.h
T
yuanyuanxianganddeepseek-flash 106ac2ff0f Fix: Resolve the Desktop, Downloads and home shortcuts on Unix clients
The file manager's remote shortcut buttons send "%USERPROFILE%\Desktop\" and
friends, which the Windows client expands with ExpandEnvironmentStringsA. Unix
clients had no such expansion, so the literal %USERPROFILE% was taken as a
directory name: opendir() failed and the Desktop, Downloads and home buttons
listed nothing at all.

Add common/UnixPath.h, which expands the variables the server can send
(%USERPROFILE%, %HOME%, %HOMEDRIVE%%HOMEPATH%, %USERNAME%) and maps
$HOME/Desktop to the localized folder named in ~/.config/user-dirs.dirs (for
example ~/桌面), falling back to the plain $HOME/<Name> path when that folder
does not exist. Unknown %VAR% tokens are left untouched, so paths that really
contain a percent sign behave as before.

FileManager and the two Windows-to-Unix converters in FileTransferV2 now share
that one conversion. Besides the listing itself, this fixes downloads into a
shortcut directory, which used to be created under a literal %USERPROFILE%
tree instead of the user's real desktop.

Co-Authored-By: deepseek-flash
2026-10-28 14:44:54 +01:00

215 lines
7.4 KiB
C++

/**
* UnixPath.h - Windows-style path handling on Unix clients
*
* The Windows server sends paths in its own dialect: drive letters ("C:\", or
* "/:" for a Unix root), backslashes, and environment variables that the Windows
* client expands with ExpandEnvironmentStringsA. The remote shortcut buttons
* (server/2015Remote/FileManagerDlg.cpp: OnRemoteDesktop/OnRemoteDownloads/
* OnRemoteHome) are the visible case — they send "%USERPROFILE%\Desktop\" and
* friends, which a Unix client cannot open as-is.
*
* This header turns such paths into something the Unix clients can use:
* %USERPROFILE% / %HOME% / %HOMEDRIVE%%HOMEPATH% -> $HOME
* %USERNAME% / %USER% / %LOGNAME% -> login name
* $HOME/Desktop (etc.) -> the XDG folder when
* user-dirs.dirs maps it
* (e.g. ~/桌面)
* Unknown %VAR% tokens are left untouched, so paths that legitimately contain a
* percent sign keep working as before.
*
* PLATFORM SUPPORT: Linux, macOS. Windows resolves these natively and does not
* include this header.
*/
#pragma once
#include <unistd.h>
#include <pwd.h>
#include <sys/stat.h>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <map>
#include <string>
namespace UnixPath
{
// ---- Home directory of the account the client runs as ----
inline std::string HomeDir()
{
const char* home = getenv("HOME");
if (home && *home) return home;
struct passwd* pw = getpwuid(getuid());
if (pw && pw->pw_dir && *pw->pw_dir) return pw->pw_dir;
return "/";
}
inline std::string TrimTrailingSlashes(std::string path)
{
while (path.size() > 1 && path.back() == '/') path.pop_back();
return path;
}
// Read ~/.config/user-dirs.dirs into {"Desktop" -> "/home/user/桌面", ...}.
// The shortcuts use the English folder names, but on a localized desktop the
// real folders are translated and only user-dirs.dirs knows where they are.
// Entries pointing at a missing directory are dropped so the caller falls back
// to the plain "$HOME/<Name>" path.
inline std::map<std::string, std::string> LoadXdgUserDirs()
{
std::map<std::string, std::string> dirs;
std::string home = TrimTrailingSlashes(HomeDir());
const char* cfgHome = getenv("XDG_CONFIG_HOME");
std::string file = (cfgHome && *cfgHome) ? cfgHome : (home + "/.config");
file += "/user-dirs.dirs";
std::ifstream in(file.c_str());
std::string line;
while (std::getline(in, line)) {
size_t eq = line.find('=');
if (eq == std::string::npos || line.compare(0, 4, "XDG_") != 0)
continue;
std::string key = line.substr(4, eq - 4); // DESKTOP_DIR
if (key.size() <= 4 || key.compare(key.size() - 4, 4, "_DIR") != 0)
continue;
std::string value = line.substr(eq + 1);
if (value.size() >= 2 && value.front() == '"' && value.back() == '"')
value = value.substr(1, value.size() - 2);
// $HOME / ${HOME} are the only variables user-dirs.dirs may use
for (size_t pos; (pos = value.find("${HOME}")) != std::string::npos; )
value.replace(pos, 7, home);
for (size_t pos; (pos = value.find("$HOME")) != std::string::npos; )
value.replace(pos, 5, home);
// DESKTOP_DIR -> "Desktop"
std::string name = key.substr(0, key.size() - 4);
for (auto& c : name) c = (char)tolower((unsigned char)c);
if (!name.empty()) name[0] = (char)toupper((unsigned char)name[0]);
if (!value.empty() && access(value.c_str(), F_OK) == 0)
dirs[name] = TrimTrailingSlashes(value);
}
return dirs;
}
inline const std::map<std::string, std::string>& XdgUserDirs()
{
// C++11 guarantees a thread-safe one-time initialization of the local static
static const std::map<std::string, std::string> dirs = LoadXdgUserDirs();
return dirs;
}
// Rewrite $HOME/Desktop (etc.) to the localized folder user-dirs.dirs names.
// Expects a slash-separated absolute path.
inline std::string RemapXdgUserDir(const std::string& path)
{
std::string home = TrimTrailingSlashes(HomeDir());
if (path.compare(0, home.size(), home) != 0)
return path;
const std::map<std::string, std::string>& dirs = XdgUserDirs();
if (dirs.empty())
return path;
std::string base = (home == "/") ? "" : home;
for (const auto& kv : dirs) {
std::string prefix = base + "/" + kv.first;
if (path == prefix ||
(path.compare(0, prefix.size(), prefix) == 0 && path[prefix.size()] == '/'))
return kv.second + path.substr(prefix.size());
}
return path;
}
// Expand %USERPROFILE% style variables in a path the server sent.
inline std::string ExpandWindowsEnvVars(const std::string& in)
{
std::string out;
out.reserve(in.size());
for (size_t i = 0; i < in.size(); ) {
if (in[i] != '%') {
out += in[i++];
continue;
}
size_t end = in.find('%', i + 1);
if (end == std::string::npos) {
out.append(in, i, std::string::npos);
break;
}
// Windows variable names are case-insensitive
std::string name = in.substr(i + 1, end - i - 1);
for (auto& c : name) c = (char)toupper((unsigned char)c);
bool known = true;
std::string value;
if (name == "USERPROFILE" || name == "HOME" || name == "HOMEPATH") {
value = HomeDir();
} else if (name == "HOMEDRIVE") {
// "%HOMEDRIVE%%HOMEPATH%" has to come out as a single absolute home path
value = "";
} else if (name == "USERNAME" || name == "USER" || name == "LOGNAME") {
const char* user = getenv("USER");
if (!user || !*user) user = getenv("LOGNAME");
struct passwd* pw = getpwuid(getuid());
value = (user && *user) ? user : ((pw && pw->pw_name) ? pw->pw_name : "");
} else {
known = false;
}
if (known)
out += value;
else
out.append(in, i, end - i + 1);
i = end + 1;
}
return out;
}
// Convert a Windows-dialect path into one the Unix clients can open:
// %USERPROFILE%\Desktop\ -> /home/user/Desktop/ (or the XDG desktop folder)
// /:\home\user\file.txt -> /home/user/file.txt
// C:\Users\file.txt -> /Users/file.txt
// "" -> /
inline std::string ToUnixPath(const std::string& winPath)
{
if (winPath.empty()) return "/";
std::string p = ExpandWindowsEnvVars(winPath);
// 1. Backslash -> forward slash
for (auto& c : p) {
if (c == '\\') c = '/';
}
// 2. Remove "X:/" or "X:" prefix (handles both /: and C: style)
if (p.size() >= 3 && p[1] == ':' && p[2] == '/') {
p = p.substr(3);
} else if (p.size() >= 2 && p[1] == ':') {
p = p.substr(2);
}
// 3. Ensure starts with /
if (p.empty() || p[0] != '/') {
p = "/" + p;
}
// 4. Merge consecutive slashes
std::string result;
result.reserve(p.size());
for (size_t i = 0; i < p.size(); i++) {
if (i > 0 && p[i] == '/' && p[i - 1] == '/')
continue;
result += p[i];
}
if (result.empty()) return "/";
// 5. "$HOME/Desktop" -> localized folder (~/桌面 ...) when user-dirs.dirs says so
return RemapXdgUserDir(result);
}
} // namespace UnixPath