thymed 0.2.3__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: thymed
3
- Version: 0.2.3
3
+ Version: 0.4.0
4
4
  Summary: Thymed
5
5
  Home-page: https://github.com/czarified/thymed
6
6
  License: MIT
@@ -17,7 +17,8 @@ Classifier: Programming Language :: Python :: 3.11
17
17
  Requires-Dist: click (>=8.0.1)
18
18
  Requires-Dist: openpyxl (>=3.0.10,<4.0.0)
19
19
  Requires-Dist: pandas (>=1.5.0,<2.0.0)
20
- Requires-Dist: rich (>=12.5.1,<13.0.0)
20
+ Requires-Dist: rich (>12.5.1)
21
+ Requires-Dist: textual (>=0.38.1,<0.39.0)
21
22
  Requires-Dist: toml (>=0.10.2,<0.11.0)
22
23
  Project-URL: Changelog, https://github.com/czarified/thymed/releases
23
24
  Project-URL: Documentation, https://thymed.readthedocs.io
@@ -87,7 +88,7 @@ please [file an issue] along with a detailed description.
87
88
 
88
89
  ## Credits
89
90
 
90
- This project was generated from [@cjolowicz]'s [Hypermodern Python Cookiecutter] template.
91
+ This project was originally generated from [@cjolowicz]'s [Hypermodern Python Cookiecutter] template.
91
92
 
92
93
  [@cjolowicz]: https://github.com/cjolowicz
93
94
  [pypi]: https://pypi.org/
@@ -97,7 +98,7 @@ This project was generated from [@cjolowicz]'s [Hypermodern Python Cookiecutter]
97
98
 
98
99
  <!-- github-only -->
99
100
 
100
- [license]: https://github.com/czarified/thymed/blob/main/LICENSE
101
- [contributor guide]: https://github.com/czarified/thymed/blob/main/CONTRIBUTING.md
101
+ [license]: https://github.com/czarified/thymed/blob/master/LICENSE
102
+ [contributor guide]: https://github.com/czarified/thymed/blob/master/CONTRIBUTING.md
102
103
  [command-line reference]: https://thymed.readthedocs.io/en/latest/usage.html
103
104
 
@@ -61,7 +61,7 @@ please [file an issue] along with a detailed description.
61
61
 
62
62
  ## Credits
63
63
 
64
- This project was generated from [@cjolowicz]'s [Hypermodern Python Cookiecutter] template.
64
+ This project was originally generated from [@cjolowicz]'s [Hypermodern Python Cookiecutter] template.
65
65
 
66
66
  [@cjolowicz]: https://github.com/cjolowicz
67
67
  [pypi]: https://pypi.org/
@@ -71,6 +71,6 @@ This project was generated from [@cjolowicz]'s [Hypermodern Python Cookiecutter]
71
71
 
72
72
  <!-- github-only -->
73
73
 
74
- [license]: https://github.com/czarified/thymed/blob/main/LICENSE
75
- [contributor guide]: https://github.com/czarified/thymed/blob/main/CONTRIBUTING.md
74
+ [license]: https://github.com/czarified/thymed/blob/master/LICENSE
75
+ [contributor guide]: https://github.com/czarified/thymed/blob/master/CONTRIBUTING.md
76
76
  [command-line reference]: https://thymed.readthedocs.io/en/latest/usage.html
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "thymed"
3
- version = "0.2.3"
3
+ version = "0.4.0"
4
4
  description = "Thymed"
5
5
  authors = ["Benjamin Crews <aceF22@gmail.com>"]
6
6
  license = "MIT"
@@ -19,9 +19,10 @@ Changelog = "https://github.com/czarified/thymed/releases"
19
19
  python = "^3.8"
20
20
  click = ">=8.0.1"
21
21
  toml = "^0.10.2"
22
- rich = "^12.5.1"
22
+ rich = ">12.5.1"
23
23
  pandas = "^1.5.0"
24
24
  openpyxl = "^3.0.10"
25
+ textual = "^0.38.1"
25
26
 
26
27
  [tool.poetry.dev-dependencies]
27
28
  Pygments = ">=2.10.0"
@@ -52,6 +53,9 @@ myst-parser = {version = ">=0.16.1"}
52
53
  thymed = "thymed.__main__:main"
53
54
  punch = "thymed.__main__:punch_default"
54
55
 
56
+ [tool.poetry.group.dev.dependencies]
57
+ textual-dev = "^1.2.1"
58
+
55
59
  [tool.coverage.paths]
56
60
  source = ["src", "*/site-packages"]
57
61
  tests = ["tests", "*/tests"]
@@ -43,6 +43,9 @@ if not __DIR.exists():
43
43
 
44
44
  # Where all charge code objects are recorded
45
45
  charges = "{CHARGEFILE.as_posix()}"
46
+
47
+ # The default charge code
48
+ default = 0
46
49
  """
47
50
  parsed_toml = toml.loads(default_config)
48
51
  with open(__CONFIG, "w") as f:
@@ -111,16 +114,16 @@ class ChargeCode:
111
114
  self.times.append(
112
115
  tuple(dt.datetime.fromisoformat(time) for time in entry)
113
116
  )
114
- except json.JSONDecodeError:
117
+ except json.JSONDecodeError: # pragma: no cover
115
118
  # If the file is completely blank, we will get an error
116
119
  pass
117
- except Exception as e:
120
+ except Exception as e: # pragma: no cover
118
121
  # Otherwise, let me know what went wrong
119
122
  raise e
120
123
 
121
124
  @property
122
- def is_active(self) -> Any:
123
- """The charge code is active if it has been initalized, but not closed."""
125
+ def is_active(self) -> [bool, Any]:
126
+ """The charge code is active if it has been activated, but not closed."""
124
127
  # If the last item in the times list has only 1 entry,
125
128
  # we assume the code is still active.
126
129
  if len(self.times) == 0:
@@ -163,7 +166,7 @@ class ChargeCode:
163
166
  # We overwrite data directly here, because the post_init method
164
167
  # reads the same file.
165
168
  final_data[f"{self.id}"] = _times
166
- except json.JSONDecodeError:
169
+ except json.JSONDecodeError: # pragma: no cover
167
170
  # Unless we can't read the file
168
171
  console.log("[red]Got JSONDecodeError, assuming the file was blank...")
169
172
  final_data = {self.id: _times}
@@ -191,7 +194,7 @@ class ChargeCode:
191
194
  with open(_CHARGES) as f:
192
195
  try:
193
196
  codes = json.load(f)
194
- except json.JSONDecodeError:
197
+ except json.JSONDecodeError: # pragma: no cover
195
198
  # If the file is completely blank, we will get an error
196
199
  codes = dict()
197
200
 
@@ -306,8 +309,16 @@ def get_code(id: int) -> Any:
306
309
  with open(_CHARGES) as f:
307
310
  try:
308
311
  codes = json.load(f, object_hook=object_decoder)
309
- except json.JSONDecodeError:
310
- # If the file is completely blank, we will get an error
312
+ except json.JSONDecodeError: # pragma: no cover
313
+ # If the Charges file is completely blank (fresh install),
314
+ # It will read with a length of zero. We should skip this
315
+ # to avoid testing or runtime errors. Notify the user and exit.
316
+ console = Console()
317
+ console.print(
318
+ "Looks like you're trying to use a ChargeCode "
319
+ "without first defining any codes! Try running `thymed create` "
320
+ "first."
321
+ )
311
322
  codes = dict()
312
323
  try:
313
324
  # We assert id is an int, so it's safe to convert into string.
@@ -337,71 +348,3 @@ def get_code(id: int) -> Any:
337
348
  # This function should be available in the CLI,
338
349
  # prompt to make the new file if non-existent,
339
350
  # and update the config.toml to use the new file.
340
-
341
-
342
- if __name__ == "__main__": # pragma: no cover
343
- # # Scratchpad
344
- console = Console(record=True)
345
-
346
- import random
347
-
348
- def build_fake_times(
349
- start: dt.datetime,
350
- end: dt.datetime,
351
- name: str,
352
- description: str,
353
- id: int,
354
- n: int = 250,
355
- ):
356
- """Temporary function for testing."""
357
- # Initialize the output variables
358
- ins = []
359
- outs = []
360
- # Iteration variable. We don't want to repeat days or "work" them out of order.
361
- iter_start = start
362
- for _i in range(n):
363
- # Pick a random timestamp in the time range
364
- date = dt.timedelta(days=random.randint(0, 2)) + iter_start
365
- iter_start = date
366
- # Check if we should stop here (beyond the end date)
367
- if (iter_start >= end) or (date > end):
368
- break
369
-
370
- # Generate the timedelta for punch in/out on that day
371
- in_delta = random.randint(-220, 1850)
372
- out_delta = random.randint(-1000, 1550)
373
-
374
- # Add the deltas for in/out
375
- in_punch = dt.datetime(
376
- year=date.year, month=date.month, day=date.day, hour=8
377
- ) + dt.timedelta(seconds=in_delta)
378
- ins.append(in_punch)
379
-
380
- out_punch = dt.datetime(
381
- year=date.year, month=date.month, day=date.day, hour=15
382
- ) + dt.timedelta(seconds=out_delta)
383
- outs.append(out_punch)
384
-
385
- df = pd.DataFrame()
386
- df["in_punch"] = ins
387
- df["out_punch"] = outs
388
-
389
- console.print(df)
390
-
391
- my_code = ChargeCode(name, description, id)
392
- console.print(my_code)
393
-
394
- my_code.times = tuple(zip(ins, outs))
395
- my_code.write_class()
396
- my_code.write_json()
397
-
398
- # build_fake_times(
399
- # dt.datetime(2022,5,31),
400
- # dt.datetime.today(),
401
- # name="Ben at Hermeus",
402
- # description="Ben's work at Hermeus since Memorial Day this year.",
403
- # id = 69
404
- # )
405
- card = TimeCard(69)
406
- console.print(card.weekly_report())
407
- card.to_excel(card.weekly_report(), Path(r"C:\Users\Czarified\.thymed"))
@@ -1,9 +1,9 @@
1
1
  """Command-line interface."""
2
- import importlib.metadata
3
2
  import json
4
3
  from typing import Any
5
4
 
6
5
  import click
6
+ import pkg_resources
7
7
  from rich.console import Console
8
8
  from rich.panel import Panel
9
9
  from rich.prompt import Confirm
@@ -13,17 +13,18 @@ from rich.table import Table
13
13
  from rich.traceback import install
14
14
 
15
15
  import thymed
16
+ from thymed.tui import ThymedApp
16
17
 
17
18
 
18
19
  install()
19
20
 
20
21
 
21
- __version__ = importlib.metadata.version("thymed")
22
+ __version__ = pkg_resources.get_distribution("thymed").version
22
23
 
23
24
 
24
25
  @click.group()
25
26
  @click.version_option()
26
- def main() -> None:
27
+ def main() -> None: # pragma: no cover
27
28
  """Thymed.
28
29
 
29
30
  This command serves as the main entrypoint into
@@ -43,11 +44,6 @@ def hello():
43
44
  "I am [spring_green3 italic]Thymed.[/] " "Simple command-line time-tracking."
44
45
  )
45
46
  console.print(f"Current Version: {__version__}\n")
46
- console.print(
47
- "Currently, this is a placeholder tool. "
48
- "Functionality exists in the API, but "
49
- "is not exteded to CLI yet.\n"
50
- )
51
47
 
52
48
 
53
49
  def default_code() -> Any:
@@ -56,25 +52,9 @@ def default_code() -> Any:
56
52
  The default ChargeCode is defined in the Thymed config file.
57
53
  If no default id is defined, raises a warning.
58
54
  """
59
- with open(thymed._CHARGES) as f:
60
- check = f.read()
61
- if len(check) == 0 or check == "{}":
62
- # If the Charges file is completely blank (fresh install),
63
- # It will read with a length of zero. We should skip this
64
- # to avoid testing or runtime errors. Notify the user and exit.
65
- console = Console()
66
- console.print(
67
- "Looks like you're trying to punch a ChargeCode "
68
- "without first defining any codes! Try running `thymed create` "
69
- "first."
70
- )
71
- return None
72
-
73
- codes = json.load(f, object_hook=thymed.object_decoder)
74
-
75
55
  try:
76
56
  default_id = thymed.__OPTIONS["database"]["default"]
77
- return codes[str(default_id)]
57
+ return thymed.get_code(default_id)
78
58
  except KeyError:
79
59
  # KeyError means default code isn't set. We should notify user,
80
60
  # and exit.
@@ -108,8 +88,8 @@ def punch(id) -> None:
108
88
  Punches the current time. Write the data and the code,
109
89
  then exit.
110
90
  """
111
- # Manually check some argument varialbes...
112
- if len(id) > 1:
91
+ # Manually check some argument variables...
92
+ if len(id) > 1: # pragma: no cover
113
93
  raise NotImplementedError
114
94
  elif len(id) == 1:
115
95
  id = id[0]
@@ -153,7 +133,7 @@ def create():
153
133
  new_code.write_class()
154
134
  # TODO: Make this prettier
155
135
  console.print("Wrote ChargeCode data to the Thymed Charges file!")
156
- else:
136
+ else: # pragma: no cover
157
137
  # TODO: Make this prettier
158
138
  console.print("Exiting without writing new ChargeCode...Try again.")
159
139
 
@@ -168,7 +148,7 @@ def list():
168
148
  # Sort the codes dictionary by key (code id)
169
149
  sorted_codes = sorted(codes.items(), key=lambda kv: int(kv[0]))
170
150
  codes = [x[1] for x in sorted_codes]
171
- except json.JSONDecodeError:
151
+ except json.JSONDecodeError: # pragma: no cover
172
152
  print("Got JSON Error")
173
153
  # If the file is completely blank, we will get an error
174
154
  codes = dict()
@@ -186,5 +166,18 @@ def list():
186
166
  console.print(table)
187
167
 
188
168
 
169
+ @main.command()
170
+ def tui():
171
+ """Launch the TUI.
172
+
173
+ This command launches the Text User Interface (TUI).
174
+ While the commandline functions are quite efficient,
175
+ many users may prefer or need the TUI for interacting
176
+ with Thymed. It's quite robust and polished! Give it a try!
177
+ """
178
+ app = ThymedApp()
179
+ app.run()
180
+
181
+
189
182
  if __name__ == "__main__":
190
183
  main(prog_name="thymed") # pragma: no cover
@@ -0,0 +1,203 @@
1
+ * {
2
+ transition: background 500ms in_out_cubic, color 500ms in_out_cubic;
3
+ }
4
+
5
+ Screen {
6
+ layers: base overlay notifications;
7
+ overflow: hidden;
8
+ }
9
+
10
+
11
+ Notification {
12
+ dock: bottom;
13
+ layer: notification;
14
+ width: auto;
15
+ margin: 2 4;
16
+ padding: 1 2;
17
+ background: $background;
18
+ color: $text;
19
+ height: auto;
20
+
21
+ }
22
+
23
+ Sidebar {
24
+ width: 40;
25
+ background: $panel;
26
+ transition: offset 500ms in_out_cubic;
27
+ layer: overlay;
28
+
29
+ }
30
+
31
+ Sidebar:focus-within {
32
+ offset: 0 0;
33
+ }
34
+
35
+ Sidebar.-hidden {
36
+ offset-x: -100%;
37
+ }
38
+
39
+ Sidebar Title {
40
+ background: $boost;
41
+ color: $secondary;
42
+ padding: 1 1;
43
+ border-right: vkey $background;
44
+ dock: top;
45
+ text-align: center;
46
+ text-style: bold;
47
+ }
48
+
49
+ ChargeManager Title {
50
+ background: $boost;
51
+ color: springgreen;
52
+ padding: 1 1;
53
+ border-right: vkey $background;
54
+ dock: top;
55
+ text-align: center;
56
+ text-style: bold underline;
57
+ }
58
+
59
+ .data {
60
+ background: $boost;
61
+ color: springgreen;
62
+ content-align: center top;
63
+ }
64
+
65
+ #add {
66
+ dock: left;
67
+ }
68
+
69
+ #remove {
70
+ dock: right;
71
+ }
72
+
73
+ OptionGroup {
74
+ background: $boost;
75
+ color: $text;
76
+ height: 1fr;
77
+ border-right: vkey $background;
78
+ }
79
+
80
+ .option {
81
+ margin: 1 1;
82
+ height: 3;
83
+ width: 100%;
84
+ border: tall $panel;
85
+ text-align: center;
86
+ }
87
+
88
+ #applet {
89
+ width: 1fr;
90
+ height: 4fr;
91
+ border: solid white;
92
+ background: $surface;
93
+ }
94
+
95
+ #info {
96
+ width: 1fr;
97
+ height: 1fr;
98
+ border: solid white;
99
+ background: $surface;
100
+ color: springgreen;
101
+ }
102
+
103
+ Screen>Container {
104
+ height: 100%;
105
+ overflow: hidden;
106
+ }
107
+
108
+ .pad {
109
+ margin: 1 0;
110
+ }
111
+
112
+ DataTable {
113
+ height: 16;
114
+ max-height: 16;
115
+ }
116
+
117
+ PunchForm {
118
+ height: auto;
119
+ padding: 1 2;
120
+ layout: grid;
121
+ grid-size: 2;
122
+ grid-rows: 4;
123
+ grid-columns: 20 1fr;
124
+ background: $boost;
125
+ border: wide $background;
126
+ }
127
+
128
+ PunchForm > Button {
129
+ margin: 1 1;
130
+ width: 75%;
131
+ content-align: center middle;
132
+ }
133
+
134
+ PunchForm .label {
135
+ padding: 1 2;
136
+ text-align: right;
137
+ color: mediumspringgreen;
138
+ }
139
+
140
+ #clock {
141
+ column-span: 2;
142
+ tint: darkgreen 20%;
143
+ text-align: center;
144
+ }
145
+
146
+ Message {
147
+ margin: 0 1;
148
+
149
+ }
150
+
151
+ Settings > Horizontal {
152
+ border: wide black;
153
+ height: 5;
154
+ }
155
+
156
+ Horizontal > Switch {
157
+ dock: right;
158
+ }
159
+
160
+ AddScreen {
161
+ align: center middle;
162
+ }
163
+
164
+ #dialog {
165
+ grid-size: 2;
166
+ grid-rows: 1fr 1fr 1fr 1fr 1fr 1fr;
167
+ grid-columns: 1fr 3fr;
168
+ padding: 0 1;
169
+ width: 70%;
170
+ height: 30;
171
+ border: thick $background 50%;
172
+ background: $surface;
173
+ }
174
+
175
+ #question {
176
+ column-span: 2;
177
+ height: 1fr;
178
+ width: 1fr;
179
+ color: mediumspringgreen;
180
+ content-align: center middle;
181
+ }
182
+
183
+ .right {
184
+ text-align: right;
185
+ }
186
+
187
+ Window {
188
+ background: $boost;
189
+ overflow: auto;
190
+ height: auto;
191
+ max-height: 16;
192
+ }
193
+
194
+ Window>Static {
195
+ width: auto;
196
+ }
197
+
198
+ Version {
199
+ color: $text-disabled;
200
+ dock: bottom;
201
+ text-align: center;
202
+ padding: 1;
203
+ }
@@ -0,0 +1,199 @@
1
+ """This module contains the TUI code.
2
+
3
+ The Text User Interface is all created, managed,
4
+ and tested with Textual.
5
+ """
6
+ import json
7
+ from time import monotonic
8
+
9
+ # from rich.text import Text
10
+ # from textual import events
11
+ from textual.app import App
12
+ from textual.app import ComposeResult
13
+ from textual.containers import Container
14
+ from textual.containers import ScrollableContainer
15
+ from textual.reactive import reactive, var
16
+ from textual.widget import Widget
17
+ from textual.widgets import Button
18
+ from textual.widgets import DataTable
19
+ from textual.widgets import Footer
20
+ from textual.widgets import Header
21
+ from textual.widgets import Rule
22
+ from textual.widgets import Static
23
+
24
+ import thymed
25
+
26
+
27
+ # from typing import Any
28
+ # from typing import Coroutine
29
+
30
+
31
+ ROWS = [("ID", "NAME", "DESCRIPTION", "ACTIVE")]
32
+ with open(thymed._CHARGES) as f:
33
+ try:
34
+ codes = json.load(f, object_hook=thymed.object_decoder)
35
+
36
+ # Sort the codes dictionary by key (code id)
37
+ sorted_codes = sorted(codes.items(), key=lambda kv: int(kv[0]))
38
+ codes = [x[1] for x in sorted_codes]
39
+ except json.JSONDecodeError: # pragma: no cover
40
+ codes = dict()
41
+
42
+ for code in codes:
43
+ ROWS.append((str(code.id), code.name, code.description, str(code.is_active)))
44
+
45
+
46
+ class TimeDisplay(Static):
47
+ """A widget to display elapsed time."""
48
+
49
+ start_time = reactive(monotonic)
50
+ time = reactive(0.0)
51
+ total = reactive(0.0)
52
+ name = reactive("name")
53
+
54
+ def on_mount(self) -> None:
55
+ """Event handler called when widget is added to the app."""
56
+ self.update_timer = self.set_interval(1 / 60, self.update_time, pause=True)
57
+
58
+ def update_time(self) -> None:
59
+ """Method to update the time to the current time."""
60
+ self.time = self.total + monotonic() - self.start_time
61
+
62
+ def watch_time(self, time: float) -> None:
63
+ """Called when the attribute changes."""
64
+ minutes, seconds = divmod(time, 60)
65
+ hours, minutes = divmod(minutes, 60)
66
+ self.update(f"{self.name}\n{hours:02,.0f}:{minutes:02.0f}:{seconds:05.2f}")
67
+
68
+ def start(self) -> None:
69
+ """Method to resume time updating."""
70
+ self.start_time = monotonic()
71
+ self.update_timer.resume()
72
+
73
+ def stop(self) -> None:
74
+ """Method to stop the time display updating."""
75
+ self.update_timer.pause()
76
+ self.total += monotonic() - self.start_time
77
+ self.time = self.total
78
+
79
+ def reset(self) -> None:
80
+ """Method to reset the time display to zero."""
81
+ self.total = 0
82
+ self.time = 0
83
+
84
+ class Stopwatch(Static):
85
+ """A stopwatch widget."""
86
+
87
+ name = reactive("name")
88
+
89
+ def on_button_pressed(self, event: Button.Pressed) -> None:
90
+ """Event handler called when a button is pressed."""
91
+ button_id = event.button.id
92
+ time_display = self.query_one(TimeDisplay)
93
+ if button_id == "start":
94
+ time_display.start()
95
+ self.add_class("started")
96
+ elif button_id == "stop":
97
+ time_display.stop()
98
+ self.remove_class("started")
99
+ elif button_id == "reset":
100
+ time_display.reset()
101
+
102
+ def compose(self) -> ComposeResult:
103
+ """Create child widgets of a stopwatch."""
104
+ display = TimeDisplay()
105
+ display.name = self.name
106
+ yield Button("Start", id="start", variant="success")
107
+ yield Button("Stop", id="stop", variant="error")
108
+ yield Button("Reset", id="reset")
109
+ yield display
110
+
111
+ class ReactiveTitle(Widget):
112
+ """A Reactive Title that changes based on the selected DataTable row."""
113
+ name: reactive[str | None] = reactive("This is a title.")
114
+ sub: reactive[str | None] = reactive("Description.")
115
+
116
+ def render(self) -> str:
117
+ return f"{self.name}\n{self.sub}"
118
+
119
+ class Thingy(Static):
120
+ """This thingy has a couple buttons to add and remove stopwatches."""
121
+
122
+ def on_button_pressed(self, event: Button.Pressed) -> None:
123
+ """Event handler for app-level actions based on buttons."""
124
+ button_id = event.button.id
125
+ if button_id == "add":
126
+ name = self.query_one(ReactiveTitle).name
127
+ new_stopwatch = Stopwatch()
128
+ new_stopwatch.name = name
129
+ self.app.query_one("#timers").mount(new_stopwatch)
130
+ new_stopwatch.scroll_visible()
131
+ elif button_id == "remove":
132
+ timers = self.app.query("Stopwatch")
133
+ if timers:
134
+ timers.last().remove()
135
+
136
+ def compose(self) -> ComposeResult:
137
+ """Create child widgets of a stopwatch."""
138
+ yield Button("Add", id="add", variant="success")
139
+ yield ReactiveTitle(id="hometitle", classes="title")
140
+ yield Button("Remove", id="remove", variant="error")
141
+
142
+
143
+ class HomePane(Container):
144
+ """A view of Thymed ChargeCodes, and buttons to add timers."""
145
+
146
+ def compose(self) -> ComposeResult:
147
+ """Compose."""
148
+ self.name_widget = Static("Thymed.\n")
149
+ self.table_title_widget = Static("ChargeCodes in Current Database:", classes="title")
150
+ yield self.name_widget
151
+ yield self.table_title_widget
152
+ yield DataTable()
153
+ yield Thingy()
154
+
155
+ def on_mount(self) -> None:
156
+ """What to do on mount."""
157
+ self.name_widget.styles.color = "springgreen"
158
+
159
+
160
+ class Thymer(App):
161
+ """A Textual app to manage timers!!"""
162
+
163
+ CSS_PATH = "thymer.tcss"
164
+ BINDINGS = [("escape", "exit", "Quit"), ("d", "toggle_dark", "Toggle dark mode")]
165
+
166
+ def compose(self) -> ComposeResult:
167
+ """Create child widgets for the app."""
168
+ yield Header(show_clock=True)
169
+ yield Footer()
170
+ yield HomePane()
171
+ yield Rule()
172
+ yield ScrollableContainer(Stopwatch(), Stopwatch(), id="timers")
173
+
174
+ def on_mount(self) -> None:
175
+ """What to do on mount."""
176
+ self.title = "Thymed"
177
+ table = self.query_one(DataTable)
178
+ table.add_columns(*ROWS[0])
179
+ table.add_rows(ROWS[1:])
180
+ table.cursor_type = "row"
181
+
182
+ def on_data_table_row_selected(self, event: DataTable.RowSelected):
183
+ """Grab the selected ChargeCode."""
184
+ data = event.data_table.get_row(event.row_key)
185
+ self.query_one("#hometitle", ReactiveTitle).name = str(data[1])
186
+ self.query_one("#hometitle", ReactiveTitle).sub = str(data[2])
187
+
188
+ def action_toggle_dark(self) -> None:
189
+ """An action to toggle dark mode."""
190
+ self.dark = not self.dark
191
+
192
+ def action_exit(self) -> None:
193
+ """Exits the app."""
194
+ self.exit()
195
+
196
+
197
+ if __name__ == "__main__": # pragma: no cover
198
+ app = Thymer()
199
+ app.run()
@@ -0,0 +1,85 @@
1
+ HomePane {
2
+ layout: vertical;
3
+ content-align: center top;
4
+ background: $boost;
5
+ margin: 1;
6
+ min-width: 50;
7
+ padding: 0;
8
+ }
9
+
10
+ Thingy {
11
+ layout: horizontal;
12
+ content-align: center top;
13
+ background: $boost;
14
+ height: 5;
15
+ margin: 2;
16
+ padding: 1;
17
+ }
18
+
19
+ Stopwatch {
20
+ layout: horizontal;
21
+ background: $boost;
22
+ height: 5;
23
+ margin: 1;
24
+ min-width: 50;
25
+ padding: 1;
26
+ }
27
+
28
+ TimeDisplay {
29
+ content-align: center middle;
30
+ text-opacity: 60%;
31
+ height: 3;
32
+ }
33
+
34
+ Button {
35
+ width: 16;
36
+ }
37
+
38
+ #start {
39
+ dock: left;
40
+ }
41
+
42
+ #stop {
43
+ dock: left;
44
+ display: none;
45
+ }
46
+
47
+ #reset {
48
+ dock: right;
49
+ }
50
+
51
+ #add {
52
+ dock: left;
53
+ }
54
+
55
+ #remove {
56
+ dock: right;
57
+ }
58
+
59
+
60
+ .started {
61
+ text-style: bold;
62
+ background: $success;
63
+ color: $text;
64
+ }
65
+
66
+ .started TimeDisplay {
67
+ text-opacity: 100%;
68
+ }
69
+
70
+ .started #start {
71
+ display: none
72
+ }
73
+
74
+ .started #stop {
75
+ display: block
76
+ }
77
+
78
+ .started #reset {
79
+ visibility: hidden
80
+ }
81
+
82
+ .title {
83
+ content-align: center top;
84
+ color:springgreen
85
+ }
@@ -0,0 +1,443 @@
1
+ """The main Thymed Textual App.
2
+
3
+ This module contains the code for the Textual TUI of the main Textual
4
+ app. The Textual app has a simple interface with a dynamic applet,
5
+ surrounded by a header and footer. Most of the functionality comes with
6
+ the dynamic sidebar of functions.
7
+ """
8
+
9
+ import json
10
+ from datetime import datetime
11
+ from importlib.metadata import version
12
+
13
+ import textual
14
+ from rich.console import RenderableType
15
+ from rich.table import Table
16
+ from textual.app import App
17
+ from textual.app import ComposeResult
18
+ from textual.binding import Binding
19
+ from textual.containers import Container
20
+ from textual.containers import Grid
21
+ from textual.containers import Horizontal
22
+ from textual.containers import ScrollableContainer
23
+ from textual.css.query import NoMatches
24
+ from textual.reactive import reactive
25
+ from textual.screen import ModalScreen
26
+ from textual.widget import Widget
27
+
28
+ # from textual.widgets import DataTable
29
+ from textual.widgets import Button
30
+ from textual.widgets import Digits
31
+ from textual.widgets import Footer
32
+ from textual.widgets import Header
33
+ from textual.widgets import Input
34
+ from textual.widgets import Placeholder
35
+ from textual.widgets import Static
36
+ from textual.widgets import Switch
37
+
38
+ import thymed
39
+
40
+
41
+ # from pathlib import Path
42
+
43
+
44
+ SIDEBAR_INFO = """
45
+ There are multiple tools available in Thymed. To use one, select it or hit the keybinding. The main area will be updated with the 'applet' along with some more information. :smiley:
46
+ """
47
+
48
+ LINKS = """
49
+ Here are some links, you can click these!
50
+
51
+ [@click="app.open_link('https://github.com/czarified/thymed')"]Thymed GitHub[/]
52
+ [@click="app.open_link('https://thymed.readthedocs.io/en/latest/')"]:books:Thymed Docs[/]
53
+ [@click="app.open_link('https://github.com/czarified/thymed/issues')"]:hammer_and_wrench: Contact the Dev[/]
54
+ [@click="app.open_link('https://github.com/czarified/thymed/blob/master/CONTRIBUTING.md')"]:heart: Contribute![/]
55
+ """
56
+
57
+ LOGO = """
58
+
59
+ ▀█▀ █░█ █▄█ █▀▄▀█ █▀▀ █▀▄ ░
60
+ ░█░ █▀█ ░█░ █░▀░█ ██▄ █▄▀ ▄
61
+ """
62
+
63
+
64
+ class Title(Static):
65
+ """A title widget."""
66
+
67
+ pass
68
+
69
+
70
+ class OptionGroup(ScrollableContainer):
71
+ """A group for options."""
72
+
73
+ pass
74
+
75
+
76
+ class Version(Static):
77
+ def render(self) -> RenderableType:
78
+ return f"[b]Thymed v{version('thymed')}"
79
+
80
+
81
+ class Sidebar(Container):
82
+ def compose(self) -> ComposeResult:
83
+ yield Title("Menu")
84
+ yield Static(SIDEBAR_INFO)
85
+ yield OptionGroup(
86
+ Button("Punch Screen", classes="option punch", variant="success"),
87
+ Button("ChargeCode Manager", classes="option charge", variant="success"),
88
+ Button("Reporting", classes="option report", variant="success"),
89
+ Button("Admin Tools", classes="option admin", variant="success"),
90
+ Button("Settings", classes="option settings", variant="success"),
91
+ )
92
+ yield Static(LINKS)
93
+ yield Version()
94
+
95
+
96
+ class InfoPane(Widget):
97
+ """The information area at the top of the Body."""
98
+
99
+ info = reactive(LOGO)
100
+
101
+ def render(self) -> str:
102
+ return f"{self.info}"
103
+
104
+
105
+ class PunchForm(Container):
106
+ """Punch a ChargeCode.
107
+
108
+ This tool presents a 'login screen' to punch a ChargeCode. Type in the
109
+ ChargeCode ID number, then press enter or select the Punch button. The
110
+ provided ID will change state ('out' to 'in' or vice versa).
111
+ """
112
+
113
+ # Info is just a formatted version of the docstring.
114
+ info = (
115
+ __doc__.split("\n")[0]
116
+ + "\n"
117
+ + " ".join([line.strip() for line in __doc__.split("\n")[1:]])
118
+ )
119
+
120
+ def compose(self) -> ComposeResult:
121
+ yield Digits("", id="clock")
122
+ yield Static("ChargeCode ID:", classes="label")
123
+ yield Input(placeholder="123456", id="chargecode")
124
+ yield Static()
125
+ yield Button("Punch", variant="primary", id="punch")
126
+
127
+
128
+ class ChargeManager(ScrollableContainer):
129
+ """Manage the available ChargeCodes in the Database.
130
+
131
+ This tool presents a tabular list of ChargeCodes, along with
132
+ buttons to add and remove items from the database.
133
+ """
134
+
135
+ # Info is just a formatted version of the docstring.
136
+ info = (
137
+ __doc__.split("\n")[0]
138
+ + "\n"
139
+ + " ".join([line.strip() for line in __doc__.split("\n")[1:]])
140
+ )
141
+
142
+ data = reactive(Table())
143
+
144
+ def get_data(self) -> Table:
145
+ """Function to retrieve Thymed data."""
146
+ with open(thymed._CHARGES) as f:
147
+ try:
148
+ codes = json.load(f, object_hook=thymed.object_decoder)
149
+
150
+ # Sort the codes dictionary by key (code id)
151
+ sorted_codes = sorted(codes.items(), key=lambda kv: int(kv[0]))
152
+ codes = [x[1] for x in sorted_codes]
153
+ except json.JSONDecodeError: # pragma: no cover
154
+ self.notify("Got JSON Error", severity="error")
155
+ # If the file is completely blank, we will get an error
156
+ codes = dict()
157
+
158
+ table = Table(style="spring_green2")
159
+ table.add_column("ID", justify="right", style="green", no_wrap=True)
160
+ table.add_column("NAME", style="spring_green3 italic")
161
+ table.add_column("DESCRIPTION", style="spring_green4")
162
+ table.add_column("ACTIVE", style="green")
163
+
164
+ for code in codes:
165
+ table.add_row(
166
+ str(code.id), code.name, code.description, str(code.is_active)
167
+ )
168
+
169
+ return table
170
+
171
+ def compose(self) -> ComposeResult:
172
+ yield Title("ChargeCodes in Current Database")
173
+ self.data = self.get_data()
174
+ yield Static(self.data, classes="data")
175
+ yield Container(
176
+ Button("Add", variant="success", id="add"),
177
+ Button("Remove", variant="error", id="remove"),
178
+ classes="controls",
179
+ )
180
+
181
+
182
+ class Settings(ScrollableContainer):
183
+ """View and change various settings relating to Thymed."""
184
+
185
+ # Info is just a formatted version of the docstring.
186
+ info = (
187
+ __doc__.split("\n")[0]
188
+ + "\n"
189
+ + " ".join([line.strip() for line in __doc__.split("\n")[1:]])
190
+ )
191
+
192
+ def compose(self) -> ComposeResult:
193
+ for _i in range(10):
194
+ yield Horizontal(Static("A settings switch"), Switch())
195
+
196
+
197
+ class UnderConstruction(Container):
198
+ """This feature is still WIP.
199
+
200
+ Still working on building this feature out. For now, we can show you
201
+ a structurally equivalent placeholder!
202
+ """
203
+
204
+ # Info is just a formatted version of the docstring.
205
+ info = (
206
+ __doc__.split("\n")[0]
207
+ + "\n"
208
+ + " ".join([line.strip() for line in __doc__.split("\n")[1:]])
209
+ )
210
+
211
+ def compose(self) -> ComposeResult:
212
+ yield Title(":hammer_and_wrench: WIP :hammer_and_wrench:")
213
+
214
+
215
+ class Body(Container):
216
+ """The Body is a container in the app that has dynamic widgets inside.
217
+
218
+ The information pane displays text with instructions about the current
219
+ active applet.
220
+
221
+ The applet is the functional tool of the application. There are multiple
222
+ applets available and which one is shown here is toggled via
223
+ the sidebar menu or keybindings.
224
+ """
225
+
226
+ applet = reactive(Placeholder(id="applet"))
227
+
228
+ def compose(self) -> ComposeResult:
229
+ yield InfoPane(id="info")
230
+ yield self.applet
231
+
232
+
233
+ class AddScreen(ModalScreen):
234
+ """Screen with a dialog to add a ChargeCode."""
235
+
236
+ def compose(self) -> ComposeResult:
237
+ yield Grid(
238
+ Title("Add new ChargeCode information", id="question"),
239
+ Static("ID Number: ", classes="right"),
240
+ Input(placeholder="123456", id="charge_id"),
241
+ Static("Name: ", classes="right"),
242
+ Input(placeholder="Name", id="charge_name"),
243
+ Static("Description: ", classes="right"),
244
+ Input(placeholder="Description", id="charge_description", classes="long"),
245
+ Static(),
246
+ Static(
247
+ "Note: After submitting, you need to reload the Manager screen to see your new ChargeCode (Hit F2)."
248
+ ),
249
+ Button("Submit", variant="success", id="submit"),
250
+ Button("Cancel", variant="primary", id="cancel"),
251
+ id="dialog",
252
+ )
253
+
254
+ def on_button_pressed(self, event: Button.Pressed) -> None:
255
+ charge_id = self.query_one("#charge_id").value
256
+ charge_name = self.query_one("#charge_name").value
257
+ charge_description = self.query_one("#charge_description").value
258
+ data = [charge_id, charge_name, charge_description]
259
+ if event.button.id == "submit":
260
+ self.dismiss(data)
261
+ else:
262
+ self.app.pop_screen()
263
+
264
+
265
+ class ThymedApp(App[None]):
266
+ CSS_PATH = "thymed.tcss"
267
+ TITLE = "Thymed App"
268
+ BINDINGS = [
269
+ ("m", "toggle_sidebar", "Menu"),
270
+ ("f1", "launch_punch", "Punch Screen"),
271
+ ("f2", "launch_chargecode", "ChargeCode Manager"),
272
+ ("f3", "launch_report", "Reporting"),
273
+ ("f4", "launch_admin", "Admin Tools"),
274
+ ("f12", "launch_settings", "Settings"),
275
+ Binding("escape", "app.quit", "Quit", show=True),
276
+ ]
277
+
278
+ show_sidebar = reactive(False)
279
+
280
+ def compose(self) -> ComposeResult:
281
+ yield Header(show_clock=True)
282
+ yield Container(Sidebar(classes="-hidden"), Body())
283
+ yield Footer()
284
+
285
+ def on_ready(self) -> None:
286
+ self.update_clock()
287
+ self.set_interval(1, self.update_clock)
288
+
289
+ def update_clock(self) -> None:
290
+ clock = datetime.now()
291
+ try:
292
+ self.query_one(Digits).update(f"{clock:%a %d %b %Y, %I:%M%p}")
293
+ except NoMatches:
294
+ # We build and destroy the clock with the active applet.
295
+ # A lot of the time it just doesn't exist, so ignore this.
296
+ pass
297
+
298
+ def action_launch_punch(self) -> None:
299
+ """This method 'launches' the punch form applet."""
300
+ self.query_one("#applet").remove()
301
+ new = PunchForm(id="applet")
302
+ self.query_one(InfoPane).info = new.info
303
+ self.query_one(Body).mount(new)
304
+
305
+ def action_launch_chargecode(self) -> None:
306
+ """This method 'launches' the chargecode manager applet."""
307
+ self.query_one("#applet").remove()
308
+ new = ChargeManager(id="applet")
309
+ self.query_one(InfoPane).info = new.info
310
+ self.query_one(Body).mount(new)
311
+
312
+ def action_launch_report(self) -> None:
313
+ """This method 'launches' the reporting applet."""
314
+ self.query_one("#applet").remove()
315
+ new = UnderConstruction(id="applet")
316
+ self.query_one(InfoPane).info = new.info
317
+ self.query_one(Body).mount(new)
318
+
319
+ def action_launch_admin(self) -> None:
320
+ """This method 'launches' the admin applet."""
321
+ self.query_one("#applet").remove()
322
+ new = UnderConstruction(id="applet")
323
+ self.query_one(InfoPane).info = new.info
324
+ self.query_one(Body).mount(new)
325
+
326
+ def action_launch_settings(self) -> None:
327
+ """This method 'launches' the settings applet."""
328
+ self.query_one("#applet").remove()
329
+ new = Settings(id="applet")
330
+ self.query_one(InfoPane).info = new.info
331
+ self.query_one(Body).mount(new)
332
+
333
+ def action_toggle_sidebar(self) -> None:
334
+ sidebar = self.query_one(Sidebar)
335
+ self.set_focus(None)
336
+ if sidebar.has_class("-hidden"):
337
+ sidebar.remove_class("-hidden")
338
+ else:
339
+ if sidebar.query("*:focus"):
340
+ self.screen.set_focus(None)
341
+ sidebar.add_class("-hidden")
342
+
343
+ def punch(self, id: int):
344
+ """Method to do the chargecode punching."""
345
+ title = "Punch"
346
+ try:
347
+ # To do the Thymed stuff for punching
348
+ code = thymed.get_code(int(id))
349
+ if not code:
350
+ # The get_code function handles KeyErrors for the CLI.
351
+ # It returns a None value in this case only.
352
+ raise KeyError
353
+ status_pre = "Active" if code.is_active else "Inactive"
354
+ code.punch()
355
+ code.write_class()
356
+ code.write_json()
357
+ status_post = "Active" if code.is_active else "Inactive"
358
+ message = f"Punching Charge: {id}, {code.name}.\nFrom {status_pre} to {status_post}"
359
+ severity = "information"
360
+ except KeyError:
361
+ # If things don't work notify the user to try again.
362
+ message = f"Cannot find the charge code with id: {id}"
363
+ severity = "error"
364
+
365
+ self.notify(message, title=title, severity=severity)
366
+
367
+ @textual.on(Input.Submitted, "#chargecode")
368
+ def charge_submitted(self, event: Input.Submitted) -> None:
369
+ """Event handler called when Input is submitted."""
370
+ field = event.input
371
+ if field.id == "chargecode":
372
+ id = event.value
373
+ if id != "":
374
+ field.value = ""
375
+ self.punch(id)
376
+
377
+ @textual.on(Button.Pressed, "#punch")
378
+ def punch_pressed(self, event: Button.Pressed) -> None:
379
+ """Event handler called when Buttons are pressed."""
380
+ field = self.query_one("#chargecode")
381
+ id = field.value
382
+ if id != "":
383
+ field.value = ""
384
+ self.punch(id)
385
+
386
+ @textual.on(Button.Pressed, ".option")
387
+ def option_buttons(self, event: Button.Pressed) -> None:
388
+ """What to do when the option buttons are pressed."""
389
+ classes = event.button.classes
390
+
391
+ if "punch" in classes:
392
+ self.action_toggle_sidebar()
393
+ self.action_launch_punch()
394
+ elif "charge" in classes:
395
+ self.action_toggle_sidebar()
396
+ self.action_launch_chargecode()
397
+ elif "report" in classes:
398
+ self.action_toggle_sidebar()
399
+ self.action_launch_report()
400
+ elif "admin" in classes:
401
+ self.action_toggle_sidebar()
402
+ self.action_launch_admin()
403
+ elif "settings" in classes:
404
+ self.action_toggle_sidebar()
405
+ self.action_launch_settings()
406
+
407
+ @textual.on(Button.Pressed, "#add")
408
+ def code_screen(self, event: Button.Pressed):
409
+ """When we want to add a chargecode.
410
+
411
+ When the AddScreen is dismissed, it will call the
412
+ callback function below.
413
+ """
414
+
415
+ def add_code(data: list):
416
+ """Method to actually build a ChargeCode object.
417
+
418
+ This method gets called after the AddScreen is dismissed.
419
+ It takes data and calls the base Thymed methods to build
420
+ a ChargeCode object, then write it to the database.
421
+
422
+ After we finish adding the code, we call get_data on
423
+ the ChargeManager screen to refresh the table.
424
+ """
425
+ id, name, description = data
426
+ charge = thymed.ChargeCode(name, description, int(id))
427
+ charge.write_class()
428
+
429
+ applet = self.query_one("#applet")
430
+ applet.data = applet.get_data()
431
+
432
+ self.push_screen(AddScreen(), add_code)
433
+
434
+ def action_open_link(self, link: str) -> None:
435
+ self.app.bell()
436
+ import webbrowser
437
+
438
+ webbrowser.open(link)
439
+
440
+
441
+ if __name__ == "__main__":
442
+ app = ThymedApp()
443
+ app.run()
File without changes
File without changes