~davidc3/onehundredscopes/calculator

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
#! /usr/bin/python
# -*- coding: latin-1 -*-

#Copyright (c) 2011 David Calle <davidc@framli.eu>

#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.
import sys, os
from gi.repository import GLib, GObject, Gio
from gi.repository import Dee
_m = dir(Dee.SequenceModel)
from gi.repository import Unity
import socket

socket.setdefaulttimeout(5)
BUS_NAME = "net.launchpad.scope.math.calculator"

class Daemon:
	def __init__ (self):
		self.scope = Unity.Scope.new ("/net/launchpad/scope/math/calculator")
		self.scope.search_in_global = False
		self.scope.connect ("notify::active-search", self.on_search_changed)
		self.scope.connect ("notify::active-global-search", self.on_search_changed)
		self.scope.connect ("notify::active", self.on_search_changed)
		self.scope.connect ("filters-changed", self.on_search_changed);
		self.scope.connect ("activate-uri", self.on_activate_uri);
		self.scope.export()

	def on_activate_uri (self, scope, uri):
		import gtk
		clipboard = gtk.clipboard_get()
		clipboard.set_text(uri)
		clipboard.store()
		GLib.spawn_command_line_async("notify-send -i gtk-copy '%s'" % uri)
		return Unity.ActivationResponse(handled=Unity.HandledType.HIDE_DASH, goto_uri='')

	def get_search_string (self):
		search = self.scope.props.active_global_search
		if search is None:
			search = self.scope.props.active_search
		return search.props.search_string if search else None

	def on_search_changed (self, scope, param_spec=None):
			search = self.get_search_string()
			print "Search changed to: '%s'" % search
			results_global = self.scope.props.global_results_model
			results_global.clear()
			self.update_results_model (search, results_global)
			results_global.flush_revision_queue ()

	def update_results_model(self, search, model):
	
	
		self.calc(search,model)

	def calc(self, search, model):
		icon = "gnome-calculator"
		if search.lower().find(" in ") > -1:
			print "Currency conversion mode"
			search = search.upper()
			mode = 0
			#FIXME I CAN HAZ ICON PLZ
			icon = "http://tanghus.files.wordpress.com/2009/10/currency-converter-128.png"
		else:
			mode = 1
			search = search.replace(' ','')
		search = search.replace(',','.')
		search = search.replace('pi','π')
		search = search.replace('"','')
		search = search.replace('\'','')
		search = search.replace('&','')
		search = search.replace('|','')
		search = search.replace(';','')
		search = search.replace('&','')

		hint = search
		hint = hint.replace('\(','(')
		hint = hint.replace('\)',')')
		hint = hint.replace('sqrt','√')
		print "Operation: %s" % search

		if mode == 1:
			print "Operation mode"
			operation = 'gcalctool -s \"%s\"' % str(search)
			calc_result = Command(operation).run(timeout=1)
		if mode == 0:
			import commands
			try:
				calc_result=commands.getoutput('gcalctool -s \"%s\"' % str(search))
				calc_result = calc_result.split('\n')[-1]
				calc_result = calc_result.replace(",", ".")
				calc_result = round(float(calc_result),4)
				calc_result =str(calc_result)
			except (ValueError):
				pass
		# We don't catch GCalctool related errors,
		# they are useful in the output
		# and don't affect the scope.
		print "Result: %s" % calc_result
		if search:
			if not (calc_result.startswith("Argument")) and not (calc_result.startswith("Error")) and not (calc_result == ''):
				model.append(calc_result, icon, 0, "text/html", calc_result, hint, '')

import subprocess, threading
class Command(object):
    def __init__(self, cmd):
        self.cmd = cmd
        self.process = None
        self.result = None
        

    def run(self, timeout):
        result = None
        def target():
            self.process = subprocess.Popen(self.cmd, shell=True, stdout=subprocess.PIPE)
            self.result = self.process.communicate()[0].split('\n')[0]

        thread = threading.Thread(target=target)
        
        thread.start()
        
        thread.join(timeout)
        
        if thread.is_alive():
            pid = str(self.process.pid+1)
            subprocess.Popen("kill "+pid, shell=True)
            self.process.terminate()
            thread.join()
        return self.result

if __name__ == "__main__":
	session_bus_connection = Gio.bus_get_sync (Gio.BusType.SESSION, None)
	session_bus = Gio.DBusProxy.new_sync (session_bus_connection, 0, None,
	  'org.freedesktop.DBus',
	  '/org/freedesktop/DBus',
	  'org.freedesktop.DBus', None)
	result = session_bus.call_sync('RequestName',
	   GLib.Variant ("(su)", (BUS_NAME, 0x4)),
	   0, -1, None)
	   
	# Unpack variant response with signature "(u)". 1 means we got it.
	result = result.unpack()[0]
	
	if result != 1 :
		print >> sys.stderr, "Failed to own name %s. Bailing out." % BUS_NAME
		raise SystemExit (1)
	
	daemon = Daemon()
	GObject.MainLoop().run()