-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
65 lines (53 loc) · 2.3 KB
/
main.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
import logging
from ulauncher.api.client.Extension import Extension
from ulauncher.api.client.EventListener import EventListener
from ulauncher.api.shared.event import KeywordQueryEvent
from ulauncher.api.shared.item.ExtensionResultItem import ExtensionResultItem
from ulauncher.api.shared.item.SmallResultItem import SmallResultItem
from ulauncher.api.shared.action.RenderResultListAction import RenderResultListAction
from ulauncher.api.shared.action.CopyToClipboardAction import CopyToClipboardAction
from pint import UnitRegistry
ureg = UnitRegistry(autoconvert_offset_to_baseunit=True)
Q_ = ureg.Quantity
logging.basicConfig()
logger = logging.getLogger(__name__)
class UnitsExtension(Extension):
def __init__(self):
super(UnitsExtension, self).__init__()
self.subscribe(KeywordQueryEvent, KeywordQueryEventListener())
class KeywordQueryEventListener(EventListener):
def on_event(self, event, extension):
# Get query
term = (event.get_argument() or '')
elem = term.split(' to ')
if len(elem) > 1:
src, dst = term.split(' to ')
# Try to handle the "in" conversion keyword
# Becomes an issue when user also wants to convert inches as "in"
else:
elem = term.split(' in ')
# The second condition occurs when the user want to convert to inches
if term.endswith(' in in'):
src, dst = term.split(' in ')
elif ' in in ' in term:
src, dst = term.split(' in in ')
src += ' in'
elif len(elem) > 1:
src, dst = term.split(' in ')
try:
src = ureg.parse_expression(src, case_sensitive=False)
dst = ureg.parse_expression(dst, case_sensitive=False)
result = description = str(src.to(dst))
except Exception as e:
result = description = "No result"
return_list = [create_item(result, "icon", "", "", "")]
return RenderResultListAction(return_list)
def create_item(name, icon, keyword, description, on_enter):
return ExtensionResultItem(
name=name,
description=description,
icon='images/{}.svg'.format(icon),
on_enter=CopyToClipboardAction(description)
)
if __name__ == '__main__':
UnitsExtension().run()