MainWindow.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. /*
  2. * GnomeSettingsVault - A GNOME configuration backup utility v0.3.2
  3. */
  4. #include "MainWindow.hpp"
  5. #include <iostream>
  6. #include <filesystem>
  7. #include <archive.h>
  8. #include <archive_entry.h>
  9. #include <fcntl.h>
  10. #include <unistd.h>
  11. #include <cstdlib>
  12. #include <cstdio>
  13. #include <algorithm>
  14. #include <chrono>
  15. #include <iomanip>
  16. #include <sstream>
  17. #include <set>
  18. #include <glibmm/miscutils.h>
  19. #include <glibmm/fileutils.h>
  20. namespace fs = std::filesystem;
  21. MainWindow::MainWindow()
  22. : m_HeaderBar(), m_MainLayout(Gtk::ORIENTATION_VERTICAL, 0), m_Notebook(),
  23. m_BottomBox(Gtk::ORIENTATION_HORIZONTAL, 10), m_StatusLabel("Ready."),
  24. m_CheckDebugMode("Write Debug Log to Disk (~/GnomeSettingsVault.log)"), m_VBoxBackup(Gtk::ORIENTATION_VERTICAL, 10),
  25. m_LabelBackupInstruction("<span size='large' weight='bold'>Backup</span>"),
  26. m_CheckThemesBackup("GTK Themes"), m_CheckIconsBackup("Icons"),
  27. m_CheckWallpapersBackup("Wallpapers"), m_CheckExtensionsBackup("GNOME Extensions"),
  28. m_CheckDconfBackup("GNOME Settings"), m_ButtonBackup("Start Backup"),
  29. m_VBoxRestore(Gtk::ORIENTATION_VERTICAL, 10),
  30. m_LabelRestoreInstruction("<span size='large' weight='bold'>Restore from Vault</span>"),
  31. m_ButtonSelectVault("Select .gbk Vault File"), m_LabelSelectedVault("No vault selected"),
  32. m_CheckThemesRestore("GTK Themes"), m_CheckIconsRestore("Icons"),
  33. m_CheckWallpapersRestore("Wallpapers"), m_CheckExtensionsRestore("GNOME Extensions"),
  34. m_CheckDconfRestore("GNOME Settings"), m_CheckDryRunRestore("Dry Run"),
  35. m_ButtonRestore("Start Restore"), m_WorkerRunning(false), m_JobSuccess(true),
  36. m_IsDebugMode(false), m_LastJobWasRestore(false)
  37. {
  38. m_Dispatcher.connect(sigc::mem_fun(*this, &MainWindow::on_dispatcher_ping));
  39. set_default_size(1000, 700);
  40. m_HeaderBar.set_title("GnomeSettingsVault 0.3.2");
  41. m_HeaderBar.set_show_close_button(true);
  42. set_titlebar(m_HeaderBar);
  43. set_wmclass("gnome-vault", "GnomeSettingsVault");
  44. m_LabelBackupInstruction.set_use_markup(true);
  45. m_LabelRestoreInstruction.set_use_markup(true);
  46. m_RefTextBuffer = Gtk::TextBuffer::create();
  47. m_LogView.set_buffer(m_RefTextBuffer);
  48. m_LogView.set_editable(false);
  49. m_LogView.override_background_color(Gdk::RGBA("#1e1e1e"));
  50. m_LogView.override_color(Gdk::RGBA("#dcdcdc"));
  51. m_RefTextBuffer->create_mark("last_line", m_RefTextBuffer->end());
  52. m_ScrolledWindow.add(m_LogView);
  53. m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_ALWAYS);
  54. m_VBoxBackup.set_border_width(20);
  55. m_VBoxBackup.pack_start(m_LabelBackupInstruction, Gtk::PACK_SHRINK);
  56. m_VBoxBackup.pack_start(m_CheckThemesBackup, Gtk::PACK_SHRINK);
  57. m_VBoxBackup.pack_start(m_CheckIconsBackup, Gtk::PACK_SHRINK);
  58. m_VBoxBackup.pack_start(m_CheckWallpapersBackup, Gtk::PACK_SHRINK);
  59. m_VBoxBackup.pack_start(m_CheckExtensionsBackup, Gtk::PACK_SHRINK);
  60. m_VBoxBackup.pack_start(m_CheckDconfBackup, Gtk::PACK_SHRINK);
  61. m_VBoxBackup.pack_end(m_ButtonBackup, Gtk::PACK_SHRINK);
  62. m_VBoxRestore.set_border_width(20);
  63. m_VBoxRestore.pack_start(m_LabelRestoreInstruction, Gtk::PACK_SHRINK);
  64. m_VBoxRestore.pack_start(m_ButtonSelectVault, Gtk::PACK_SHRINK);
  65. m_VBoxRestore.pack_start(m_LabelSelectedVault, Gtk::PACK_SHRINK);
  66. m_VBoxRestore.pack_start(m_CheckThemesRestore, Gtk::PACK_SHRINK);
  67. m_VBoxRestore.pack_start(m_CheckIconsRestore, Gtk::PACK_SHRINK);
  68. m_VBoxRestore.pack_start(m_CheckWallpapersRestore, Gtk::PACK_SHRINK);
  69. m_VBoxRestore.pack_start(m_CheckExtensionsRestore, Gtk::PACK_SHRINK);
  70. m_VBoxRestore.pack_start(m_CheckDconfRestore, Gtk::PACK_SHRINK);
  71. m_VBoxRestore.pack_start(m_CheckDryRunRestore, Gtk::PACK_SHRINK);
  72. m_VBoxRestore.pack_end(m_ButtonRestore, Gtk::PACK_SHRINK);
  73. m_Notebook.append_page(m_VBoxBackup, "Backup");
  74. m_Notebook.append_page(m_VBoxRestore, "Restore");
  75. m_BottomBox.set_border_width(10);
  76. m_BottomBox.pack_start(m_StatusLabel, Gtk::PACK_EXPAND_WIDGET);
  77. m_BottomBox.pack_end(m_CheckDebugMode, Gtk::PACK_SHRINK);
  78. m_MainLayout.pack_start(m_Notebook, Gtk::PACK_SHRINK);
  79. m_MainLayout.pack_start(m_ScrolledWindow, Gtk::PACK_EXPAND_WIDGET);
  80. m_MainLayout.pack_start(m_BottomBox, Gtk::PACK_SHRINK);
  81. m_ButtonBackup.signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::on_button_backup_clicked));
  82. m_ButtonRestore.signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::on_button_restore_clicked));
  83. m_ButtonSelectVault.signal_clicked().connect(sigc::mem_fun(*this, &MainWindow::on_button_select_vault_clicked));
  84. add(m_MainLayout);
  85. show_all_children();
  86. }
  87. MainWindow::~MainWindow() {}
  88. void MainWindow::send_notification(const std::string& title, const std::string& body) {
  89. auto app = Gtk::Application::get_default();
  90. auto notification = Gio::Notification::create(title);
  91. notification->set_body(body);
  92. app->send_notification(notification);
  93. }
  94. void MainWindow::scan_vault_contents(const std::string& path) {
  95. struct archive *a = archive_read_new();
  96. struct archive_entry *entry;
  97. archive_read_support_format_all(a);
  98. archive_read_support_filter_all(a);
  99. std::set<std::string> found;
  100. if (archive_read_open_filename(a, path.c_str(), 10240) == ARCHIVE_OK) {
  101. while (archive_read_next_header(a, &entry) == ARCHIVE_OK) {
  102. std::string p = archive_entry_pathname(entry);
  103. if (p.find("themes_") != std::string::npos) found.insert("themes");
  104. if (p.find("icons_") != std::string::npos) found.insert("icons");
  105. if (p.find("wallpapers.tar.gz") != std::string::npos) found.insert("wallpapers");
  106. if (p.find("extensions.tar.gz") != std::string::npos) found.insert("extensions");
  107. if (p.find("settings.ini") != std::string::npos) found.insert("dconf");
  108. }
  109. }
  110. archive_read_free(a);
  111. m_CheckThemesRestore.set_active(found.count("themes"));
  112. m_CheckIconsRestore.set_active(found.count("icons"));
  113. m_CheckWallpapersRestore.set_active(found.count("wallpapers"));
  114. m_CheckExtensionsRestore.set_active(found.count("extensions"));
  115. m_CheckDconfRestore.set_active(found.count("dconf"));
  116. }
  117. void MainWindow::on_button_select_vault_clicked() {
  118. Gtk::FileChooserDialog dialog("Choose vault", Gtk::FILE_CHOOSER_ACTION_OPEN);
  119. dialog.set_transient_for(*this);
  120. dialog.add_button("_Cancel", Gtk::RESPONSE_CANCEL);
  121. dialog.add_button("_Open", Gtk::RESPONSE_OK);
  122. if (dialog.run() == Gtk::RESPONSE_OK) {
  123. m_SelectedVaultPath = dialog.get_filename();
  124. m_LabelSelectedVault.set_text("Selected: " + fs::path(m_SelectedVaultPath).filename().string());
  125. scan_vault_contents(m_SelectedVaultPath);
  126. add_log_ui("Vault loaded.");
  127. }
  128. }
  129. void MainWindow::queue_log(const std::string& message) {
  130. if (m_IsDebugMode) {
  131. std::ofstream log_file(std::string(std::getenv("HOME")) + "/GnomeSettingsVault.log", std::ios::app);
  132. if (log_file.is_open()) { log_file << message << std::endl; log_file.close(); }
  133. }
  134. std::lock_guard<std::mutex> lock(m_LogMutex);
  135. m_LogQueue.push(message);
  136. m_Dispatcher.emit();
  137. }
  138. void MainWindow::on_dispatcher_ping() {
  139. std::lock_guard<std::mutex> lock(m_LogMutex);
  140. while (!m_LogQueue.empty()) {
  141. std::string msg = m_LogQueue.front();
  142. m_LogQueue.pop();
  143. if (msg == "__UNLOCK_UI__") {
  144. set_ui_locked(false);
  145. send_notification("Job Finished", m_JobSuccess ? "Successfully completed." : "Errors detected.");
  146. if (m_JobSuccess && m_LastJobWasRestore) {
  147. Gtk::MessageDialog dialog(*this, "Restore Complete", false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO);
  148. dialog.set_secondary_text("Settings restored. Restart GNOME session now?");
  149. if (dialog.run() == Gtk::RESPONSE_YES) system("gnome-session-quit --logout --no-prompt &");
  150. }
  151. } else {
  152. add_log_ui(msg);
  153. }
  154. }
  155. }
  156. void MainWindow::add_log_ui(const std::string& message) {
  157. m_RefTextBuffer->insert(m_RefTextBuffer->end(), message + "\n");
  158. auto mark = m_RefTextBuffer->get_mark("last_line");
  159. m_RefTextBuffer->move_mark(mark, m_RefTextBuffer->end());
  160. if (m_LogView.get_realized()) m_LogView.scroll_to(mark);
  161. }
  162. void MainWindow::set_ui_locked(bool locked) {
  163. m_ButtonBackup.set_sensitive(!locked);
  164. m_ButtonRestore.set_sensitive(!locked);
  165. m_ButtonSelectVault.set_sensitive(!locked);
  166. m_CheckDebugMode.set_sensitive(!locked);
  167. if (!locked) {
  168. m_StatusLabel.override_color(m_JobSuccess ? Gdk::RGBA("#44ff44") : Gdk::RGBA("#ff4444"));
  169. m_StatusLabel.set_text(m_JobSuccess ? "Job Successful." : "Job Failed.");
  170. }
  171. }
  172. void MainWindow::run_backup_job(JobConfig config, std::string home_dir) {
  173. m_JobSuccess = true; std::error_code ec;
  174. queue_log("--- Starting Backup ---");
  175. char tpl[] = "/tmp/gvault_pack_XXXXXX";
  176. if (mkdtemp(tpl) == nullptr) {
  177. queue_log("!!! ERROR: Failed to create secure temp directory.");
  178. m_JobSuccess = false;
  179. m_WorkerRunning = false;
  180. queue_log("__UNLOCK_UI__");
  181. return;
  182. }
  183. std::string temp_dir(tpl);
  184. auto pack_h = [&](const std::string& p, const std::string& n) {
  185. if (fs::exists(p)) if(!create_tar_archive(p, temp_dir + "/" + n, false)) m_JobSuccess = false;
  186. };
  187. if (config.themes) { pack_h(home_dir + "/.themes", "themes_legacy.tar.gz"); pack_h(home_dir + "/.local/share/themes", "themes_xdg.tar.gz"); }
  188. if (config.icons) { pack_h(home_dir + "/.icons", "icons_legacy.tar.gz"); pack_h(home_dir + "/.local/share/icons", "icons_xdg.tar.gz"); }
  189. if (config.wallpapers) { std::string w = get_wallpaper_directory(); if(!w.empty()) pack_h(w, "wallpapers.tar.gz"); }
  190. if (config.extensions) pack_h(home_dir + "/.local/share/gnome-shell/extensions", "extensions.tar.gz");
  191. if (config.dconf) {
  192. queue_log("[BACKUP] Exporting GNOME Settings...");
  193. if (system(("dconf dump / > '" + temp_dir + "/settings.ini'").c_str()) != 0) m_JobSuccess = false;
  194. }
  195. if(!create_tar_archive(temp_dir, home_dir + "/" + config.vault_name + ".gbk", true)) m_JobSuccess = false;
  196. fs::remove_all(temp_dir, ec);
  197. queue_log("__UNLOCK_UI__");
  198. m_WorkerRunning = false;
  199. }
  200. void MainWindow::on_button_backup_clicked() {
  201. Gtk::MessageDialog dialog(*this, "Vault Name", false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_OK_CANCEL);
  202. Gtk::Entry entry; entry.set_text("GnomeVaultBackup");
  203. dialog.get_content_area()->pack_start(entry, Gtk::PACK_SHRINK);
  204. dialog.show_all_children();
  205. if (dialog.run() == Gtk::RESPONSE_OK) {
  206. m_IsDebugMode = m_CheckDebugMode.get_active();
  207. m_LastJobWasRestore = false;
  208. set_ui_locked(true); m_WorkerRunning = true;
  209. m_StatusLabel.set_text("Backup in progress...");
  210. JobConfig cfg;
  211. cfg.themes = m_CheckThemesBackup.get_active(); cfg.icons = m_CheckIconsBackup.get_active();
  212. cfg.wallpapers = m_CheckWallpapersBackup.get_active(); cfg.extensions = m_CheckExtensionsBackup.get_active();
  213. cfg.dconf = m_CheckDconfBackup.get_active(); cfg.dry_run = false; cfg.vault_name = entry.get_text();
  214. std::thread(&MainWindow::run_backup_job, this, cfg, std::string(std::getenv("HOME"))).detach();
  215. }
  216. }
  217. void MainWindow::run_restore_job(JobConfig config, std::string home_dir) {
  218. m_JobSuccess = true; std::error_code ec;
  219. queue_log("--- Starting Restore ---");
  220. auto settings = Gio::Settings::create("org.gnome.shell");
  221. if (config.extensions && !config.dry_run) settings->set_boolean("disable-user-extensions", true);
  222. char tpl[] = "/tmp/gvault_unpack_XXXXXX";
  223. if (mkdtemp(tpl) == nullptr) {
  224. queue_log("!!! ERROR: Failed to create secure temp directory.");
  225. m_JobSuccess = false;
  226. if (config.extensions && !config.dry_run) settings->set_boolean("disable-user-extensions", false);
  227. m_WorkerRunning = false;
  228. queue_log("__UNLOCK_UI__");
  229. return;
  230. }
  231. std::string temp_unpack(tpl);
  232. if (!extract_tar_archive(config.custom_restore_path, temp_unpack, false, false)) m_JobSuccess = false;
  233. auto atomic_res = [&](const std::string& n, const std::string& lp, const std::string& lbl) {
  234. std::string arch = temp_unpack + "/" + n + ".tar.gz";
  235. if (fs::exists(arch)) {
  236. queue_log("[RESTORE] Swapping " + lbl + "...");
  237. std::string sh = lp + "_vault_new"; std::string od = lp + "_vault_old";
  238. fs::remove_all(sh, ec); fs::remove_all(od, ec); fs::create_directories(sh);
  239. if (extract_tar_archive(arch, sh, config.dry_run, false)) {
  240. if (!config.dry_run) {
  241. sync();
  242. bool had_old = fs::exists(lp);
  243. if (had_old) fs::rename(lp, od, ec);
  244. fs::rename(sh, lp, ec);
  245. if (ec) {
  246. queue_log("!!! FAIL: Rolling back " + lbl);
  247. if (had_old) fs::rename(od, lp, ec);
  248. m_JobSuccess = false;
  249. } else fs::remove_all(od, ec);
  250. }
  251. } else m_JobSuccess = false;
  252. }
  253. };
  254. if (config.themes) { atomic_res("themes_legacy", home_dir + "/.themes", "Themes (Legacy)"); atomic_res("themes_xdg", home_dir + "/.local/share/themes", "Themes (XDG)"); }
  255. if (config.icons) { atomic_res("icons_legacy", home_dir + "/.icons", "Icons (Legacy)"); atomic_res("icons_xdg", home_dir + "/.local/share/icons", "Icons (XDG)"); }
  256. if (config.extensions) atomic_res("extensions", home_dir + "/.local/share/gnome-shell/extensions", "Extensions");
  257. if (config.wallpapers && fs::exists(temp_unpack + "/wallpapers.tar.gz")) {
  258. queue_log("[RESTORE] Restoring Wallpapers...");
  259. if (!extract_tar_archive(temp_unpack + "/wallpapers.tar.gz", "/", config.dry_run, true)) m_JobSuccess = false;
  260. }
  261. if (config.dconf && fs::exists(temp_unpack + "/settings.ini") && !config.dry_run) {
  262. queue_log("[RESTORE] Injecting Dconf...");
  263. if (system(("dconf load / < '" + temp_unpack + "/settings.ini'").c_str()) != 0) m_JobSuccess = false;
  264. }
  265. if (config.extensions && !config.dry_run) settings->set_boolean("disable-user-extensions", false);
  266. fs::remove_all(temp_unpack, ec);
  267. queue_log("__UNLOCK_UI__");
  268. }
  269. void MainWindow::on_button_restore_clicked() {
  270. if (m_SelectedVaultPath.empty()) return;
  271. m_IsDebugMode = m_CheckDebugMode.get_active();
  272. m_LastJobWasRestore = true; set_ui_locked(true); m_WorkerRunning = true;
  273. m_StatusLabel.set_text("Restore in progress...");
  274. JobConfig cfg;
  275. cfg.themes = m_CheckThemesRestore.get_active(); cfg.icons = m_CheckIconsRestore.get_active();
  276. cfg.wallpapers = m_CheckWallpapersRestore.get_active(); cfg.extensions = m_CheckExtensionsRestore.get_active();
  277. cfg.dconf = m_CheckDconfRestore.get_active(); cfg.dry_run = m_CheckDryRunRestore.get_active(); cfg.custom_restore_path = m_SelectedVaultPath;
  278. std::thread(&MainWindow::run_restore_job, this, cfg, std::string(std::getenv("HOME"))).detach();
  279. }
  280. bool MainWindow::create_tar_archive(const std::string& s, const std::string& o, bool strip) {
  281. struct archive *a = archive_write_new();
  282. archive_write_add_filter_gzip(a); archive_write_set_format_pax_restricted(a);
  283. archive_write_open_filename(a, o.c_str());
  284. fs::path bp = fs::absolute(s); bool ok = true;
  285. for (const auto& d : fs::recursive_directory_iterator(bp, fs::directory_options::skip_permission_denied)) {
  286. std::string f = d.path().string(); std::string st = strip ? fs::relative(d.path(), bp).string() : f;
  287. if (st == "." || st == "..") continue;
  288. struct archive_entry *e = archive_entry_new(); archive_entry_set_pathname(e, st.c_str());
  289. struct stat sbuf; if (lstat(f.c_str(), &sbuf) != 0) { archive_entry_free(e); ok = false; continue; }
  290. archive_entry_copy_stat(e, &sbuf);
  291. if (S_ISLNK(sbuf.st_mode)) { char t[4096]; ssize_t l = readlink(f.c_str(), t, 4095); if (l != -1) { t[l]='\0'; archive_entry_set_symlink(e, t); } }
  292. archive_write_header(a, e);
  293. queue_log(" -> Packed: " + st);
  294. if (S_ISREG(sbuf.st_mode)) { int fd = ::open(f.c_str(), O_RDONLY); if (fd >= 0) { char b[65536]; ssize_t l; while ((l = ::read(fd, b, 65536)) > 0) archive_write_data(a, b, l); ::close(fd); } else ok = false; }
  295. archive_entry_free(e);
  296. }
  297. archive_write_close(a); archive_write_free(a); return ok;
  298. }
  299. bool MainWindow::extract_tar_archive(const std::string& ap, const std::string& ds, bool dr, bool abs) {
  300. struct archive *a = archive_read_new();
  301. archive_read_support_format_all(a); archive_read_support_filter_all(a);
  302. if (archive_read_open_filename(a, ap.c_str(), 10240) != ARCHIVE_OK) return false;
  303. struct archive_entry *e; bool ok = true;
  304. while (archive_read_next_header(a, &e) == ARCHIVE_OK) {
  305. std::string sp = archive_entry_pathname(e);
  306. if (!abs) {
  307. size_t p = sp.find("/themes/"); if (p == std::string::npos) p = sp.find("/icons/");
  308. if (p == std::string::npos) p = sp.find("/extensions/");
  309. if (p != std::string::npos) { size_t s = sp.find('/', p + 1); if (s != std::string::npos) sp = sp.substr(s + 1); }
  310. }
  311. std::string t = abs ? archive_entry_pathname(e) : ds + "/" + sp;
  312. archive_entry_set_pathname(e, t.c_str());
  313. if (dr) { queue_log(" -> [DRY] " + t); archive_read_data_skip(a); }
  314. else if (archive_read_extract(a, e, ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_UNLINK) != ARCHIVE_OK) { if (!fs::is_directory(t)) ok = false; }
  315. else queue_log(" -> Restored: " + t);
  316. }
  317. archive_read_close(a); archive_read_free(a); return ok;
  318. }
  319. std::string MainWindow::get_wallpaper_directory() {
  320. char b[256]; std::string r = "";
  321. FILE* p = popen("gsettings get org.gnome.desktop.background picture-uri-dark 2>/dev/null", "r");
  322. if (p) { while (fgets(b, 256, p)) r += b; pclose(p); }
  323. size_t f = r.find("file://");
  324. if (f != std::string::npos) {
  325. std::string path = r.substr(f + 7);
  326. path.erase(std::remove(path.begin(), path.end(), '\''), path.end());
  327. path.erase(std::remove(path.begin(), path.end(), '\n'), path.end());
  328. return fs::path(path).parent_path().string();
  329. }
  330. return "";
  331. }