Skip to content

Commit

Permalink
feat(ui): make settings menu work WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
dynobo committed Feb 26, 2024
1 parent 6c00946 commit 09add85
Show file tree
Hide file tree
Showing 10 changed files with 251 additions and 102 deletions.
3 changes: 0 additions & 3 deletions keyhint/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1 @@
from keyhint import config, context, sheets, utils

__version__ = "0.4.4"
__all__ = ["config", "context", "sheets", "utils", "__version__"]
6 changes: 3 additions & 3 deletions keyhint/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@
from keyhint.window import KeyhintWindow # noqa: E402

logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
format="%(asctime)s - %(levelname)-7s - %(module)s.py:%(lineno)d - %(message)s",
datefmt="%H:%M:%S",
level="WARNING",
)
logger = logging.getLogger(__name__)
logger = logging.getLogger("keyhint")


class Application(Adw.Application):
Expand Down Expand Up @@ -96,7 +96,7 @@ def do_command_line(self, cli: Gtk, **__: Mapping[Any, Any]) -> int:
self.options = cli.get_options_dict().end().unpack()

if "verbose" in self.options:
logging.getLogger().setLevel("DEBUG")
logger.setLevel("DEBUG")
logger.debug("CLI Options: %s", self.options)

self.activate()
Expand Down
11 changes: 11 additions & 0 deletions keyhint/config.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
import os
from configparser import ConfigParser
from pathlib import Path
Expand All @@ -8,6 +9,8 @@
CONFIG_PATH = Path.home() / ".config" / "keyhint"
CONFIG_FILE = CONFIG_PATH / "keyhint.ini"

logger = logging.getLogger("keyhint")


class WritingConfigParser(ConfigParser):
def set_persistent(
Expand All @@ -25,10 +28,18 @@ def load() -> WritingConfigParser:
"sort_by": "size",
"orientation": "vertical",
"default_cheatsheet": "keyhint",
"zoom": "100",
},
)
if CONFIG_FILE.exists():
config.read(CONFIG_FILE)
logger.debug("Loaded config from %s.", CONFIG_FILE)
if not config.has_section("main"):
config.add_section("main")
logger.debug("Created missing 'main' section.")
return config


if __name__ == "__main__":
load()
load()
8 changes: 4 additions & 4 deletions keyhint/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import subprocess
import traceback

logger = logging.getLogger(__name__)
logger = logging.getLogger("keyhint")


def get_active_window_info_wayland() -> tuple[str, str]:
Expand Down Expand Up @@ -130,9 +130,9 @@ def detect_active_window() -> tuple[str, str]:
"incl. the traceback above on https://github.com/dynobo/keyhint/issues."
)

logger.debug(
"Detected wm_class: '%s'. Detected window_title: '%s'", wm_class, window_title
)
logger.debug("Detected wm_class: '%s'.", wm_class)
logger.debug("Detected window_title: '%s'.", window_title)

if "" in [wm_class, window_title]:
logger.error(
"Couldn't detect active window! Please report this error "
Expand Down
23 changes: 17 additions & 6 deletions keyhint/resources/header_bar.ui
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
</style>
<child>
<object class="GtkLabel">
<property name="label">Section Sorting</property>
<property name="label">Section Ordering</property>
</object>
</child>
<child>
Expand All @@ -29,7 +29,7 @@
<property name="spacing">6</property>
<child>
<object class="GtkToggleButton" id="sort_by_size_button">
<property name="tooltip_text" translatable="yes">Smooth shapes</property>
<property name="tooltip_text" translatable="yes">Sort sections by height</property>
<property name="active">true</property>
<child>
<object class="GtkLabel">
Expand All @@ -40,7 +40,7 @@
</child>
<child>
<object class="GtkToggleButton" id="sort_by_title_button">
<property name="tooltip_text" translatable="yes">Rough shapes</property>
<property name="tooltip_text" translatable="yes">Sort sections alphabetically</property>
<property name="group">sort_by_size_button</property>
<child>
<object class="GtkLabel">
Expand All @@ -49,6 +49,17 @@
</child>
</object>
</child>
<child>
<object class="GtkToggleButton" id="sort_by_native_button">
<property name="tooltip_text" translatable="yes">Use section order from config files</property>
<property name="group">sort_by_size_button</property>
<child>
<object class="GtkLabel">
<property name="label">Native</property>
</object>
</child>
</object>
</child>
</object>
</child>
<child>
Expand Down Expand Up @@ -90,7 +101,7 @@
</child>
<child>
<object class="GtkLabel">
<property name="label">Zoom</property>
<property name="label">Zoom %</property>
</object>
</child>
<child>
Expand All @@ -103,8 +114,8 @@
<property name="digits">0</property>
<property name="adjustment">
<object class="GtkAdjustment">
<property name="lower">50</property>
<property name="upper">200</property>
<property name="lower">70</property>
<property name="upper">150</property>
<property name="step-increment">10</property>
<property name="value">100</property>
</object>
Expand Down
37 changes: 37 additions & 0 deletions keyhint/resources/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,40 @@
.bindings-section .view {
background-color: transparent;
}

.zoom-70,
.zoom-70 .bindings-section header label {
font-size: 70%;
}
.zoom-80,
.zoom-80 .bindings-section header label {
font-size: 80%;
}
.zoom-90,
.zoom-90 .bindings-section header label {
font-size: 90%;
}
.zoom-100,
.zoom-100 .bindings-section header label {
font-size: 100%;
}
.zoom-110,
.zoom-110 .bindings-section header label {
font-size: 110%;
}
.zoom-120,
.zoom-120 .bindings-section header label {
font-size: 120%;
}
.zoom-130,
.zoom-130 .bindings-section header label {
font-size: 130%;
}
.zoom-140,
.zoom-140 .bindings-section header label {
font-size: 140%;
}
.zoom-150,
.zoom-150 .bindings-section header label {
font-size: 150%;
}
44 changes: 24 additions & 20 deletions keyhint/sheets.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
from copy import deepcopy
from pathlib import Path

import keyhint
from keyhint import config

logger = logging.getLogger(__name__)
logger = logging.getLogger("keyhint")


def _load_toml(file_path: str | os.PathLike) -> dict:
Expand All @@ -24,7 +24,7 @@ def _load_toml(file_path: str | os.PathLike) -> dict:
with Path(file_path).open("rb") as fh:
result = tomllib.load(fh)
except Exception as exc:
print(exc) # noqa: T201
logger.warning("Could not loading toml file %s: %s", file_path, exc)
result = {}

return result
Expand All @@ -38,7 +38,7 @@ def load_default_sheets() -> list[dict]:
"""
default_sheet_path = Path(__file__).parent / "config"
sheets = [_load_toml(f) for f in default_sheet_path.glob("*.toml")]
logger.info("Loaded %s default cheatsheets.", len(sheets))
logger.debug("Found %s default sheets.", len(sheets))
return sorted(sheets, key=lambda k: k["id"])


Expand All @@ -48,9 +48,9 @@ def load_user_sheets() -> list[dict]:
Returns:
List[dict]: List of application keyhints and meta info.
"""
files = keyhint.config.CONFIG_PATH.glob("*.toml")
files = config.CONFIG_PATH.glob("*.toml")
sheets = [_load_toml(f) for f in files]
logger.info("Loaded %s user cheatsheets.", len(sheets))
logger.debug("Found %s user sheets in %s/.", len(sheets), config.CONFIG_PATH)
return sorted(sheets, key=lambda k: k["id"])


Expand All @@ -60,7 +60,7 @@ def _expand_includes(sheets: list[dict]) -> list[dict]:
for include in s.get("include", []):
included_sheets = [c for c in sheets if c["id"] == include]
if not included_sheets:
message = f"Cheatsheet '{include}' included by '{s['id']}' not found!"
message = f"Sheet '{include}' included by '{s['id']}' not found!"
raise ValueError(message)
included_sheet = deepcopy(included_sheets[0])
included_sheet["section"] = {
Expand All @@ -82,6 +82,20 @@ def _remove_hidden(sheets: list[dict]) -> list[dict]:
return [s for s in sheets if not s.get("hidden", False)]


def _update_or_append(sheets: list[dict], new_sheet: dict) -> list[dict]:
for sheet in sheets:
if sheet["id"] == new_sheet["id"]:
# Update existing default sheet by user sheet
user_sheet_sections = new_sheet.pop("section")
sheet.update(new_sheet)
sheet["section"].update(user_sheet_sections)
break
else:
# If default sheet didn't exist, append as new
sheets.append(new_sheet)
return sheets


def load_sheets() -> list[dict]:
"""Load unified default keyhints and keyhints from user config.
Expand All @@ -95,23 +109,13 @@ def load_sheets() -> list[dict]:
user_sheets = load_user_sheets()

for user_sheet in user_sheets:
existed = False
for sheet in sheets:
# Update default sheet by user sheet (if existing)
if sheet["id"] == user_sheet["id"]:
user_sheet_sections = user_sheet.pop("section")
sheet.update(user_sheet)
sheet["section"].update(user_sheet_sections)
existed = True
break
# If it didn't exist, append as new
if not existed:
sheets.append(user_sheet)
sheets = _update_or_append(sheets, user_sheet)

sheets = _expand_includes(sheets)
sheets = _remove_hidden(sheets)
sheets = _remove_empty_sections(sheets)
return sheets # noqa: RET504
logger.debug("Loaded %s sheets.", len(sheets))
return sheets


if __name__ == "__main__":
Expand Down
8 changes: 1 addition & 7 deletions keyhint/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from gi.repository import GLib, Gtk

logger = logging.getLogger(__name__)
logger = logging.getLogger("keyhint")


def replace_keys(text: str) -> str:
Expand Down Expand Up @@ -56,9 +56,3 @@ def create_shortcut(text: str) -> Gtk.Box:
label.set_markup(f"{GLib.markup_escape_text(key)}")
box.append(label)
return box


def create_section_title(text: str) -> Gtk.Label:
label = Gtk.Label(xalign=0.0)
label.set_markup(f"<b>{text}</b>")
return label
Loading

0 comments on commit 09add85

Please sign in to comment.