Skip to content

Commit

Permalink
switch from editor_path to data_path, implement RuleManager for readi…
Browse files Browse the repository at this point in the history
…ng and writing rule files
  • Loading branch information
mwinkens committed Jun 4, 2024
1 parent eae096d commit f3d0ae4
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 20 deletions.
58 changes: 47 additions & 11 deletions src/backend/rule_manager.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from typing import List, Dict
from pathlib import Path
from typing import List, Dict, Optional

from src.backend.tile_connection import TileConnection
from src.backend.tile_handler import TileHandler
from src.backend.tile_status import TileStatus
from src.config.config_manager import ConfigManager
from src.globals import NUM_TILES
from src.widgets.widget_base_tile import BaseTile

Expand All @@ -17,14 +19,24 @@ def __init__(self):

@staticmethod
def _loadRuleFile(filename_base) -> RuleConfig:
# filename = f"{filename_base}.rules"
# TODO check if file exists, if exists, load
# StorageFinder.findRule(filename)
# if exists
# config = ConfigParser()
# config.read(filename)
# else
config = {filename_base: []}
filename = f"{filename_base}.rules"
data_path = Path(ConfigManager.config()["data_path"])
if not data_path:
raise ValueError("No editor directory path known")

automapper_path = data_path.joinpath(Path("editor/automap"))
if not automapper_path.exists():
automapper_path.mkdir()

full_file_path = automapper_path.joinpath(Path(filename))

# load file if it exists
if full_file_path.is_file():
config = RuleManager._readRuleFile(full_file_path)

# file doesn't exist
else:
config = {filename_base: []}
return config

@staticmethod
Expand Down Expand Up @@ -94,8 +106,8 @@ def _createIndexRule(tile_id: int, tile_status: TileStatus):
str_rotate = " ROTATE" if rotate else ""
return f"{str_index}{str_x_flip}{str_y_flip}{str_rotate}"

@classmethod
def _writeRuleFile(cls, filename_base, config: RuleConfig):
@staticmethod
def _writeRuleFile(filename_base, config: RuleConfig):
filename = f"{filename_base}.rules"
with open(filename, 'w') as f:
for key in config.keys():
Expand All @@ -104,3 +116,27 @@ def _writeRuleFile(cls, filename_base, config: RuleConfig):
for line in lines:
f.write(line)
f.write('\n')

@staticmethod
def _readRuleFile(full_file_path: Path) -> RuleConfig:
config = {}

with open(str(full_file_path), 'r', encoding='utf-8') as f:
section: Optional[str] = None

# read file line by line
while line := f.readline():
line = line.rstrip()

# handle sections
if len(line) >= 2 and line[0] == '[' and line[-1] == ']':
section = line[1:-1]
config[section] = []

# handle normal lines
else:
if section:
config[section].append(line)
elif len(line) > 0: # ignore empty lines
raise ValueError("files may contain rules without section, aborting")
return config
4 changes: 2 additions & 2 deletions src/config/config_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ def _init(self):

def createConfig(self):
client_path = StorageFinder.instance().getClientPath()
editor_path = StorageFinder.instance().getEditorPath()
data_path = StorageFinder.instance().getDataPath()
data = {
'version': "1.0.0",
'client_path': str(client_path),
'editor_path': str(editor_path),
'data_path': str(data_path),
}
self._config = data

Expand Down
6 changes: 3 additions & 3 deletions src/config/storage_finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def getClientPath(self):
pass

@abstractmethod
def getEditorPath(self):
def getDataPath(self):
pass


Expand Down Expand Up @@ -102,10 +102,10 @@ def getClientPath(self):
pass
return None

def getEditorPath(self):
def getDataPath(self):
if self.data_path:
try:
p = Path(self.data_path).joinpath("editor")
p = Path(self.data_path)
if p.is_dir():
return p
except OSError:
Expand Down
2 changes: 1 addition & 1 deletion src/dialogs/dialog_config_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def __init__(self, *args):

configs = [
("client_path", "Client path:", QFileDialog.FileMode.ExistingFile),
("editor_path", "Editor directory path:", QFileDialog.FileMode.Directory)
("data_path", "Data directory path:", QFileDialog.FileMode.Directory)
]

index = 0
Expand Down
6 changes: 3 additions & 3 deletions src/widgets/widget_mapper_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,9 @@ def startDDNetCheck(self):
# automap map with debroijn torus
# open map with ddnet
map_name = ""
editor_path = ConfigManager.instance().config()["client_path"]
if not editor_path:
client_path = ConfigManager.instance().config()["client_path"]
if not client_path:
self.ddnet_push_button.setDisabled(True)
return
cmd = [editor_path, map_name]
cmd = [client_path, map_name]
subprocess.Popen(cmd, start_new_session=True)

0 comments on commit f3d0ae4

Please sign in to comment.