1"""Open files in platform-specific default viewing application."""
2
3import logging
4import os
5import platform
6import subprocess
7import typing
8
9from .. import _tools
10
11__all__ = ['view']
12
13PLATFORM = platform.system().lower()
14
15
16log = logging.getLogger(__name__)
17
18
19@_tools.deprecate_positional_args(supported_number=1)
20def view(filepath: typing.Union[os.PathLike, str],
21 quiet: bool = False) -> None:
22 """Open filepath with its default viewing application (platform-specific).
23
24 Args:
25 filepath: Path to the file to open in viewer.
26 quiet: Suppress ``stderr`` output
27 from the viewer process (ineffective on Windows).
28
29 Raises:
30 RuntimeError: If the current platform is not supported.
31
32 Note:
33 There is no option to wait for the application to close,
34 and no way to retrieve the application's exit status.
35 """
36 try:
37 view_func = getattr(view, PLATFORM)
38 except AttributeError:
39 raise RuntimeError(f'platform {PLATFORM!r} not supported')
40 view_func(filepath, quiet=quiet)
41
42
43@_tools.attach(view, 'darwin')
44def view_darwin(filepath: typing.Union[os.PathLike, str], *,
45 quiet: bool) -> None:
46 """Open filepath with its default application (mac)."""
47 cmd = ['open', filepath]
48 log.debug('view: %r', cmd)
49 kwargs = {'stderr': subprocess.DEVNULL} if quiet else {}
50 subprocess.Popen(cmd, **kwargs)
51
52
53@_tools.attach(view, 'linux')
54@_tools.attach(view, 'freebsd')
55def view_unixoid(filepath: typing.Union[os.PathLike, str], *,
56 quiet: bool) -> None:
57 """Open filepath in the user's preferred application (linux, freebsd)."""
58 cmd = ['xdg-open', filepath]
59 log.debug('view: %r', cmd)
60 kwargs = {'stderr': subprocess.DEVNULL} if quiet else {}
61 subprocess.Popen(cmd, **kwargs)
62
63
64@_tools.attach(view, 'windows')
65def view_windows(filepath: typing.Union[os.PathLike, str], *,
66 quiet: bool) -> None:
67 """Start filepath with its associated application (windows)."""
68 # TODO: implement quiet=True
69 filepath = os.path.normpath(filepath)
70 log.debug('view: %r', filepath)
71 os.startfile(filepath) # pytype: disable=module-attr