Refactor to use pathlib

This commit is contained in:
kramo
2023-04-01 11:33:48 +02:00
parent 397f267522
commit 3bcbf8457c
13 changed files with 169 additions and 266 deletions

View File

@@ -105,22 +105,17 @@ class game(Gtk.Box): # pylint: disable=invalid-name
sys.exit() sys.exit()
def toggle_hidden(self): def toggle_hidden(self):
games_dir = os.path.join( games_dir = self.parent_widget.data_dir / "cartridges" / "games"
os.getenv("XDG_DATA_HOME")
or os.path.expanduser(os.path.join("~", ".local", "share")),
"cartridges",
"games",
)
if not os.path.exists(games_dir): if not games_dir.exists():
return return
with open(os.path.join(games_dir, f"{self.game_id}.json"), "r") as open_file: with open((games_dir / f"{self.game_id}.json") / "r") as open_file:
data = json.loads(open_file.read()) data = json.loads(open_file.read())
data["hidden"] = not data["hidden"] data["hidden"] = not data["hidden"]
save_game(data) save_game(self.parent_widget, data)
def get_cover(self): def get_cover(self):
@@ -129,16 +124,15 @@ class game(Gtk.Box): # pylint: disable=invalid-name
return self.parent_widget.pixbufs[self.game_id] return self.parent_widget.pixbufs[self.game_id]
# Create a new pixbuf # Create a new pixbuf
cover_path = os.path.join( cover_path = (
os.getenv("XDG_DATA_HOME") self.parent_widget.data_dir
or os.path.expanduser(os.path.join("~", ".local", "share")), / "cartridges"
"cartridges", / "covers"
"covers", / f"{self.game_id}.tiff"
f"{self.game_id}.tiff",
) )
if os.path.isfile(cover_path): if cover_path.is_file():
return GdkPixbuf.Pixbuf.new_from_file(cover_path) return GdkPixbuf.Pixbuf.new_from_file(str(cover_path))
# Return the placeholder pixbuf # Return the placeholder pixbuf
return self.parent_widget.placeholder_pixbuf return self.parent_widget.placeholder_pixbuf

View File

@@ -138,9 +138,9 @@ class CartridgesApplication(Adw.Application):
game_id = self.win.active_game_id game_id = self.win.active_game_id
data = get_games([game_id])[game_id] data = get_games(self.win, [game_id])[game_id]
data["last_played"] = int(time.time()) data["last_played"] = int(time.time())
save_game(data) save_game(self.win, data)
self.win.games[game_id].launch() self.win.games[game_id].launch()
@@ -188,9 +188,9 @@ class CartridgesApplication(Adw.Application):
# Add "removed=True" to the game properties so it can be deleted on next init # Add "removed=True" to the game properties so it can be deleted on next init
game_id = self.win.active_game_id game_id = self.win.active_game_id
data = get_games([game_id])[game_id] data = get_games(self.win, [game_id])[game_id]
data["removed"] = True data["removed"] = True
save_game(data) save_game(self.win, data)
self.win.update_games([game_id]) self.win.update_games([game_id])
if self.win.stack.get_visible_child() == self.win.overview: if self.win.stack.get_visible_child() == self.win.overview:

View File

@@ -18,6 +18,7 @@
# SPDX-License-Identifier: GPL-3.0-or-later # SPDX-License-Identifier: GPL-3.0-or-later
import os import os
from pathlib import Path
from gi.repository import Adw, Gio, GLib, Gtk from gi.repository import Adw, Gio, GLib, Gtk
@@ -46,10 +47,7 @@ class ImportPreferences:
if response == "choose_folder": if response == "choose_folder":
window.choose_folder(widget, set_dir) window.choose_folder(widget, set_dir)
if not any( if not any((path / current_path).exists() for current_path in paths):
os.path.exists(os.path.join(path, current_path))
for current_path in paths
):
create_dialog( create_dialog(
window.parent_widget, window.parent_widget,
_("Installation Not Found"), _("Installation Not Found"),
@@ -163,8 +161,8 @@ class PreferencesWindow(Adw.PreferencesWindow):
"steam-location", "steam-location",
[ [
"steamapps", "steamapps",
os.path.join("steam", "steamapps"), Path("steam") / "steamapps",
os.path.join("Steam", "steamapps"), Path("Steam") / "steamapps",
], ],
self.steam_expander_row, self.steam_expander_row,
self.steam_file_chooser_button, self.steam_file_chooser_button,
@@ -209,13 +207,13 @@ class PreferencesWindow(Adw.PreferencesWindow):
def set_cache_dir(_source, result, _unused): def set_cache_dir(_source, result, _unused):
try: try:
path = self.file_chooser.select_folder_finish(result).get_path() path = Path(self.file_chooser.select_folder_finish(result).get_path())
def response(widget, response): def response(widget, response):
if response == "choose_folder": if response == "choose_folder":
self.choose_folder(widget, set_cache_dir) self.choose_folder(widget, set_cache_dir)
if not os.path.exists(os.path.join(path, "coverart")): if not (path / "coverart").exists():
create_dialog( create_dialog(
self.parent_widget, self.parent_widget,
_("Cache Not Found"), _("Cache Not Found"),
@@ -235,6 +233,9 @@ class PreferencesWindow(Adw.PreferencesWindow):
"clicked", self.choose_folder, set_cache_dir "clicked", self.choose_folder, set_cache_dir
) )
if os.name == "nt":
self.sources_group.remove(self.lutris_expander_row)
# Heroic # Heroic
ImportPreferences( ImportPreferences(
self, self,
@@ -285,20 +286,20 @@ class PreferencesWindow(Adw.PreferencesWindow):
def undo_remove_all(self, _widget, _unused): def undo_remove_all(self, _widget, _unused):
for game_id in self.removed_games: for game_id in self.removed_games:
data = get_games([game_id])[game_id] data = get_games(self.parent_widget, [game_id])[game_id]
if "removed" in data: if "removed" in data:
data.pop("removed") data.pop("removed")
save_game(data) save_game(self.parent_widget, data)
self.parent_widget.update_games(self.removed_games) self.parent_widget.update_games(self.removed_games)
self.removed_games = [] self.removed_games = []
self.toast.dismiss() self.toast.dismiss()
def remove_all_games(self, _widget): def remove_all_games(self, _widget):
for game in get_games().values(): for game in get_games(self.parent_widget).values():
if "removed" not in game: if "removed" not in game:
self.removed_games.append(game["game_id"]) self.removed_games.append(game["game_id"])
game["removed"] = True game["removed"] = True
save_game(game) save_game(self.parent_widget, game)
self.parent_widget.update_games(self.parent_widget.games) self.parent_widget.update_games(self.parent_widget.games)
if self.parent_widget.stack.get_visible_child() == self.parent_widget.overview: if self.parent_widget.stack.get_visible_child() == self.parent_widget.overview:

View File

@@ -17,7 +17,7 @@
# #
# SPDX-License-Identifier: GPL-3.0-or-later # SPDX-License-Identifier: GPL-3.0-or-later
import os from pathlib import Path
from time import time from time import time
import yaml import yaml
@@ -25,37 +25,28 @@ import yaml
def bottles_parser(parent_widget): def bottles_parser(parent_widget):
schema = parent_widget.schema schema = parent_widget.schema
bottles_dir = os.path.expanduser(schema.get_string("bottles-location")) bottles_dir = Path(schema.get_string("bottles-location")).expanduser()
if not os.path.isfile(os.path.join(bottles_dir, "library.yml")): if not (bottles_dir / "library.yml").is_file():
if os.path.exists( if (
os.path.expanduser("~/.var/app/com.usebottles.bottles/data/bottles/") Path("~/.var/app/com.usebottles.bottles/data/bottles/")
.expanduser()
.exists()
): ):
schema.set_string( schema.set_string(
"bottles-location", "~/.var/app/com.usebottles.bottles/data/bottles/" "bottles-location", "~/.var/app/com.usebottles.bottles/data/bottles/"
) )
elif os.path.exists( elif (parent_widget.data_dir / "bottles").exists():
os.path.join(
os.getenv("XDG_DATA_HOME")
or os.path.expanduser(os.path.join("~", ".local", "share")),
"bottles",
)
):
schema.set_string( schema.set_string(
"bottles-location", "bottles-location", str(parent_widget.data_dir / "bottles")
os.path.join(
os.getenv("XDG_DATA_HOME")
or os.path.expanduser(os.path.join("~", ".local", "share")),
"bottles",
),
) )
else: else:
return return
bottles_dir = os.path.expanduser(schema.get_string("bottles-location")) bottles_dir = Path(schema.get_string("bottles-location")).expanduser()
current_time = int(time()) current_time = int(time())
with open(os.path.join(bottles_dir, "library.yml"), "r") as open_file: with open((bottles_dir / "library.yml"), "r") as open_file:
data = open_file.read() data = open_file.read()
library = yaml.load(data, Loader=yaml.Loader) library = yaml.load(data, Loader=yaml.Loader)
@@ -90,12 +81,12 @@ def bottles_parser(parent_widget):
if game["thumbnail"]: if game["thumbnail"]:
importer.save_cover( importer.save_cover(
values["game_id"], values["game_id"],
os.path.join( (
bottles_dir, bottles_dir
"bottles", / "bottles"
game["bottle"]["path"], / game["bottle"]["path"]
"grids", / "grids"
game["thumbnail"].split(":")[1], / game["thumbnail"].split(":")[1]
), ),
) )
importer.save_game(values) importer.save_game(values)

View File

@@ -274,23 +274,15 @@ def create_details_window(parent_widget, game_id=None):
values["developer"] = final_developer or None values["developer"] = final_developer or None
values["executable"] = final_executable_split values["executable"] = final_executable_split
path = os.path.join( path = parent_widget.data_dir / "cartridges" / "games" / f"{game_id}.json"
os.path.join(
os.getenv("XDG_DATA_HOME")
or os.path.expanduser(os.path.join("~", ".local", "share")),
"cartridges",
"games",
f"{game_id}.json",
)
)
if os.path.exists(path): if path.exists():
with open(path, "r") as open_file: with open(path, "r") as open_file:
data = json.loads(open_file.read()) data = json.loads(open_file.read())
data.update(values) data.update(values)
save_game(data) save_game(parent_widget, data)
else: else:
save_game(values) save_game(parent_widget, values)
parent_widget.update_games([game_id]) parent_widget.update_games([game_id])
if parent_widget.stack.get_visible_child() == parent_widget.overview: if parent_widget.stack.get_visible_child() == parent_widget.overview:

View File

@@ -18,28 +18,22 @@
# SPDX-License-Identifier: GPL-3.0-or-later # SPDX-License-Identifier: GPL-3.0-or-later
import json import json
import os
def get_games(game_ids=None): def get_games(parent_widget, game_ids=None):
games_dir = os.path.join( games_dir = parent_widget.data_dir / "cartridges" / "games"
os.getenv("XDG_DATA_HOME")
or os.path.expanduser(os.path.join("~", ".local", "share")),
"cartridges",
"games",
)
games = {} games = {}
if not os.path.exists(games_dir): if not games_dir.exists():
return {} return {}
if game_ids: if game_ids:
game_files = [f"{game_id}.json" for game_id in game_ids] game_files = [f"{game_id}.json" for game_id in game_ids]
else: else:
game_files = os.listdir(games_dir) game_files = games_dir.iterdir()
for game in game_files: for game in game_files:
with open(os.path.join(games_dir, game), "r") as open_file: with open((games_dir / game), "r") as open_file:
data = json.loads(open_file.read()) data = json.loads(open_file.read())
games[data["game_id"]] = data games[data["game_id"]] = data

View File

@@ -20,46 +20,36 @@
import hashlib import hashlib
import json import json
import os import os
from pathlib import Path
from time import time from time import time
def heroic_parser(parent_widget): def heroic_parser(parent_widget):
schema = parent_widget.schema schema = parent_widget.schema
heroic_dir = os.path.expanduser(schema.get_string("heroic-location")) heroic_dir = Path(schema.get_string("heroic-location")).expanduser()
if not os.path.exists(os.path.join(heroic_dir, "config.json")): if not (heroic_dir / "config.json").exists():
if os.path.exists( if (
os.path.expanduser("~/.var/app/com.heroicgameslauncher.hgl/config/heroic/") Path("~/.var/app/com.heroicgameslauncher.hgl/config/heroic/")
.expanduser()
.exists()
): ):
schema.set_string( schema.set_string(
"heroic-location", "heroic-location",
"~/.var/app/com.heroicgameslauncher.hgl/config/heroic/", "~/.var/app/com.heroicgameslauncher.hgl/config/heroic/",
) )
elif os.path.exists( elif (parent_widget.config_dir / "heroic").exists():
os.path.join(
os.getenv("XDG_CONFIG_HOME")
or os.path.expanduser(os.path.join("~", ".config")),
"heroic",
)
):
schema.set_string( schema.set_string(
"heroic-location", "heroic-location", str(parent_widget.config_dir / "heroic")
os.path.join(
os.getenv("XDG_CONFIG_HOME")
or os.path.expanduser(os.path.join("~", ".config")),
"heroic",
),
) )
elif os.name == "nt" and os.path.exists( elif os.name == "nt" and (Path(os.getenv("appdata")) / "heroic").exists():
os.path.join(os.getenv("appdata"), "heroic")
):
schema.set_string( schema.set_string(
"heroic-location", os.path.join(os.getenv("appdata"), "heroic") "heroic-location", str(Path((os.getenv("appdata") / "heroic")))
) )
else: else:
return return
heroic_dir = os.path.expanduser(schema.get_string("heroic-location")) heroic_dir = Path(schema.get_string("heroic-location")).expanduser()
current_time = int(time()) current_time = int(time())
importer = parent_widget.importer importer = parent_widget.importer
@@ -67,10 +57,8 @@ def heroic_parser(parent_widget):
# Import Epic games # Import Epic games
if not schema.get_boolean("heroic-import-epic"): if not schema.get_boolean("heroic-import-epic"):
pass pass
elif os.path.exists(os.path.join(heroic_dir, "lib-cache", "library.json")): elif (heroic_dir / "lib-cache" / "library.json").exists():
with open( with open((heroic_dir / "lib-cache" / "library.json"), "r") as open_file:
os.path.join(heroic_dir, "lib-cache", "library.json"), "r"
) as open_file:
data = open_file.read() data = open_file.read()
library = json.loads(data) library = json.loads(data)
@@ -106,14 +94,14 @@ def heroic_parser(parent_widget):
values["added"] = current_time values["added"] = current_time
values["last_played"] = 0 values["last_played"] = 0
image_path = os.path.join( image_path = (
heroic_dir, heroic_dir
"images-cache", / "images-cache"
hashlib.sha256( / hashlib.sha256(
(f'{game["art_square"]}?h=400&resize=1&w=300').encode() (f'{game["art_square"]}?h=400&resize=1&w=300').encode()
).hexdigest(), ).hexdigest()
) )
if os.path.exists(image_path): if image_path.exists():
importer.save_cover(values["game_id"], image_path) importer.save_cover(values["game_id"], image_path)
importer.save_game(values) importer.save_game(values)
@@ -123,10 +111,8 @@ def heroic_parser(parent_widget):
# Import GOG games # Import GOG games
if not schema.get_boolean("heroic-import-gog"): if not schema.get_boolean("heroic-import-gog"):
pass pass
elif os.path.exists(os.path.join(heroic_dir, "gog_store", "installed.json")): elif (heroic_dir / "gog_store" / "installed.json").exists():
with open( with open((heroic_dir / "gog_store" / "installed.json"), "r") as open_file:
os.path.join(heroic_dir, "gog_store", "installed.json"), "r"
) as open_file:
data = open_file.read() data = open_file.read()
installed = json.loads(data) installed = json.loads(data)
@@ -147,21 +133,19 @@ def heroic_parser(parent_widget):
continue continue
# Get game title and developer from library.json as they are not present in installed.json # Get game title and developer from library.json as they are not present in installed.json
with open( with open((heroic_dir / "gog_store" / "library.json"), "r") as open_file:
os.path.join(heroic_dir, "gog_store", "library.json"), "r"
) as open_file:
data = open_file.read() data = open_file.read()
library = json.loads(data) library = json.loads(data)
for game in library["games"]: for game in library["games"]:
if game["app_name"] == app_name: if game["app_name"] == app_name:
values["developer"] = game["developer"] values["developer"] = game["developer"]
values["name"] = game["title"] values["name"] = game["title"]
image_path = os.path.join( image_path = (
heroic_dir, heroic_dir
"images-cache", / "images-cache"
hashlib.sha256(game["art_square"].encode()).hexdigest(), / hashlib.sha256(game["art_square"].encode()).hexdigest()
) )
if os.path.exists(image_path): if image_path.exists():
importer.save_cover(values["game_id"], image_path) importer.save_cover(values["game_id"], image_path)
break break
@@ -180,10 +164,8 @@ def heroic_parser(parent_widget):
# Import sideloaded games # Import sideloaded games
if not schema.get_boolean("heroic-import-sideload"): if not schema.get_boolean("heroic-import-sideload"):
pass pass
elif os.path.exists(os.path.join(heroic_dir, "sideload_apps", "library.json")): elif (heroic_dir / "sideload_apps" / "library.json").exists():
with open( with open((heroic_dir / "sideload_apps" / "library.json"), "r") as open_file:
os.path.join(heroic_dir, "sideload_apps", "library.json"), "r"
) as open_file:
data = open_file.read() data = open_file.read()
library = json.loads(data) library = json.loads(data)
@@ -213,12 +195,12 @@ def heroic_parser(parent_widget):
values["source"] = "heroic_sideload" values["source"] = "heroic_sideload"
values["added"] = current_time values["added"] = current_time
values["last_played"] = 0 values["last_played"] = 0
image_path = os.path.join( image_path = (
heroic_dir, heroic_dir
"images-cache", / "images-cache"
hashlib.sha256(item["art_square"].encode()).hexdigest(), / hashlib.sha256(item["art_square"].encode()).hexdigest()
) )
if os.path.exists(image_path): if image_path.extsts():
importer.save_cover(values["game_id"], image_path) importer.save_cover(values["game_id"], image_path)
importer.save_game(values) importer.save_game(values)

View File

@@ -55,7 +55,7 @@ class Importer:
def save_game(self, values=None): def save_game(self, values=None):
if values: if values:
self.games_no += 1 self.games_no += 1
save_game(values) save_game(self.parent_widget, values)
self.parent_widget.update_games([values["game_id"]]) self.parent_widget.update_games([values["game_id"]])
if "blacklisted" in values: if "blacklisted" in values:
self.games_no -= 1 self.games_no -= 1

View File

@@ -17,8 +17,7 @@
# #
# SPDX-License-Identifier: GPL-3.0-or-later # SPDX-License-Identifier: GPL-3.0-or-later
import os from pathlib import Path
import shutil
from sqlite3 import connect from sqlite3 import connect
from time import time from time import time
@@ -27,73 +26,40 @@ def lutris_parser(parent_widget):
schema = parent_widget.schema schema = parent_widget.schema
database_path = os.path.join( database_path = (Path(schema.get_string("lutris-location")) / "pga.db").expanduser()
os.path.expanduser(schema.get_string("lutris-location")), "pga.db" if not database_path.is_file():
) if Path("~/.var/app/net.lutris.Lutris/data/lutris/").expanduser().exists():
if not os.path.isfile(database_path):
if os.path.exists(
os.path.expanduser("~/.var/app/net.lutris.Lutris/data/lutris/")
):
schema.set_string( schema.set_string(
"lutris-location", "~/.var/app/net.lutris.Lutris/data/lutris/" "lutris-location", "~/.var/app/net.lutris.Lutris/data/lutris/"
) )
elif os.path.exists( elif (parent_widget.data_dir / "lutris").exists():
os.path.join( schema.set_string("lutris-location", str(parent_widget.data_dir / "lutris"))
os.getenv("XDG_DATA_HOME")
or os.path.expanduser(os.path.join("~", ".local", "share")),
"lutris",
)
):
schema.set_string(
"lutris-location",
os.path.join(
os.getenv("XDG_DATA_HOME")
or os.path.expanduser(os.path.join("~", ".local", "share")),
"lutris",
),
)
else: else:
return return
cache_dir = os.path.expanduser(schema.get_string("lutris-cache-location")) cache_dir = Path(schema.get_string("lutris-cache-location")).expanduser()
if not os.path.exists(cache_dir): if not cache_dir.exists():
if os.path.exists( if Path("~/.var/app/net.lutris.Lutris/cache/lutris/").expanduser().exists():
os.path.expanduser("~/.var/app/net.lutris.Lutris/cache/lutris/")
):
schema.set_string( schema.set_string(
"lutris-cache-location", "~/.var/app/net.lutris.Lutris/cache/lutris/" "lutris-cache-location", "~/.var/app/net.lutris.Lutris/cache/lutris/"
) )
elif os.path.exists( elif (parent_widget.cache_dir / "lutris").exists():
os.path.join(
os.getenv("XDG_CACHE_HOME")
or os.path.expanduser(os.path.join("~", ".cache")),
"lutris",
)
):
schema.set_string( schema.set_string(
"lutris-cache-location", "lutris-cache-location", str(parent_widget.cache_dir / "lutris")
os.path.join(
os.getenv("XDG_CACHE_HOME")
or os.path.expanduser(os.path.join("~", ".cache")),
"lutris",
),
) )
else: else:
return return
database_path = os.path.join( database_path = Path(schema.get_string("lutris-location")) / "pga.db"
os.path.expanduser(schema.get_string("lutris-location")), "pga.db" database_path.expanduser()
) cache_dir = Path(schema.get_string("lutris-cache-location")).expanduser()
cache_dir = os.path.expanduser(schema.get_string("lutris-cache-location"))
db_cache_dir = os.path.join( db_cache_dir = parent_widget.cache_dir / "cartridges" / "lutris"
os.getenv("XDG_CACHE_HOME") or os.path.expanduser(os.path.join("~", ".cache")), db_cache_dir.mkdir(parents=True, exist_ok=True)
"cartridges",
"lutris",
)
os.makedirs(db_cache_dir, exist_ok=True)
shutil.copyfile(database_path, os.path.join(db_cache_dir, "pga.db")) database_link_path = db_cache_dir / "pga.db"
database_link_path.unlink(True)
database_link_path.symlink_to(database_path)
db_request = """ db_request = """
SELECT SELECT
@@ -108,7 +74,7 @@ def lutris_parser(parent_widget):
; ;
""" """
connection = connect(os.path.join(db_cache_dir, "pga.db")) connection = connect(database_link_path)
cursor = connection.execute(db_request) cursor = connection.execute(db_request)
rows = cursor.fetchall() rows = cursor.fetchall()
connection.close() connection.close()
@@ -141,9 +107,9 @@ def lutris_parser(parent_widget):
values["name"] = row[1] values["name"] = row[1]
values["source"] = f"lutris_{row[3]}" values["source"] = f"lutris_{row[3]}"
if os.path.isfile(os.path.join(cache_dir, "coverart", f"{row[2]}.jpg")): if (cache_dir / "coverart" / f"{row[2]}.jpg").is_file():
importer.save_cover( importer.save_cover(
values["game_id"], os.path.join(cache_dir, "coverart", f"{row[2]}.jpg") values["game_id"], (cache_dir / "coverart" / f"{row[2]}.jpg")
) )
importer.save_game(values) importer.save_game(values)

View File

@@ -17,28 +17,24 @@
# #
# SPDX-License-Identifier: GPL-3.0-or-later # SPDX-License-Identifier: GPL-3.0-or-later
import os
from gi.repository import GdkPixbuf, Gio from gi.repository import GdkPixbuf, Gio
def save_cover(parent_widget, game_id, cover_path, pixbuf=None): def save_cover(parent_widget, game_id, cover_path, pixbuf=None):
covers_dir = os.path.join( covers_dir = parent_widget.data_dir / "cartridges" / "covers"
os.getenv("XDG_DATA_HOME")
or os.path.expanduser(os.path.join("~", ".local", "share")),
"cartridges",
"covers",
)
os.makedirs(covers_dir, exist_ok=True) covers_dir.mkdir(parents=True, exist_ok=True)
if pixbuf is None: if pixbuf is None:
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(cover_path, 400, 600, False) pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(
str(cover_path), 400, 600, False
)
def cover_callback(*_unused): def cover_callback(*_unused):
pass pass
open_file = Gio.File.new_for_path(os.path.join(covers_dir, f"{game_id}.tiff")) open_file = Gio.File.new_for_path(str(covers_dir / f"{game_id}.tiff"))
parent_widget.pixbufs[game_id] = pixbuf parent_widget.pixbufs[game_id] = pixbuf
pixbuf.save_to_streamv_async( pixbuf.save_to_streamv_async(
open_file.replace(None, False, Gio.FileCreateFlags.NONE), open_file.replace(None, False, Gio.FileCreateFlags.NONE),

View File

@@ -18,18 +18,12 @@
# SPDX-License-Identifier: GPL-3.0-or-later # SPDX-License-Identifier: GPL-3.0-or-later
import json import json
import os
def save_game(game): def save_game(parent_widget, game):
games_dir = os.path.join( games_dir = parent_widget.data_dir / "cartridges" / "games"
os.getenv("XDG_DATA_HOME")
or os.path.expanduser(os.path.join("~", ".local", "share")),
"cartridges",
"games",
)
os.makedirs(games_dir, exist_ok=True) games_dir.mkdir(parents=True, exist_ok=True)
with open(os.path.join(games_dir, f'{game["game_id"]}.json'), "w") as open_file: with open((games_dir / f'{game["game_id"]}.json'), "w") as open_file:
open_file.write(json.dumps(game, indent=4, sort_keys=True)) open_file.write(json.dumps(game, indent=4, sort_keys=True))

View File

@@ -21,6 +21,7 @@ import json
import os import os
import re import re
import urllib.request import urllib.request
from pathlib import Path
from time import time from time import time
from gi.repository import Gio, GLib from gi.repository import Gio, GLib
@@ -89,21 +90,19 @@ def get_game(
if content: if content:
values = update_values_from_data(content, values) values = update_values_from_data(content, values)
if os.path.isfile( if (
os.path.join( steam_dir
steam_dir, / "appcache"
"appcache", / "librarycache"
"librarycache", / f'{values["appid"]}_library_600x900.jpg'
f'{values["appid"]}_library_600x900.jpg', ).is_file():
)
):
importer.save_cover( importer.save_cover(
values["game_id"], values["game_id"],
os.path.join( (
steam_dir, steam_dir
"appcache", / "appcache"
"librarycache", / "librarycache"
f'{values["appid"]}_library_600x900.jpg', / f'{values["appid"]}_library_600x900.jpg'
), ),
) )
@@ -151,49 +150,48 @@ def get_games_async(parent_widget, appmanifests, steam_dir, importer):
def steam_parser(parent_widget): def steam_parser(parent_widget):
schema = parent_widget.schema schema = parent_widget.schema
steam_dir = os.path.expanduser(schema.get_string("steam-location")) steam_dir = Path(schema.get_string("steam-location")).expanduser()
def steam_not_found(): def steam_not_found():
if os.path.exists( if Path("~/.var/app/com.valvesoftware.Steam/data/Steam/").expanduser().exists():
os.path.expanduser("~/.var/app/com.valvesoftware.Steam/data/Steam/")
):
schema.set_string( schema.set_string(
"steam-location", "~/.var/app/com.valvesoftware.Steam/data/Steam/" "steam-location", "~/.var/app/com.valvesoftware.Steam/data/Steam/"
) )
elif os.path.exists(os.path.expanduser("~/.steam/steam/")): elif Path("~/.steam/steam/").expanduser().exists():
schema.set_string("steam-location", "~/.steam/steam/") schema.set_string("steam-location", "~/.steam/steam/")
elif os.name == "nt" and os.path.exists( elif (
os.path.join(os.getenv("programfiles(x86)"), "Steam") os.name == "nt"
and (Path((os.getenv("programfiles(x86)"))) / "Steam").exists()
): ):
schema.set_string( schema.set_string(
"steam-location", os.path.join(os.getenv("programfiles(x86)"), "Steam") "steam-location", str(Path(os.getenv("programfiles(x86)")) / "Steam")
) )
if os.path.exists(os.path.join(steam_dir, "steamapps")): if (steam_dir / "steamapps").exists():
pass pass
elif os.path.exists(os.path.join(steam_dir, "steam", "steamapps")): elif (steam_dir / "steam" / "steamapps").exists():
schema.set_string("steam-location", os.path.join(steam_dir, "steam")) schema.set_string("steam-location", str(steam_dir / "steam"))
elif os.path.exists(os.path.join(steam_dir, "Steam", "steamapps")): elif (steam_dir / "Steam" / "steamapps").exists():
schema.set_string("steam-location", os.path.join(steam_dir, "Steam")) schema.set_string("steam-location", str(steam_dir / "Steam"))
else: else:
steam_not_found() steam_not_found()
steam_parser(parent_widget) steam_parser(parent_widget)
return return
steam_dir = os.path.expanduser(schema.get_string("steam-location")) steam_dir = Path(schema.get_string("steam-location")).expanduser()
appmanifests = [] appmanifests = []
steam_dirs = schema.get_strv("steam-extra-dirs") steam_dirs = schema.get_strv("steam-extra-dirs")
steam_dirs.append(steam_dir) steam_dirs.append(steam_dir)
for directory in steam_dirs: for directory in steam_dirs:
if not os.path.exists(os.path.join(directory, "steamapps")): if not (directory / "steamapps").exists():
steam_dirs.remove(directory) steam_dirs.remove(directory)
for directory in steam_dirs: for directory in steam_dirs:
for open_file in os.listdir(os.path.join(directory, "steamapps")): for open_file in (directory / "steamapps").iterdir():
path = os.path.join(directory, "steamapps", open_file) path = directory / "steamapps" / open_file
if os.path.isfile(path) and "appmanifest" in open_file: if path.is_file() and "appmanifest" in open_file.name:
appmanifests.append(path) appmanifests.append(path)
importer = parent_widget.importer importer = parent_widget.importer

View File

@@ -19,6 +19,7 @@
import datetime import datetime
import os import os
from pathlib import Path
from gi.repository import Adw, GdkPixbuf, Gio, GLib, Gtk from gi.repository import Adw, GdkPixbuf, Gio, GLib, Gtk
@@ -68,6 +69,12 @@ class CartridgesWindow(Adw.ApplicationWindow):
def __init__(self, **kwargs): def __init__(self, **kwargs):
super().__init__(**kwargs) super().__init__(**kwargs)
self.data_dir = (
Path(os.getenv("XDG_DATA_HOME")) or Path.home() / ".local" / "share"
)
self.config_dir = Path(os.getenv("XDG_CONFIG_HOME")) or Path.home() / ".config"
self.cache_dir = Path(os.getenv("XDG_CACHE_HOME")) or Path.home() / ".cache"
self.games = {} self.games = {}
self.visible_widgets = {} self.visible_widgets = {}
self.hidden_widgets = {} self.hidden_widgets = {}
@@ -85,35 +92,23 @@ class CartridgesWindow(Adw.ApplicationWindow):
self.placeholder_pixbuf = GdkPixbuf.Pixbuf.new_from_resource_at_scale( self.placeholder_pixbuf = GdkPixbuf.Pixbuf.new_from_resource_at_scale(
"/hu/kramo/Cartridges/library_placeholder.svg", 400, 600, False "/hu/kramo/Cartridges/library_placeholder.svg", 400, 600, False
) )
current_games = get_games() current_games = get_games(self)
for current_game in current_games: for current_game in current_games:
if "removed" in current_games[current_game]: if "removed" in current_games[current_game]:
os.remove( (
os.path.join( self.data_dir / "cartridges" / "games" / f"{current_game}.json"
os.getenv("XDG_DATA_HOME") ).remove()
or os.path.expanduser(os.path.join("~", ".local", "share")),
"cartridges",
"games",
f"{current_game}.json",
)
)
try: try:
os.remove( (
os.path.join( self.data_dir / "cartridges" / "covers" / f"{current_game}.tiff"
os.getenv("XDG_DATA_HOME") ).remove()
or os.path.expanduser(os.path.join("~", ".local", "share")),
"cartridges",
"covers",
f"{current_game}.tiff",
)
)
except FileNotFoundError: except FileNotFoundError:
pass pass
self.library.set_filter_func(self.search_filter) self.library.set_filter_func(self.search_filter)
self.hidden_library.set_filter_func(self.hidden_search_filter) self.hidden_library.set_filter_func(self.hidden_search_filter)
self.update_games(get_games()) self.update_games(get_games(self))
# Connect signals # Connect signals
self.search_entry.connect("search-changed", self.search_changed, False) self.search_entry.connect("search-changed", self.search_changed, False)
@@ -124,7 +119,7 @@ class CartridgesWindow(Adw.ApplicationWindow):
self.add_controller(back_mouse_button) self.add_controller(back_mouse_button)
def update_games(self, games): def update_games(self, games):
current_games = get_games() current_games = get_games(self)
for game_id in games: for game_id in games:
if game_id in self.visible_widgets: if game_id in self.visible_widgets:
@@ -420,9 +415,9 @@ class CartridgesWindow(Adw.ApplicationWindow):
game_id = list(self.toasts)[-1] game_id = list(self.toasts)[-1]
except IndexError: except IndexError:
return return
data = get_games([game_id])[game_id] data = get_games(self, [game_id])[game_id]
data.pop("removed", None) data.pop("removed", None)
save_game(data) save_game(self, data)
self.update_games([game_id]) self.update_games([game_id])
self.toasts[game_id].dismiss() self.toasts[game_id].dismiss()
self.toasts.pop(game_id) self.toasts.pop(game_id)