-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdisplay_nums.py
483 lines (366 loc) · 14.2 KB
/
display_nums.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
import sublime
import sublime_plugin
import struct
import re
import json
popup_mode_list = ["basic", "extended", "tabled"]
split_re = re.compile(r"\B_\B", re.I)
dec_re = re.compile(r"^(0|[1-9][0-9]*)(u|l|ul|lu|ll|ull|llu)?$", re.I)
hex_re = re.compile(r"^0x([0-9a-f]+)(u|l|ul|lu|ll|ull|llu)?$", re.I)
oct_re = re.compile(r"^(0[0-7]+)(u|l|ul|lu|ll|ull|llu)?$", re.I)
bin_re = re.compile(r"^0b([01]+)(u|l|ul|lu|ll|ull|llu)?$", re.I)
#####
# Sublime settings getters
#####
def get_setting_by_name(project_settings, name):
if project_settings.has("disnum." + name):
return project_settings.get("disnum." + name)
else:
return sublime.load_settings("display_nums.sublime-settings").get(name)
def get_bits_in_word(project_settings):
bytes_in_word = get_setting_by_name(project_settings, "bytes_in_word")
if not isinstance(bytes_in_word, int):
return 4 * 8
return bytes_in_word * 8
def get_positions_reversed(project_settings):
position_reversed = get_setting_by_name(project_settings, "bit_positions_reversed")
if not isinstance(position_reversed, bool):
return False
return position_reversed
def get_popup_mode(project_settings):
extended = get_setting_by_name(project_settings, "plugin_mode")
if not isinstance(extended, str):
return "basic"
return extended
def get_mouse_move_option(project_settings):
mouse_move = get_setting_by_name(project_settings, "hide_on_mouse_move_away")
if not isinstance(mouse_move, bool):
return sublime.HIDE_ON_MOUSE_MOVE_AWAY
return sublime.HIDE_ON_MOUSE_MOVE_AWAY if mouse_move else 0
def get_swap_addition(project_settings):
swap = get_setting_by_name(project_settings, "addition_swap_endianness")
if not isinstance(swap, bool):
return False
return swap
def get_float_addition(project_settings):
float_nums = get_setting_by_name(project_settings, "addition_float_from_hex")
if not isinstance(float_nums, bool):
return False
return float_nums
def get_size_addition(project_settings):
addition = get_setting_by_name(project_settings, "addition_size_in_bytes")
if not isinstance(addition, bool):
return False
return addition
def get_shift_addition(project_settings):
addition = get_setting_by_name(project_settings, "addition_shift_bit")
if not isinstance(addition, bool):
return False
return addition
def get_size_precision(project_settings):
precision = get_setting_by_name(project_settings, "addition_size_precision")
if not isinstance(precision, int):
return 7
return precision
#####
# Pop-up string generators
#####
space = " "
temp_small_space = "*"
small_space = "<span>"+space+"</span>"
def format_str(string, num, separator=" "):
res = string[-num:]
string = string[:-num]
while len(string):
res = string[-num:] + separator + res
string = string[:-num]
return res
def get_bits_positions(settings, curr_bits_in_word):
positions = ""
start = 0
while start < curr_bits_in_word:
if get_positions_reversed(settings):
positions += "{: <4}".format(start)
else:
positions = "{: >4}".format(start) + positions
start += 4
positions = format_str(positions, 2, temp_small_space*3)
positions = positions.replace(" ", space).replace(temp_small_space, small_space)
return positions
def prepare_urls(s):
res = ""
offset = 0
bit = """<a id='bits' href='{{ "func":"{func}",
"data":{{ "offset":{offset} }}
}}'>{char}</a>"""
for c in s[::-1]:
if c.isdigit():
res = bit.format(
func = "change_bit", offset = offset, char = c
) + res
offset += 1
else:
res = c + res
return res
html_basic = """
<body id='show'>
<style>
span {{ font-size: 0.35rem; }}
#swap {{ color: var(--yellowish); }}
#bits {{ color: var(--foreground); }}
#hr {{ margin: 5px 0; }}
</style>
<div>{hex_name}: {hex_num}</div>
<div>{dec_name}: {dec_num}</div>
<div>{oct_name}: {oct_num}</div>
<div>{bin_name}: {bin_num}</div>
<div id='swap'>""" + " "*5 + """{pos}</div>
{additional}
</body>
"""
html_hr = "<div id='hr'></div>"
str_convert_number = """<a href='{{ "func": "convert_number","data": {{ "base":{base} }}}}'>{name}</a>"""
feature_swap_endian = """
<div id='options'>Swap endianness as
<a href='{ "func": "swap_endianness", "data" : { "bits": 16 } }'>16 bit</a>
<a href='{ "func": "swap_endianness", "data" : { "bits": 32 } }'>32 bit</a>
<a href='{ "func": "swap_endianness", "data" : { "bits": 64 } }'>64 bit</a>
</div>
"""
str_size = "<div>Size: {:.{precision}g} {}</div>"
def feature_float_numbers(number, bits_count):
res = ""
if bits_count/8 <= 4:
res += "<div>Float: {}</div>".format(struct.unpack('!f',struct.pack('!I',number))[0])
if bits_count/8 <= 8:
res += "<div>Double: {}</div>".format(struct.unpack('!d',struct.pack('!Q',number))[0])
return res
def feature_size(number, precision):
names = ['B','kB','MB','GB','TB','PB','EB','ZB','YB']
index = 0
while number >= 1024 and index < len(names) - 1:
number /= 1024
index += 1
return str_size.format(number, names[index], precision=precision)
def feature_shift_bit():
left = """<a href='{ "func": "shift_bits", "data" : { "direction": "left" } }'>left</a>"""
right = """<a href='{ "func": "shift_bits", "data" : { "direction": "right" } }'>right</a>"""
return "<div>Bit shift: "+left+" "+right+"</div>"
def get_closer_bits_num(curr_bits):
i = 8 # bits number in byte
while i <= curr_bits:
i <<= 1
return i
def create_popup_content(settings, mode, number, base):
# select max between (bit_length in settings) and (bit_length of selected number aligned to 4)
curr_bits_in_word = max(get_bits_in_word(settings), number.bit_length() + ((-number.bit_length()) & 0x3))
hex_num = format_str("{:x}".format(number), 2)
dec_num = format_str("{}".format(number), 3, ",")
oct_num = format_str("{:o}".format(number), 3)
bin_num = prepare_urls(
format_str(
format_str(
"{:0={}b}".format(number, curr_bits_in_word),
4,
temp_small_space),
1,
temp_small_space)
).replace(temp_small_space, small_space)
# check if number can be negative
sign_bit = get_closer_bits_num((number // 2).bit_length()) - 1
if number & (1 << sign_bit):
mask = (2 ** (sign_bit + 1)) - number
dec_num += " (-{})".format(mask)
hex_name = "Hex"
dec_name = "Dec"
oct_name = "Oct"
bin_name = "Bin"
additional = ""
if mode == "extended":
hex_name = str_convert_number.format(name=hex_name,base=16)
dec_name = str_convert_number.format(name=dec_name,base=10)
oct_name = str_convert_number.format(name=oct_name,base=8)
bin_name = str_convert_number.format(name=bin_name,base=2)
if get_swap_addition(settings):
additional += html_hr
additional += feature_swap_endian
if base == 16 and get_float_addition(settings):
additional += html_hr
additional += feature_float_numbers(number, curr_bits_in_word)
if get_size_addition(settings):
additional += html_hr
additional += feature_size(number, get_size_precision(settings))
if number != 0 and get_shift_addition(settings):
additional += html_hr
additional += feature_shift_bit()
return html_basic.format(
hex_name = hex_name,
dec_name = dec_name,
oct_name = oct_name,
bin_name = bin_name,
hex_num = hex_num,
dec_num = dec_num,
oct_num = oct_num,
bin_num = bin_num,
pos = get_bits_positions(settings, curr_bits_in_word),
additional = additional
)
def create_tabled_popup_content(number, hex_num):
name = ["Hex", "Dec", "Bin"]
base = [16, 10, 2]
# calculate length of strings
lens = [
max(len(name[0]), len(number)),
len('{:x}'.format(hex_num)),
max(len(name[0]), len('{:d}'.format(hex_num))),
len('{:b}'.format(hex_num))
]
html = "<u>{} {} {} {}</u>".format(
"{: <{}}".format(number, lens[0]),
"{: <{}}".format(name[0], lens[1] + len("0x")),
"{: <{}}".format(name[1], lens[2]),
"{: <{}}".format(name[2], lens[3] + len("0b"))
)
# convert from every numeral system
for i in range(0, len(name)):
try:
num = int(number, base[i])
except:
continue
html += "<div>{} 0x{} {} 0b{}</div>".format(
"{: <{}}".format(name[i], lens[0]),
"{: <{}X}".format(num, lens[1]),
"{: <{}d}".format(num, lens[2]),
"{: <{}b}".format(num, lens[3])
)
return html.replace(" ", space)
#####
# Main listener of selection event
#####
def parse_number(text):
if "_" in text:
underscores = "_"
else:
underscores = ""
# remove underscores in the number
text = "".join(split_re.split(text))
for reg, base in [(dec_re,10), (hex_re,16), (oct_re,8), (bin_re,2)]:
match = reg.match(text)
if match:
return {
"number": int(match.group(1), base),
"base": base,
"suffix": match.group(2) or "",
"underscores": underscores,
"length": len(match.group(1))
}
class DisplayNumberListener(sublime_plugin.EventListener):
def on_selection_modified_async(self, view):
# if more then one select close popup
if len(view.sel()) > 1:
return view.hide_popup()
# selected string without spaces
string = view.substr(view.sel()[0]).strip()
# get plugin mode
mode = get_popup_mode(view.settings())
if mode not in popup_mode_list:
return
if mode == "tabled":
# trying to convert string as hex
try:
hex_num = int(string, 16)
except:
return
html = create_tabled_popup_content(string, hex_num)
else:
parsed = parse_number(string)
if parsed is None:
return
html = create_popup_content(view.settings(), mode, parsed["number"], parsed["base"])
def select_function(x):
data = json.loads(x)
if data.get("func") is not None:
view.run_command(data.get("func"), data.get("data"))
view.show_popup(
html,
flags=get_mouse_move_option(view.settings()),
max_width = 1366,
max_height = 768,
location = view.sel()[0].begin(),
on_navigate = select_function
)
#####
# Sublime commands
#####
def convert_number(parsed, width=0):
if parsed["base"] == 10:
prefix = ""
num = "{:d}".format(parsed["number"])
num = format_str(num, 3, parsed["underscores"])
elif parsed["base"] == 16:
prefix = "0x"
num = "{:0{width}x}".format(parsed["number"], width=width)
num = format_str(num, 4, parsed["underscores"])
elif parsed["base"] == 2:
prefix = "0b"
num = "{:0{width}b}".format(parsed["number"], width=width)
num = format_str(num, 4, parsed["underscores"])
else:
prefix = "0"
num = "{:o}".format(parsed["number"])
num = format_str(num, 4, parsed["underscores"])
return "{}{}{}".format(prefix, num, parsed["suffix"])
class ConvertNumberCommand(sublime_plugin.TextCommand):
def run(self, edit, base):
if len(self.view.sel()) > 1:
return self.view.hide_popup()
selected_range = self.view.sel()[0]
selected_number = self.view.substr(selected_range).strip()
parsed = parse_number(selected_number)
if parsed is None:
return self.view.hide_popup()
parsed["base"] = base
self.view.replace(edit, selected_range, convert_number(parsed))
class ChangeBitCommand(sublime_plugin.TextCommand):
def run(self, edit, offset):
selected_range = self.view.sel()[0]
selected_number = self.view.substr(selected_range).strip()
parsed = parse_number(selected_number)
if parsed is None:
return self.view.hide_popup()
parsed["number"] = parsed["number"] ^ (1 << offset)
self.view.replace(edit, selected_range, convert_number(parsed, width=parsed["length"]))
class SwapEndiannessCommand(sublime_plugin.TextCommand):
def run(self, edit, bits):
if len(self.view.sel()) > 1:
return self.view.hide_popup()
selected_range = self.view.sel()[0]
selected_number = self.view.substr(selected_range).strip()
parsed = parse_number(selected_number)
if parsed is None:
return self.view.hide_popup()
bit_len = parsed["number"].bit_length()
# align bit length to bits
bit_len = bit_len + ((-bit_len) & (bits - 1))
bytes_len = bit_len // 8
number = parsed["number"].to_bytes(bytes_len, byteorder="big")
bytes_word = bits // 8
result = []
for i in range(bytes_word, bytes_len + 1, bytes_word):
for j in range(0, bytes_word):
result.append(number[i - j - 1])
result = int.from_bytes(bytes(result), byteorder="big")
parsed["number"] = result
self.view.replace(edit, selected_range, convert_number(parsed))
class ShiftBitsCommand(sublime_plugin.TextCommand):
def run(self, edit, direction):
selected_range = self.view.sel()[0]
selected_number = self.view.substr(selected_range).strip()
parsed = parse_number(selected_number)
if parsed is None:
return self.view.hide_popup()
if direction == "left":
parsed["number"] = parsed["number"] << 1
else:
parsed["number"] = parsed["number"] >> 1
self.view.replace(edit, selected_range, convert_number(parsed))