Skip to content

Commit

Permalink
Add custom decimal separator #16
Browse files Browse the repository at this point in the history
- Add custom decimal separator #16
  • Loading branch information
deanishe committed Jul 14, 2017
1 parent 2551399 commit 71868f8
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 62 deletions.
10 changes: 5 additions & 5 deletions src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
# ----------------------------------------------------------------------
# Result display
# ----------------------------------------------------------------------
DECIMAL_PLACES_DEFAULT = 2
DECIMAL_PLACES = int(os.getenv('DECIMAL_PLACES') or '2')
DECIMAL_SEPARATOR = os.getenv('DECIMAL_SEPARATOR') or '.'

# ----------------------------------------------------------------------
# Currency settings
Expand Down Expand Up @@ -1464,13 +1465,12 @@
# ----------------------------------------------------------------------
# Icons
# ----------------------------------------------------------------------
ICON_UPDATE = 'icons/update-available.png'
ICON_CURRENCY = 'icons/money.png'
ICON_HELP = 'icons/help.png'
ICON_UPDATE = 'icons/update-available.png'

# ----------------------------------------------------------------------
# Update and default user settings
# ----------------------------------------------------------------------
UPDATE_SETTINGS = {'github_slug': 'deanishe/alfred-convert'}
DEFAULT_SETTINGS = {
'decimal_places': DECIMAL_PLACES_DEFAULT,
}
DEFAULT_SETTINGS = {}
36 changes: 22 additions & 14 deletions src/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,18 @@

from workflow import Workflow3, ICON_WARNING, ICON_INFO
from workflow.background import run_in_background, is_running
from config import (CURRENCIES, CRYPTO_CURRENCIES,
CURRENCY_CACHE_AGE, CURRENCY_CACHE_NAME,
ICON_UPDATE,
UPDATE_SETTINGS, DEFAULT_SETTINGS,
BUILTIN_UNIT_DEFINITIONS,
CUSTOM_DEFINITIONS_FILENAME,
HELP_URL)
from config import (
BUILTIN_UNIT_DEFINITIONS,
CURRENCY_CACHE_AGE,
CURRENCY_CACHE_NAME,
CUSTOM_DEFINITIONS_FILENAME,
DECIMAL_PLACES,
DECIMAL_SEPARATOR,
DEFAULT_SETTINGS,
HELP_URL,
ICON_UPDATE,
UPDATE_SETTINGS,
)

log = None

Expand Down Expand Up @@ -82,12 +87,11 @@ def register_exchange_rates(exchange_rates):
ureg.define(definition)


def convert(query, decimal_places=2):
def convert(query):
"""Parse query, calculate and return conversion result.
Args:
query (unicode): Alfred's query.
decimal_places (int, optional): Number of decimal places in result.
Raises:
ValueError: Raised if the query is incomplete or invalid.
Expand Down Expand Up @@ -117,14 +121,17 @@ def convert(query, decimal_places=2):
# of units that `pint` understands
if len(atoms) == 1:
raise ValueError('No destination unit specified')

q1 = q2 = ''
for i in range(len(atoms)):
from_unit = to_unit = None # reset so no old values spill over
q1 = ' '.join(atoms[:i + 1]).strip()
q2 = ' '.join(atoms[i + 1:]).strip()
log.debug('atoms : %r i : %d q1 : %s q2 : %s', atoms, i, q1, q2)

if not len(q1) or not len(q2): # an empty unit
continue

try:
from_unit = ureg.Quantity(qty, q1)
except UndefinedUnitError:
Expand All @@ -144,11 +151,14 @@ def convert(query, decimal_places=2):
raise ValueError('Unknown unit : %s' % q1)
if to_unit is None:
raise ValueError('Unknown unit : %s' % q2)

conv = from_unit.to(to_unit)
log.debug('%f %s' % (conv.magnitude, conv.units))

fmt = '%%0.%df %%s' % decimal_places
result = fmt % (conv.magnitude, conv.units)
fmt = '%%0.%df' % DECIMAL_PLACES
number = fmt % conv.magnitude
number = number.replace('.', DECIMAL_SEPARATOR)
result = '{} {}'.format(number, conv.units)

return result

Expand Down Expand Up @@ -202,9 +212,7 @@ def main(wf):
conversion = None

try:
conversion = convert(query,
decimal_places=wf.settings.get('decimal_places',
2))
conversion = convert(query)
except UndefinedUnitError as err:
log.critical('unknown unit : %s', err.unit_names)
error = 'Unknown unit : {}'.format(err.unit_names)
Expand Down
Binary file added src/icons/help.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 9 additions & 1 deletion src/info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,11 @@ You can also add your own custom units.
Configuration
-------------
UPDATE_INTERVAL is the number of minutes between exchange rate updates.</string>
UPDATE_INTERVAL is the number of minutes between exchange rate updates.
DECIMAL_PLACES is the number of decimal places to show in conversion results.
DECIMAL_SEPARATOR is the character used to separate whole numbers from decimal fraction.</string>
<key>uidata</key>
<dict>
<key>14C63701-669A-43A3-BF6A-65A23759DA5F</key>
Expand Down Expand Up @@ -301,6 +305,10 @@ UPDATE_INTERVAL is the number of minutes between exchange rate updates.</string>
</dict>
<key>variables</key>
<dict>
<key>DECIMAL_PLACES</key>
<string>2</string>
<key>DECIMAL_SEPARATOR</key>
<string>.</string>
<key>UPDATE_INTERVAL</key>
<string>360</string>
</dict>
Expand Down
43 changes: 1 addition & 42 deletions src/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,12 @@
info.py --openhelp
info.py --openunits
info.py --currencies [<query>]
info.py --places <query>
Options:
-h, --help Show this message
--openhelp Open help file in default browser
--openunits Open custom units file in default editor
--currencies View/search supported currencies
--places Set decimal places
"""

Expand All @@ -40,7 +38,6 @@
from docopt import docopt

from workflow import (
ICON_HELP,
ICON_INFO,
ICON_SETTINGS,
ICON_WARNING,
Expand All @@ -54,8 +51,8 @@
CRYPTO_CURRENCIES,
CURRENCY_CACHE_NAME,
CUSTOM_DEFINITIONS_FILENAME,
DECIMAL_PLACES_DEFAULT,
ICON_CURRENCY,
ICON_HELP,
KEYWORD_SETTINGS,
README_URL,
)
Expand Down Expand Up @@ -143,28 +140,6 @@ def handle_delimited_query(query):

wf.send_feedback()

elif mode == 'places':

if query:
if not query.isdigit():
wf.add_item(u'Invalid number : {}'.format(query),
'Please enter a number',
icon=ICON_WARNING)
else:
wf.add_item(u'Set decimal places to : {}'.format(query),
u'↩ to save',
valid=True,
arg='--places {}'.format(query),
icon=ICON_SETTINGS)
else:
wf.add_item('Enter a number of decimal places',
'Current number is {}'.format(
wf.settings.get('decimal_places',
DECIMAL_PLACES_DEFAULT)),
icon=ICON_INFO)

wf.send_feedback()


def main(wf):
"""Run Script Filter.
Expand Down Expand Up @@ -196,14 +171,6 @@ def main(wf):
subprocess.call(['open', path])
return 0

if args.get('--places'):
value = int(query)
log.debug('setting `decimal_places` to %r', value)
wf.settings['decimal_places'] = value
print('Set decimal places to {}'.format(value))
# subprocess.call(['osascript', '-e', ALFRED_AS])
return

# Parse query ------------------------------------------------------

if DELIMITER in query:
Expand All @@ -225,14 +192,6 @@ def main(wf):
autocomplete=u'currencies {} '.format(DELIMITER),
icon=ICON_CURRENCY),

dict(title=('Decimal Places in Results '
'(current : {})'.format(
wf.settings.get('decimal_places',
DECIMAL_PLACES_DEFAULT))),
subtitle='View and search list of supported currencies',
autocomplete=u'places {} '.format(DELIMITER),
icon=ICON_SETTINGS),

dict(title='Edit Custom Units',
subtitle='Add and edit your own custom units',
valid=True,
Expand Down

0 comments on commit 71868f8

Please sign in to comment.