This repository has been archived by the owner on Feb 3, 2024. It is now read-only.
/
common.py
286 lines (232 loc) · 8.54 KB
/
common.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
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
"""
Copyright (c) 2011-2012 Fredrik Ehnbom
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
"""
import threading
import time
try:
import Queue
except:
import queue as Queue
import os
import re
import sys
if sys.version[0] == '2':
def sencode(s):
return s.encode("utf-8")
def sdecode(s):
return s
def bencode(s):
return s
def bdecode(s):
return s
else:
def sencode(s):
return s
def sdecode(s):
return s
def bencode(s):
return s.encode("utf-8")
def bdecode(s):
return s.decode("utf-8")
loaded = False
loaded_callbacks = []
def plugin_loaded():
global loaded
global loaded_callbacks
loaded = True
for c in loaded_callbacks:
c()
loaded_callbacks = []
try:
import sublime
def are_we_there_yet(x):
global loaded_callbacks
if loaded:
x()
else:
loaded_callbacks.append(x)
def run_in_main_thread(func):
sublime.set_timeout(func, 0)
def error_message(msg):
# Work around for http://www.sublimetext.com/forum/viewtopic.php?f=3&t=9825
if sublime.active_window() == None:
sublime.set_timeout(lambda: error_message(msg), 500)
else:
sublime.error_message(msg)
language_regex = re.compile("(?<=source\.)[\w+#]+")
def get_language(view):
caret = view.sel()[0].a
language = language_regex.search(view.scope_name(caret))
if language == None:
return None
return language.group(0)
def is_supported_language(view):
if view.is_scratch() or not get_setting("enabled", True, view) or view.file_name() == None:
return False
language = get_language(view)
if language == None or (language != "c++" and
language != "c" and
language != "objc" and
language != "objc++"):
return False
return True
def status_message(msg):
sublime.status_message(sdecode(msg))
def get_settings():
return sublime.load_settings("SublimeClang.sublime-settings")
def get_setting(key, default=None, view=None):
try:
if view == None:
view = sublime.active_window().active_view()
s = view.settings()
if s.has("sublimeclang_%s" % key):
return s.get("sublimeclang_%s" % key)
except:
pass
return get_settings().get(key, default)
def expand_path(value, window):
if window == None:
# Views can apparently be window less, in most instances getting
# the active_window will be the right choice (for example when
# previewing a file), but the one instance this is incorrect
# is during Sublime Text 2 session restore. Apparently it's
# possible for views to be windowless then too and since it's
# possible that multiple windows are to be restored, the
# "wrong" one for this view might be the active one and thus
# ${project_path} will not be expanded correctly.
#
# This will have to remain a known documented issue unless
# someone can think of something that should be done plugin
# side to fix this.
window = sublime.active_window()
get_existing_files = \
lambda m: [ path \
for f in window.folders() \
for path in [os.path.join(f, m.group('file'))] \
if os.path.exists(path) \
]
view = window.active_view()
value = re.sub(r'\${project_path:(?P<file>[^}]+)}', lambda m: len(get_existing_files(m)) > 0 and get_existing_files(m)[0] or m.group('file'), value)
value = re.sub(r'\${env:(?P<variable>[^}]+)}', lambda m: os.getenv(m.group('variable')) if os.getenv(m.group('variable')) else "%s_NOT_SET" % m.group('variable'), value)
value = re.sub(r'\${home}', re.escape(os.getenv('HOME')) if os.getenv('HOME') else "HOME_NOT_SET", value)
value = re.sub(r'\${folder:(?P<file>[^}]+)}', lambda m: os.path.dirname(m.group('file')), value)
value = value.replace('${this_file_path}', os.path.dirname(view.file_name()) if view and view.file_name() else "FILE_NOT_ON_DISK")
value = value.replace('\\', '/')
return value
def display_user_selection(options, callback):
sublime.active_window().show_quick_panel(options, callback)
except:
# Just used for unittesting
def are_we_there_yet(f):
f()
def error_message(msg):
raise Exception(msg)
def get_setting(key, default=None, view=None):
return default
def get_language(view):
return "c++"
def run_in_main_thread(func):
func()
def status_message(msg):
print(msg)
def expand_path(value, window):
return value
def display_user_selection(options, callback):
callback(0)
class LockedVariable:
def __init__(self, var):
self.var = var
self.l = threading.Lock()
def try_lock(self):
return self.l.acquire(False)
def lock(self):
self.l.acquire()
return self.var
def unlock(self):
self.l.release()
class Worker(object):
def __init__(self, threadcount=-1):
if threadcount < 1:
threadcount = get_cpu_count()
self.tasks = Queue.Queue()
for i in range(threadcount):
t = threading.Thread(target=self.worker)
t.daemon = True
t.start()
def display_status(self):
status_message(self.status)
def set_status(self, msg):
self.status = msg
run_in_main_thread(self.display_status)
def worker(self):
try:
# Just so we give time for the editor itself to start
# up before we start doing work
if sys.version[0] != '3':
time.sleep(5)
except:
pass
while True:
task, data = self.tasks.get()
try:
task(data)
except:
import traceback
traceback.print_exc()
finally:
self.tasks.task_done()
def complete_path(value):
path_init, path_last = os.path.split(value)
if path_init[:2] == "-I" and (path_last == "**" or path_last == "*"):
starting_path = path_init[2:]
include_paths = []
if os.path.exists(starting_path):
if path_last == "*":
for dirname in os.listdir(starting_path):
if not dirname.startswith("."): # skip directories that begin with .
include_paths.append("-I" + os.path.join(starting_path, dirname))
elif path_last == "**":
for dirpath, dirs, files in os.walk(starting_path):
for dirname in list(dirs):
if dirname.startswith("."): # skip directories that begin with .
dirs.remove(dirname)
if dirpath != starting_path:
include_paths.append("-I" + dirpath)
else:
include_paths.append("-I" + starting_path)
else:
pass # perhaps put some error here?
return include_paths
else:
return [value]
def get_path_setting(key, default=None, view=None):
value = get_setting(key, default, view)
opts = []
if isinstance(value, list):
for v in value:
opts.append(expand_path(v, view.window()))
else:
opts.append(expand_path(value, view.window()))
return opts
def get_cpu_count():
cpus = 1
try:
import multiprocessing
cpus = multiprocessing.cpu_count()
except:
pass
return cpus