Skip to content

Commit

Permalink
Merge pull request #1411 from A-UNDERSCORE-D/sys-plaform-mypy
Browse files Browse the repository at this point in the history
Ensure that platform guards are recognised by mypy
  • Loading branch information
Athanasius authored Jan 27, 2022
2 parents 055254d + 8c2a0ae commit 5e612d5
Show file tree
Hide file tree
Showing 20 changed files with 1,491 additions and 1,383 deletions.
1 change: 1 addition & 0 deletions .mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
follow_imports = skip
ignore_missing_imports = True
scripts_are_modules = True
; platform = darwin
15 changes: 15 additions & 0 deletions Contributing.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ handy if you want to step through the testing code to be sure of anything.
Otherwise, see the [pytest documentation](https://docs.pytest.org/en/stable/contents.html).

---

## Debugging network sends

Rather than risk sending bad data to a remote service, even if only through
Expand Down Expand Up @@ -484,6 +485,20 @@ Please be verbose here, more info about weird choices is always prefered over ma

Additionally, if your hack is over around 5 lines, please include a `# HACK END` or similar comment to indicate the end of the hack.

# Use `sys.platform` for platform guards

`mypy` (and `pylance`) understand platform guards and will show unreachable code / resolve imports correctly
for platform specific things. However, this only works if you directly reference `sys.platform`, importantly
the following does not work:

```py
from sys import platform
if platform == 'darwin':
...
```

It **MUST** be `if sys.platform`.

---

## Build process
Expand Down
52 changes: 27 additions & 25 deletions EDMarketConnector.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Entry point for the main GUI application."""
from __future__ import annotations

import argparse
import html
Expand All @@ -14,7 +15,6 @@
from builtins import object, str
from os import chdir, environ
from os.path import dirname, join
from sys import platform
from time import localtime, strftime, time
from typing import TYPE_CHECKING, Optional, Tuple, Union

Expand All @@ -23,7 +23,7 @@
# place for things like config.py reading .gitversion
if getattr(sys, 'frozen', False):
# Under py2exe sys.path[0] is the executable name
if platform == 'win32':
if sys.platform == 'win32':
chdir(dirname(sys.path[0]))
# Allow executable to be invoked from any cwd
environ['TCL_LIBRARY'] = join(dirname(sys.path[0]), 'lib', 'tcl')
Expand Down Expand Up @@ -234,7 +234,7 @@ def handle_edmc_callback_or_foregrounding() -> None: # noqa: CCR001
"""Handle any edmc:// auth callback, else foreground existing window."""
logger.trace_if('frontier-auth.windows', 'Begin...')

if platform == 'win32':
if sys.platform == 'win32':

# If *this* instance hasn't locked, then another already has and we
# now need to do the edmc:// checks for auth callback
Expand Down Expand Up @@ -370,8 +370,9 @@ def already_running_popup():
# isort: off
if TYPE_CHECKING:
from logging import TRACE # type: ignore # noqa: F401 # Needed to update mypy
import update
from infi.systray import SysTrayIcon

if sys.platform == 'win32':
from infi.systray import SysTrayIcon
# isort: on

def _(x: str) -> str:
Expand Down Expand Up @@ -443,7 +444,7 @@ def __init__(self, master: tk.Tk): # noqa: C901, CCR001 # TODO - can possibly f

self.prefsdialog = None

if platform == 'win32':
if sys.platform == 'win32':
from infi.systray import SysTrayIcon

def open_window(systray: 'SysTrayIcon') -> None:
Expand All @@ -456,8 +457,8 @@ def open_window(systray: 'SysTrayIcon') -> None:

plug.load_plugins(master)

if platform != 'darwin':
if platform == 'win32':
if sys.platform != 'darwin':
if sys.platform == 'win32':
self.w.wm_iconbitmap(default='EDMarketConnector.ico')

else:
Expand Down Expand Up @@ -527,7 +528,7 @@ def open_window(systray: 'SysTrayIcon') -> None:

# LANG: Update button in main window
self.button = ttk.Button(frame, text=_('Update'), width=28, default=tk.ACTIVE, state=tk.DISABLED)
self.theme_button = tk.Label(frame, width=32 if platform == 'darwin' else 28, state=tk.DISABLED)
self.theme_button = tk.Label(frame, width=32 if sys.platform == 'darwin' else 28, state=tk.DISABLED)
self.status = tk.Label(frame, name='status', anchor=tk.W)

ui_row = frame.grid_size()[1]
Expand All @@ -540,14 +541,15 @@ def open_window(systray: 'SysTrayIcon') -> None:
theme.button_bind(self.theme_button, self.capi_request_data)

for child in frame.winfo_children():
child.grid_configure(padx=self.PADX, pady=(platform != 'win32' or isinstance(child, tk.Frame)) and 2 or 0)
child.grid_configure(padx=self.PADX, pady=(
sys.platform != 'win32' or isinstance(child, tk.Frame)) and 2 or 0)

# The type needs defining for adding the menu entry, but won't be
# properly set until later
self.updater: update.Updater = None

self.menubar = tk.Menu()
if platform == 'darwin':
if sys.platform == 'darwin':
# Can't handle (de)iconify if topmost is set, so suppress iconify button
# http://wiki.tcl.tk/13428 and p15 of
# https://developer.apple.com/legacy/library/documentation/Carbon/Conceptual/HandlingWindowsControls/windowscontrols.pdf
Expand Down Expand Up @@ -603,7 +605,7 @@ def open_window(systray: 'SysTrayIcon') -> None:
self.help_menu.add_command(command=lambda: not self.HelpAbout.showing and self.HelpAbout(self.w))

self.menubar.add_cascade(menu=self.help_menu)
if platform == 'win32':
if sys.platform == 'win32':
# Must be added after at least one "real" menu entry
self.always_ontop = tk.BooleanVar(value=bool(config.get_int('always_ontop')))
self.system_menu = tk.Menu(self.menubar, name='system', tearoff=tk.FALSE)
Expand Down Expand Up @@ -674,11 +676,11 @@ def open_window(systray: 'SysTrayIcon') -> None:
if config.get_str('geometry'):
match = re.match(r'\+([\-\d]+)\+([\-\d]+)', config.get_str('geometry'))
if match:
if platform == 'darwin':
if sys.platform == 'darwin':
# http://core.tcl.tk/tk/tktview/c84f660833546b1b84e7
if int(match.group(2)) >= 0:
self.w.geometry(config.get_str('geometry'))
elif platform == 'win32':
elif sys.platform == 'win32':
# Check that the titlebar will be at least partly on screen
import ctypes
from ctypes.wintypes import POINT
Expand Down Expand Up @@ -776,7 +778,7 @@ def toggle_suit_row(self, visible: Optional[bool] = None) -> None:
self.suit_shown = True

if not self.suit_shown:
if platform != 'win32':
if sys.platform != 'win32':
pady = 2

else:
Expand Down Expand Up @@ -826,7 +828,7 @@ def set_labels(self):
self.system_label['text'] = _('System') + ':' # LANG: Label for 'System' line in main UI
self.station_label['text'] = _('Station') + ':' # LANG: Label for 'Station' line in main UI
self.button['text'] = self.theme_button['text'] = _('Update') # LANG: Update button in main window
if platform == 'darwin':
if sys.platform == 'darwin':
self.menubar.entryconfigure(1, label=_('File')) # LANG: 'File' menu title on OSX
self.menubar.entryconfigure(2, label=_('Edit')) # LANG: 'Edit' menu title on OSX
self.menubar.entryconfigure(3, label=_('View')) # LANG: 'View' menu title on OSX
Expand Down Expand Up @@ -873,7 +875,7 @@ def login(self):

self.button['state'] = self.theme_button['state'] = tk.DISABLED

if platform == 'darwin':
if sys.platform == 'darwin':
self.view_menu.entryconfigure(0, state=tk.DISABLED) # Status
self.file_menu.entryconfigure(0, state=tk.DISABLED) # Save Raw Data

Expand All @@ -887,7 +889,7 @@ def login(self):
# LANG: Successfully authenticated with the Frontier website
self.status['text'] = _('Authentication successful')

if platform == 'darwin':
if sys.platform == 'darwin':
self.view_menu.entryconfigure(0, state=tk.NORMAL) # Status
self.file_menu.entryconfigure(0, state=tk.NORMAL) # Save Raw Data

Expand Down Expand Up @@ -1211,7 +1213,7 @@ def capi_handle_response(self, event=None): # noqa: C901, CCR001
companion.session.invalidate()
self.login()

except companion.ServerConnectionError as e:
except companion.ServerConnectionError as e: # TODO: unreachable (subclass of ServerLagging -- move to above)
logger.warning(f'Exception while contacting server: {e}')
err = self.status['text'] = str(e)
play_bad = True
Expand Down Expand Up @@ -1429,7 +1431,7 @@ def auth(self, event=None) -> None:
companion.session.auth_callback()
# LANG: Successfully authenticated with the Frontier website
self.status['text'] = _('Authentication successful')
if platform == 'darwin':
if sys.platform == 'darwin':
self.view_menu.entryconfigure(0, state=tk.NORMAL) # Status
self.file_menu.entryconfigure(0, state=tk.NORMAL) # Save Raw Data

Expand Down Expand Up @@ -1570,11 +1572,11 @@ def __init__(self, parent: tk.Tk):

# position over parent
# http://core.tcl.tk/tk/tktview/c84f660833546b1b84e7
if platform != 'darwin' or parent.winfo_rooty() > 0:
if sys.platform != 'darwin' or parent.winfo_rooty() > 0:
self.geometry(f'+{parent.winfo_rootx():d}+{parent.winfo_rooty():d}')

# remove decoration
if platform == 'win32':
if sys.platform == 'win32':
self.attributes('-toolwindow', tk.TRUE)

self.resizable(tk.FALSE, tk.FALSE)
Expand Down Expand Up @@ -1651,7 +1653,7 @@ def save_raw(self) -> None:
"""
default_extension: str = ''

if platform == 'darwin':
if sys.platform == 'darwin':
default_extension = '.json'

timestamp: str = strftime('%Y-%m-%dT%H.%M.%S', localtime())
Expand All @@ -1676,15 +1678,15 @@ def exit_tray(self, systray: 'SysTrayIcon') -> None:

def onexit(self, event=None) -> None:
"""Application shutdown procedure."""
if platform == 'win32':
if sys.platform == 'win32':
shutdown_thread = threading.Thread(target=self.systray.shutdown)
shutdown_thread.setDaemon(True)
shutdown_thread.start()

config.set_shutdown() # Signal we're in shutdown now.

# http://core.tcl.tk/tk/tktview/c84f660833546b1b84e7
if platform != 'darwin' or self.w.winfo_rooty() > 0:
if sys.platform != 'darwin' or self.w.winfo_rooty() > 0:
x, y = self.w.geometry().split('+')[1:3] # e.g. '212x170+2881+1267'
config.set('geometry', f'+{x}+{y}')

Expand Down
Loading

0 comments on commit 5e612d5

Please sign in to comment.