summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSimeon Simeonov2026-06-05 07:11:03 +0200
committerSimeon Simeonov2026-06-05 07:11:03 +0200
commit742fcdfabaeed8f9f70e14165cc9740f5b17d5a8 (patch)
tree7ac25ffe633cf6d36ead4e8cf2cce9f230936f6e
parent7b66519eb4ebe119e5fdc9c1eb6a11fdfab9b7bf (diff)
Add support for storing data permanently
-rw-r--r--.ruff.toml49
-rw-r--r--README.md3
-rw-r--r--README.rst12
-rw-r--r--pyproject.toml6
-rw-r--r--src/scorecounter/__init__.py1
-rw-r--r--src/scorecounter/app.py109
-rw-r--r--tests/__init__.py0
-rw-r--r--tests/scorecounter.py35
-rw-r--r--tests/test_app.py3
9 files changed, 94 insertions, 124 deletions
diff --git a/.ruff.toml b/.ruff.toml
index 956737c..9018176 100644
--- a/.ruff.toml
+++ b/.ruff.toml
@@ -4,57 +4,29 @@ line-length = 79
4target-version = "py314" 4target-version = "py314"
5 5
6[lint] 6[lint]
7select = ["ALL", "D101", "D102", "D103", "D104"] 7select = ["ALL"]
8ignore = [ 8ignore = [
9 "ANN",
10 "BLE001", 9 "BLE001",
11 "COM812", 10 "COM812",
12 "D", 11 "D2",
13 "EM101", # Exception must not use a string literal, assign to variable first 12 "D4",
14 "EM102", # Exception must not use an f-string literal, assign to variable first
15 "ERA001",
16 #"FBT001",
17 #"FBT002",
18 #"INP001",
19 #"ISC001",
20 #"N802",
21 #"N806",
22 #"PLR2004",
23 # "PTH111",
24 # "PTH123",
25 "RUF012",
26 #"RUF013",
27 #"S101",
28 "S308",
29 #"T201",
30 "TRY003",
31 "TRY300",
32 #"UP020"
33] 13]
34 14
35# C901 - `outside_temperature` is too complex (12 > 10) 15# ARG005 - Unused lambda argument: `args`
16# BLE001 - Do not catch blind exception: `Exception`
36# D101 - Missing docstring in public class 17# D101 - Missing docstring in public class
37# D102 - Missing docstring in public method 18# D102 - Missing docstring in public method
38# D200 - One-line docstring should fit on one line 19# E721 - Use `is` and `is not` for type comparisons, or `isinstance()` for isinstance checks
39# D203 - 1 blank line required before class docstring
40# D205 - 1 blank line required between summary line and description
41# D403 - First word of the first line should be capitalized: `str` -> `Str`
42# ERA001 - Found commented-out code 20# ERA001 - Found commented-out code
43# FBT001 - Boolean-typed positional argument in function definition 21# FBT001 - Boolean-typed positional argument in function definition
44# FBT002 - Boolean default positional argument in function definition 22# FBT002 - Boolean default positional argument in function definition
45# INP001 - File `beinc_weechat.py` is part of an implicit namespace package. Add an `__init__.py` 23# INP001 - File `beinc_weechat.py` is part of an implicit namespace package. Add an `__init__.py`
46# N802 - Function name `do_GET` should be lowercase 24# PT008 - Use `return_value=` instead of patching with `lambda`
47# N806 - Variable `POST_data` in function should be lowercase
48# PTH111 - `os.path.expanduser()` should be replaced by `Path.expanduser()`
49# PTH123 - `open()` should be replaced by `Path.open()`
50# PLR0912 - Too many branches (13 > 12)
51# PLR0913 - Too many arguments in function definition (6 > 5)
52# PLR2004 - Magic value used in comparison, consider replacing `200` with a constant variable 25# PLR2004 - Magic value used in comparison, consider replacing `200` with a constant variable
53# RUF012 - Mutable class attributes should be annotated with `typing.ClassVar` 26# RUF012 - Mutable class attributes should be annotated with `typing.ClassVar`
54# RUF013 - PEP 484 prohibits implicit `Optional` 27# RUF013 - PEP 484 prohibits implicit `Optional`
55# S101 - Use of `assert` detected 28# S101 - Use of `assert` detected
56# S308 - Use of `mark_safe` may expose cross-site scripting vulnerabilities 29# S324 - Probable use of insecure hash functions in `hashlib`: `md5`
57# S603 - `subprocess` call: check for execution of untrusted input
58# T201 - `print` found 30# T201 - `print` found
59# TRY003 - Avoid specifying long messages outside the exception class 31# TRY003 - Avoid specifying long messages outside the exception class
60# TRY300 - Consider moving this statement to an `else` block 32# TRY300 - Consider moving this statement to an `else` block
@@ -75,7 +47,7 @@ indent-style = "space"
75skip-magic-trailing-comma = true 47skip-magic-trailing-comma = true
76 48
77# Like Black, automatically detect the appropriate line ending. 49# Like Black, automatically detect the appropriate line ending.
78line-ending = "lf" 50line-ending = "auto"
79 51
80# Enable auto-formatting of code examples in docstrings. Markdown, 52# Enable auto-formatting of code examples in docstrings. Markdown,
81# reStructuredText code/literal blocks and doctests are all supported. 53# reStructuredText code/literal blocks and doctests are all supported.
@@ -93,6 +65,3 @@ docstring-code-line-length = "dynamic"
93 65
94[lint.flake8-quotes] 66[lint.flake8-quotes]
95inline-quotes = "single" 67inline-quotes = "single"
96
97[lint.isort]
98split-on-trailing-comma = false
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..ccff7b1
--- /dev/null
+++ b/README.md
@@ -0,0 +1,3 @@
1# scorecounter
2
3*scorecounter* is a simple score counting app written in Python.
diff --git a/README.rst b/README.rst
deleted file mode 100644
index 9316f3e..0000000
--- a/README.rst
+++ /dev/null
@@ -1,12 +0,0 @@
1scorecounter
2============
3
4**This cross-platform app was generated by** `Briefcase`_ **- part of**
5`The BeeWare Project`_. **If you want to see more tools like Briefcase, please
6consider** `becoming a financial member of BeeWare`_.
7
8Simple application for counting scores for two teams
9
10.. _`Briefcase`: https://briefcase.readthedocs.io/
11.. _`The BeeWare Project`: https://beeware.org/
12.. _`becoming a financial member of BeeWare`: https://beeware.org/contributing/membership
diff --git a/pyproject.toml b/pyproject.toml
index 29103c1..449c6ee 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -2,9 +2,10 @@
2[tool.briefcase] 2[tool.briefcase]
3project_name = "scorecounter" 3project_name = "scorecounter"
4bundle = "org.pichove" 4bundle = "org.pichove"
5version = "1.1.0" 5version = "1.2.0"
6url = "https://simeon.simeonov.no" 6url = "https://simeon.simeonov.no"
7license.file = "LICENSE" 7license = "GPL-3.0-or-later"
8license-files = ["LICENSE"]
8author = "Simeon Simeonov" 9author = "Simeon Simeonov"
9author_email = "sgs@pichove.org" 10author_email = "sgs@pichove.org"
10 11
@@ -191,4 +192,3 @@ build_gradle_dependencies = [
191requires = [ 192requires = [
192 "toga-web~=0.5.0", 193 "toga-web~=0.5.0",
193] 194]
194
diff --git a/src/scorecounter/__init__.py b/src/scorecounter/__init__.py
index e69de29..9bb96e2 100644
--- a/src/scorecounter/__init__.py
+++ b/src/scorecounter/__init__.py
@@ -0,0 +1 @@
"""scorecounter package"""
diff --git a/src/scorecounter/app.py b/src/scorecounter/app.py
index fecdf9d..124ae35 100644
--- a/src/scorecounter/app.py
+++ b/src/scorecounter/app.py
@@ -1,20 +1,31 @@
1"""Simple score counter for two teams""" 1"""Simple score counter for two teams"""
2 2
3import dataclasses
4import json
5
3import toga 6import toga
4from toga.colors import BLUE, RED, WHITE 7from toga.colors import BLUE, RED, WHITE
5from toga.constants import COLUMN, ROW 8from toga.constants import COLUMN, ROW
6 9
7 10
11@dataclasses.dataclass
12class ScoreCounterTeam:
13 """A dataclass that represents the state of a team"""
14
15 name: str
16 score: int
17
18 def to_dict(self) -> dict:
19 """Returns a dictionary representation of the object"""
20 return {'name': self.name, 'score': self.score}
21
22
8class ScoreCounter(toga.App): 23class ScoreCounter(toga.App):
9 """The main ScoreCounter application""" 24 """The main ScoreCounter application"""
10 25
11 def startup(self): 26 def startup(self) -> None:
12 """startup entry point""" 27 """startup entry point"""
13 self._score_team1 = 0 28 self._team1, self._team2 = self.load_teams()
14 self._score_team2 = 0
15
16 self._name_team1 = 'Team 1'
17 self._name_team2 = 'Team 2'
18 29
19 self.main_window = toga.MainWindow( 30 self.main_window = toga.MainWindow(
20 title=self.formal_name, on_resize=self.cb_main_window_resize 31 title=self.formal_name, on_resize=self.cb_main_window_resize
@@ -35,44 +46,48 @@ class ScoreCounter(toga.App):
35 46
36 self.main_window.show() 47 self.main_window.show()
37 48
38 def cb_clear(self, _widget): 49 def cb_clear(self, _widget: toga.Widget) -> None:
39 """Clear on press callback""" 50 """Clear on press callback"""
40 self._score_team1 = 0 51 self._team1.score = 0
41 self._score_team2 = 0 52 self._team2.score = 0
53 self.save()
42 self.refresh() 54 self.refresh()
43 55
44 def cb_score_team1(self, _widget): 56 def cb_score_team1(self, _widget: toga.Widget) -> None:
45 """Team1 on press callback""" 57 """Team1 on press callback"""
46 self._score_team1 += 1 58 self._team1.score += 1
59 self.save()
47 self.refresh() 60 self.refresh()
48 61
49 def cb_score_team2(self, _widget): 62 def cb_score_team2(self, _widget: toga.Widget) -> None:
50 """Team 2 on press callback""" 63 """Team 2 on press callback"""
51 self._score_team2 += 1 64 self._team2.score += 1
65 self.save()
52 self.refresh() 66 self.refresh()
53 67
54 def cb_main_window_resize(self, widget) -> None: 68 def cb_main_window_resize(self, widget: toga.Widget) -> None:
55 """On main window resize callback""" 69 """On main window resize callback"""
56 self._button_team1.style.height = int(widget.size.height / 5) 70 self._button_team1.style.height = int(widget.size.height / 5)
57 self._button_team2.style.height = int(widget.size.height / 5) 71 self._button_team2.style.height = int(widget.size.height / 5)
58 72
59 def cb_set(self, _widget): 73 def cb_set(self, _widget: toga.Widget) -> None:
60 """Set the settings callback""" 74 """Set the settings callback"""
61 self._name_team1 = self._input_team1.value 75 self._team1.name = self._input_team1.value
62 self._name_team2 = self._input_team2.value 76 self._team2.name = self._input_team2.value
77 self.save()
63 self.refresh() 78 self.refresh()
64 self._draw_main_view() 79 self._draw_main_view()
65 80
66 def cb_settings(self, _widget): 81 def cb_settings(self, _widget: toga.Widget) -> None:
67 """Create settings window menu""" 82 """Create settings window menu"""
68 self._input_team1 = toga.TextInput(flex=1, value=self._name_team1) 83 self._input_team1 = toga.TextInput(flex=1, value=self._team1.name)
69 box_team1 = toga.Box( 84 box_team1 = toga.Box(
70 direction=ROW, 85 direction=ROW,
71 margin=5, 86 margin=5,
72 children=[toga.Label('Team 1:', margin=5), self._input_team1], 87 children=[toga.Label('Team 1:', margin=5), self._input_team1],
73 ) 88 )
74 89
75 self._input_team2 = toga.TextInput(flex=1, value=self._name_team2) 90 self._input_team2 = toga.TextInput(flex=1, value=self._team2.name)
76 box_team2 = toga.Box( 91 box_team2 = toga.Box(
77 direction=ROW, 92 direction=ROW,
78 margin=5, 93 margin=5,
@@ -93,24 +108,56 @@ class ScoreCounter(toga.App):
93 children=[box_team1, box_team2, toga.Box(flex=1), button_box], 108 children=[box_team1, box_team2, toga.Box(flex=1), button_box],
94 ) 109 )
95 110
96 def refresh(self): 111 def load_teams(self) -> tuple[ScoreCounterTeam, ScoreCounterTeam]:
112 """
113 Loads the teams from config of config exists
114
115 Default teams are returned if config doesn't exist
116
117 :return: Tuple of 2 teams
118 :rtype: tuple
119 """
120 config_path = self.paths.config / 'scorecounter_config.json'
121
122 try:
123 with config_path.open('r', encoding='utf-8') as fp:
124 config_dict = json.load(fp)
125 return (
126 ScoreCounterTeam(**config_dict['team1']),
127 ScoreCounterTeam(**config_dict['team2']),
128 )
129 except Exception:
130 return (
131 ScoreCounterTeam(name='Team Red', score=0),
132 ScoreCounterTeam(name='Team Blue', score=0),
133 )
134
135 def refresh(self) -> None:
97 """Refreshes the score labels""" 136 """Refreshes the score labels"""
98 self._button_team1.text = f'{self._name_team1} (+1)' 137 self._button_team1.text = f'{self._team1.name} (+1)'
99 self._button_team2.text = f'{self._name_team2} (+1)' 138 self._button_team2.text = f'{self._team2.name} (+1)'
100 self._score_label1.text = f'{self._name_team1}: {self._score_team1}' 139 self._score_label1.text = f'{self._team1.name}: {self._team1.score}'
101 self._score_label2.text = f'{self._name_team2}: {self._score_team2}' 140 self._score_label2.text = f'{self._team2.name}: {self._team2.score}'
141
142 def save(self) -> None:
143 """Saves the teams to storage"""
144 data = {'team1': self._team1.to_dict(), 'team2': self._team2.to_dict()}
145
146 config_path = self.paths.config / 'scorecounter_config.json'
147 with config_path.open('w', encoding='utf-8') as fp:
148 json.dump(data, fp, indent=4)
102 149
103 def _draw_main_view(self): 150 def _draw_main_view(self) -> None:
104 """Draws the main view in the main window""" 151 """Draws the main view in the main window"""
105 self._score_label1 = toga.Label( 152 self._score_label1 = toga.Label(
106 f'{self._name_team1}: {self._score_team1}', 153 f'{self._team1.name}: {self._team1.score}',
107 margin=(0, 5), 154 margin=(0, 5),
108 color=RED, 155 color=RED,
109 font_weight='bold', 156 font_weight='bold',
110 font_size=24, 157 font_size=24,
111 ) 158 )
112 self._score_label2 = toga.Label( 159 self._score_label2 = toga.Label(
113 f'{self._name_team2}: {self._score_team2}', 160 f'{self._team2.name}: {self._team2.score}',
114 margin=(0, 5), 161 margin=(0, 5),
115 color=BLUE, 162 color=BLUE,
116 font_weight='bold', 163 font_weight='bold',
@@ -124,7 +171,7 @@ class ScoreCounter(toga.App):
124 ) 171 )
125 172
126 self._button_team1 = toga.Button( 173 self._button_team1 = toga.Button(
127 f'{self._name_team1} (+1)', 174 f'{self._team1.name} (+1)',
128 on_press=self.cb_score_team1, 175 on_press=self.cb_score_team1,
129 background_color=RED, 176 background_color=RED,
130 flex=1, 177 flex=1,
@@ -132,7 +179,7 @@ class ScoreCounter(toga.App):
132 color=WHITE, 179 color=WHITE,
133 ) 180 )
134 self._button_team2 = toga.Button( 181 self._button_team2 = toga.Button(
135 f'{self._name_team2} (+1)', 182 f'{self._team2.name} (+1)',
136 on_press=self.cb_score_team2, 183 on_press=self.cb_score_team2,
137 background_color=BLUE, 184 background_color=BLUE,
138 flex=1, 185 flex=1,
@@ -153,6 +200,6 @@ class ScoreCounter(toga.App):
153 self._button_team2.style.height = int(self.main_window.size.height / 5) 200 self._button_team2.style.height = int(self.main_window.size.height / 5)
154 201
155 202
156def main(): 203def main() -> ScoreCounter:
157 """main entry point""" 204 """main entry point"""
158 return ScoreCounter() 205 return ScoreCounter()
diff --git a/tests/__init__.py b/tests/__init__.py
deleted file mode 100644
index e69de29..0000000
--- a/tests/__init__.py
+++ /dev/null
diff --git a/tests/scorecounter.py b/tests/scorecounter.py
deleted file mode 100644
index d59e9f3..0000000
--- a/tests/scorecounter.py
+++ /dev/null
@@ -1,35 +0,0 @@
1import os
2import sys
3import tempfile
4from pathlib import Path
5
6import pytest
7
8
9def run_tests():
10 project_path = Path(__file__).parent.parent
11 os.chdir(project_path)
12
13 # Determine any args to pass to pytest. If there aren't any,
14 # default to running the whole test suite.
15 args = sys.argv[1:]
16 if len(args) == 0:
17 args = ["tests"]
18
19 returncode = pytest.main(
20 [
21 # Turn up verbosity
22 "-vv",
23 # Disable color
24 "--color=no",
25 # Overwrite the cache directory to somewhere writable
26 "-o",
27 f"cache_dir={tempfile.gettempdir()}/.pytest_cache",
28 ] + args
29 )
30
31 print(f">>>>>>>>>> EXIT {returncode} <<<<<<<<<<")
32
33
34if __name__ == "__main__":
35 run_tests()
diff --git a/tests/test_app.py b/tests/test_app.py
deleted file mode 100644
index e1a335f..0000000
--- a/tests/test_app.py
+++ /dev/null
@@ -1,3 +0,0 @@
1def test_first():
2 """An initial test for the app."""
3 assert 1 + 1 == 2