forked from thonny/thonny
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
250 lines (193 loc) · 7.36 KB
/
Copy pathmain.py
File metadata and controls
250 lines (193 loc) · 7.36 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import argparse
import logging
import os
import sys
from typing import Any, Dict, List
import pystart
from pystart import (
SINGLE_INSTANCE_DEFAULT,
choose_logging_level,
configure_logging,
get_configuration_file,
get_ipc_file_path,
get_runner,
get_pystart_user_dir,
get_version,
prepare_pystart_user_dir,
)
logger = logging.getLogger(__name__)
def run() -> int:
# First make sure the command line is good
parsed_args = _parse_arguments_to_dict(sys.argv[1:])
# Temporary compatibility measure for the breaking change introduced in version 5.0
pystart.PYSTART_USER_DIR = get_pystart_user_dir()
import runpy
if sys.executable.endswith("pystart.exe"):
# otherwise some library may try to run its subprocess with pystart.exe
# NB! Must be pythonw.exe not python.exe, otherwise Runner thinks console
# is already allocated.
sys.executable = sys.executable[: -len("pystart.exe")] + "pythonw.exe"
_set_dpi_aware()
try:
runpy.run_module("pystart.customize", run_name="__main__")
except ImportError:
pass
prepare_pystart_user_dir()
configure_logging(_get_frontend_log_file(), choose_logging_level())
if not _check_welcome():
return 0
if _should_delegate():
try:
_delegate_to_existing_instance(parsed_args)
print("Delegated to an existing PyStart instance. Exiting now.")
return 0
except Exception:
import traceback
traceback.print_exc()
# Did not or could not delegate
try:
from pystart import workbench
bench = workbench.Workbench(parsed_args)
bench.mainloop()
return 0
except Exception as e:
title = "Internal launch or mainloop error"
logger.exception(title)
import tkinter as tk
if tk._default_root is not None:
from tkinter import messagebox
# Messagebox may or may not be shown, but here it's no use of being defencive anymore
messagebox.showerror(
title,
f"PyStart encountered an internal error:\n{str(e) or type(e)}"
f"\n\nSee frontend.log for more details",
parent=tk._default_root,
)
return -1
finally:
runner = get_runner()
if runner is not None:
runner.destroy_backend()
def _check_welcome():
from pystart import misc_utils, is_portable
if not os.path.exists(get_configuration_file()) and not misc_utils.running_on_rpi():
from pystart.config import ConfigurationManager
mgr = ConfigurationManager(get_configuration_file())
# For portable version, skip FirstRunWindow and auto-configure
if is_portable():
# Auto select Chinese and Regular mode
mgr.set_option("general.language", "zh_CN")
# Regular mode is default, no need to set ui_mode
mgr.save()
logger.info("Portable mode: auto-configured with zh_CN and regular mode")
return True
from pystart.first_run import FirstRunWindow
win = FirstRunWindow(mgr)
win.mainloop()
return win.ok
else:
return True
def _should_delegate():
if not os.path.exists(get_ipc_file_path()):
# no previous instance
return False
from pystart.config import try_load_configuration
configuration_manager = try_load_configuration(get_configuration_file())
configuration_manager.set_default("general.single_instance", SINGLE_INSTANCE_DEFAULT)
return configuration_manager.get_option("general.single_instance")
def _delegate_to_existing_instance(parsed_args: Dict[str, Any]):
import socket
from pystart import workbench
try:
sock, secret = _create_client_socket()
except Exception:
# Maybe the lock is abandoned or the content is corrupted
try:
os.remove(get_ipc_file_path())
except Exception:
import traceback
traceback.print_exc()
raise
data = repr((secret, parsed_args)).encode(encoding="utf_8")
sock.settimeout(2.0)
sock.sendall(data)
sock.shutdown(socket.SHUT_WR)
response = bytes([])
while len(response) < len(workbench.SERVER_SUCCESS):
new_data = sock.recv(2)
if len(new_data) == 0:
break
else:
response += new_data
if response.decode("UTF-8") != workbench.SERVER_SUCCESS:
raise RuntimeError("Unsuccessful delegation")
def _create_client_socket():
import socket
timeout = 2.0
if sys.platform == "win32":
with open(get_ipc_file_path(), "r") as fp:
port = int(fp.readline().strip())
secret = fp.readline().strip()
# "localhost" can be much slower than "127.0.0.1"
client_socket = socket.create_connection(("127.0.0.1", port), timeout=timeout)
else:
client_socket = socket.socket(socket.AF_UNIX) # @UndefinedVariable
client_socket.settimeout(timeout)
client_socket.connect(get_ipc_file_path())
secret = ""
return client_socket, secret
def _set_dpi_aware():
# https://stackoverflow.com/questions/36134072/setprocessdpiaware-seems-not-to-work-under-windows-10
# https://bugs.python.org/issue33656
# https://msdn.microsoft.com/en-us/library/windows/desktop/dn280512(v=vs.85).aspx
# https://github.com/python/cpython/blob/master/Lib/idlelib/pyshell.py
if sys.platform == "win32":
try:
import ctypes
# 尝试使用 Per-Monitor DPI Aware V2 (Windows 10 1703+)
# DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 = -4
try:
ctypes.windll.user32.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4))
except (AttributeError, OSError):
# 回退到 Per-Monitor DPI Aware (Windows 8.1+)
# PROCESS_PER_MONITOR_DPI_AWARE = 2
try:
ctypes.OleDLL("shcore").SetProcessDpiAwareness(2)
except (AttributeError, OSError):
# 最后回退到 System DPI Aware
ctypes.windll.user32.SetProcessDPIAware()
except (ImportError, AttributeError, OSError):
pass
def _get_frontend_log_file():
return os.path.join(get_pystart_user_dir(), "frontend.log")
def _parse_arguments_to_dict(raw_args: List[str]) -> Dict[str, Any]:
parser = argparse.ArgumentParser(
description="Python IDE for beginners",
allow_abbrev=False,
add_help=False,
)
parser.add_argument(
"-h",
"" "--help",
help="Show this help message and exit",
action="help",
)
parser.add_argument(
"--version", help="Show PyStart version and exit", action="version", version=get_version()
)
parser.add_argument(
"--profile",
help="The profile to create or open. If not specified, the default profile is used. Profile name must be a valid directory name.",
default="default",
metavar="<profile_name>",
)
parser.add_argument(
"files",
help="",
nargs="*",
metavar="<python_file>",
)
parsed_args = vars(parser.parse_args(args=raw_args))
# Need to store CWD, because PyStart may be with different cwd by the time of opening the files
parsed_args["cwd"] = os.getcwd()
return parsed_args