forked from revolunet/sublimetext-markdown-preview
-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
browser.py
67 lines (59 loc) · 2.15 KB
/
browser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""
Open browser.
Licensed under MIT
Copyright (c) 2014 - 2017 Isaac Muse <isaacmuse@gmail.com>
"""
import webbrowser
import subprocess
import sys
import os
import json
if sys.platform.startswith('win'):
PLATFORM = "windows"
elif sys.platform == "darwin":
PLATFORM = "osx"
else:
PLATFORM = "linux"
def to_unicode(string, encoding='utf-8'):
"""Convert byte string to Unicode."""
return str(string, encoding) if isinstance(string, bytes) else string
def open_in_browser(name):
"""Auto open HTML."""
if PLATFORM == "osx":
web_handler = None
try:
# In case HTML is defaulted to an editor or something, try to check URL handling.
launch_services = os.path.expanduser(
'~/Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist'
)
if not os.path.exists(launch_services):
launch_services = os.path.expanduser('~/Library/Preferences/com.apple.LaunchServices.plist')
with open(launch_services, "rb") as f:
content = f.read()
args = ["plutil", "-convert", "json", "-o", "-", "--", "-"]
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write(content)
out = p.communicate()[0]
plist = json.loads(to_unicode(out))
for handler in plist['LSHandlers']:
if handler.get('LSHandlerURLScheme', '') == "http":
web_handler = handler.get('LSHandlerRoleAll', None)
break
except Exception:
pass
if web_handler is not None:
# Open with the URL handler we found
subprocess.Popen(['open', '-b', web_handler, name])
else:
# Just open normally as we never found a web_handler
subprocess.Popen(['open', name])
elif PLATFORM == "windows":
webbrowser.open(name, new=2)
else:
# Linux
try:
# Maybe...?
subprocess.Popen(['xdg-open', name])
except OSError:
# Well we gave it our best shot...
webbrowser.open(name, new=2)