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
|
#!/usr/bin/env python3
# GladeVcp Widget - calculator input
# This widgets allows simple calculations.
# The result can be returned for further use.
# Originally to be used as numerical input on a touch screen.
#
# Copyright (c) 2012 Chris Morley
#
# 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 2 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.
import sys, os
import math
# localization
import locale
locale.setlocale( locale.LC_ALL, '' )
datadir = os.path.abspath( os.path.dirname( __file__ ) )
BASE = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), ".."))
LOCALEDIR = os.path.join(BASE, "share", "locale")
locale.bindtextdomain("linuxcnc", LOCALEDIR)
import gi
gi.require_version("Gtk","3.0")
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GObject
from gi.repository import Pango
class Calculator( Gtk.VBox ):
__gtype_name__ = 'Calculator'
__gproperties__ = {
'is_editable' : ( GObject.TYPE_BOOLEAN, 'Is Editable', 'Ability to use a keyboard to enter data',
False, GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT ),
'font' : ( GObject.TYPE_STRING, 'Pango Font', 'Display font to use',
"sans 12", GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT ),
}
__gproperties = __gproperties__
def __init__( self, *a, **kw ):
Gtk.VBox.__init__( self, *a, **kw )
self.preset_value = None
self.eval_string = ""
self.font = "sans 12"
self.is_editable = False
self.integer_only = False
self.has_num_pad_only = False
self.wTree = Gtk.Builder()
self.wTree.set_translation_domain("linuxcnc") # for locale translations
self.wTree.add_from_file( os.path.join( datadir, "calculator.glade" ) )
dic = {
"on_displayText_activate" : self.displayText,
"on_displayText_changed" : self.displayText_changed,
"on_CLR_clicked" : self.displayClr,
"on_Pi_clicked" : self.displayPi,
"on_Left_bracket_clicked" : self.displayLeftBracket,
"on_Right_bracket_clicked" : self.displayRightBracket,
"on_Seven_clicked" : self.displaySeven,
"on_Eight_clicked" : self.displayEight,
"on_Nine_clicked" : self.displayNine,
"on_Divide_clicked" : self.displayDiv,
"on_Four_clicked" : self.displayFour,
"on_Five_clicked" : self.displayFive,
"on_Six_clicked" : self.displaySix,
"on_Multiply_clicked" : self.displayMultiply,
"on_One_clicked" : self.displayOne,
"on_Two_clicked" : self.displayTwo,
"on_Three_clicked" : self.displayThree,
"on_Minus_clicked" : self.displayMinus,
"on_Zero_clicked" : self.displayZero,
"on_Dot_clicked" : self.displayDot,
"on_Equal_clicked" : self.displayEqual,
"on_Add_clicked" : self.displayAdd,
"on_Backspace_clicked" : self.displayBackspace,
"on_mm_inch_clicked" : self.displayMmInch,
"on_inch_mm_clicked" : self.displayInchMm,
"on_ok_button_clicked" : self.on_ok_button_clicked,
"on_cancel_button_clicked" : self.on_cancel_button_clicked
}
self.wTree.connect_signals( dic )
self.entry = self.wTree.get_object( "displayText" )
self.entry.modify_font( Pango.FontDescription( self.font ) )
self.calc_box = self.wTree.get_object( "calc_box" )
self.calc_box.set_vexpand(True)
self.calc_box.set_hexpand(True)
self.table = self.wTree.get_object("table1")
self.window = self.calc_box.get_parent()
self.window.remove(self.calc_box)
self.add(self.calc_box)
# Use CSS style for buttons
screen = Gdk.Screen.get_default()
provider = Gtk.CssProvider()
style_context = Gtk.StyleContext()
style_context.add_provider_for_screen(screen, provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
css = b"button {padding: 0;}"
provider.load_from_data(css)
def num_pad_only( self, value ):
self.has_num_pad_only = value
objects = ["Left_bracket", "Right_bracket", "Pi", "Divide", "Multiply",
"Add", "Minus", "Equal", "Inch_mm", "mm_Inch", "Backspace", "CLR",
"Inch_mm", "mm_Inch", "cancel_button", "ok_button"]
if value:
for i in objects:
self.table.remove(self.wTree.get_object(i))
if self.integer_only:
col_offs = 0
else:
col_offs = 1
self.table.resize(5, 3+col_offs)
# reorder items to fit size-reduced table
self.table.attach(self.wTree.get_object("Backspace"), 1, 2, 0, 1)
self.table.attach(self.wTree.get_object("CLR"), 2, 3, 0, 1)
self.table.attach(self.wTree.get_object("cancel_button"), 1+col_offs, 2+col_offs, 4, 5)
self.table.attach(self.wTree.get_object("ok_button"), 2+col_offs, 3+col_offs, 4, 5)
self.show_all()
def integer_entry_only( self, value ):
if value:
self.table.remove(self.wTree.get_object('Dot'))
self.integer_only = True
else:
self.integer_only = False
def set_editable( self, value ):
self.is_editable = value
self.entry.set_editable( value )
def set_font( self, font ):
self.font = font
self.entry.modify_font( Pango.FontDescription( font ) )
def set_value( self, value ):
val = value
try:
val = str( locale.format_string( "%f", float( val ) ).rstrip( "0" ) )
if val[-1] == locale.localeconv()["decimal_point"]:
val = val.rstrip( locale.localeconv()["decimal_point"] )
except:
value = "Error"
self.delete()
self.displayOperand( str( val ) )
self.preset_value = value
def get_value( self ):
self.compute()
try:
value = self.wTree.get_object( "displayText" ).get_text()
return locale.atof( value )
except:
return None
# print( "value in get value = ", value )
# print( "converted value in get value = ", locale.atof( value ) )
def get_preset_value( self ):
return self.preset_value
def compute( self ):
qualified = ''
# print"string:",self.eval_string
temp = self.eval_string.strip( " " ).replace("Pi", "math.pi")
# this loop adds only spaces around the mentioned operators
for i in( '-', '+', '/', '*', 'math.pi', '(', ')' ):
new = " %s " % i
temp = temp.replace( i, new )
for i in temp.split():
# print ( "i in compute = ", i )
try:
i = str( locale.atof( i ) )
# print ( "converted i in compute = ", i )
except:
pass
if i.isdigit():
qualified = qualified + str( float( i ) )
else:
qualified = qualified + i
try :
if self.integer_only:
b = str( int( eval( qualified ) ) )
else:
b = str( eval( qualified ) )
except:
b = "Error"
print("Calculator widget error, string:", self.eval_string, sys.exc_info()[0])
self.eval_string = ''
else : self.eval_string = b
# if locale.localeconv()["decimal_point" = comma ,
# we have to replace the internal dot by a comma,
# otherwise it will be interpreted as an thousend separator
try:
b = locale.format_string( "%f", float( b ) ).rstrip( "0" )
if b[-1] == locale.localeconv()["decimal_point"]:
b = b.rstrip( locale.localeconv()["decimal_point"] )
except:
b = "Error"
self.wTree.get_object( "displayText" ).set_text( b )
self.eval_string = b + " " # add space to indicate that calculation was last
def delete( self ):
self.eval_string = ''
self.wTree.get_object( "displayText" ).set_text( "" )
def displayOperand( self, i ):
if self.wTree.get_object( "displayText" ).get_selection_bounds():
self.delete()
if "Error" in self.eval_string:
self.eval_string = ""
# clear text area when entering a number after a finished calculation
#if i.isdigit():
if i not in "+-*/" and self.eval_string != "":
if self.eval_string[-1] == " ":
self.eval_string = ""
self.eval_string = self.eval_string + i
self.wTree.get_object( "displayText" ).set_text( str( self.eval_string ) )
def displayText_changed( self, widget ):
self.eval_string = widget.get_text()
def displayText( self, widget ):
pass
# self.compute()
def displayClr( self, widget ):
self.delete()
def displayBackspace( self, widget ):
text = self.wTree.get_object( "displayText" ).get_text()
if(text == "Error"):
self.delete()
else:
if text[-2:] == "Pi":
self.wTree.get_object( "displayText" ).set_text(text[:-2])
else:
self.wTree.get_object( "displayText" ).set_text(text[:-1])
def displayLeftBracket( self, widget ):
self.displayOperand( "(" )
def displayRightBracket( self, widget ):
self.displayOperand( ")" )
def displaySeven( self, widget ):
self.displayOperand( "7" )
def displayEight( self, widget ):
self.displayOperand( "8" )
def displayNine( self, widget ):
self.displayOperand( "9" )
def displayFour( self, widget ):
self.displayOperand( "4" )
def displayFive( self, widget ):
self.displayOperand( "5" )
def displaySix( self, widget ):
self.displayOperand( "6" )
def displayOne( self, widget ):
self.displayOperand( "1" )
def displayTwo( self, widget ):
self.displayOperand( "2" )
def displayThree( self, widget ):
self.displayOperand( "3" )
def displayZero( self, widget ):
self.displayOperand( "0" )
def displayDot( self, widget ):
self.displayOperand( locale.localeconv()["decimal_point"] )
def displayPi( self, widget ):
self.displayOperand( "Pi" )
def displayDiv( self, widget ):
self.displayOperand( "/" )
def displayMultiply( self, widget ):
self.displayOperand( "*" )
def displayMinus( self, widget ):
self.displayOperand( "-" )
def displayEqual( self, widget ):
self.compute()
def displayAdd( self, widget ):
self.displayOperand( "+" )
def displayMmInch( self, widget ):
self.eval_string = "("+ self.eval_string + ") / " + locale.format("%f", float(25.4))
self.compute()
def displayInchMm( self, widget ):
self.eval_string = "("+ self.eval_string + ") * " + locale.format("%f", float(25.4))
self.compute()
def on_ok_button_clicked ( self, widget ):
dialog = self.calc_box.get_toplevel()
dialog.response(Gtk.ResponseType.ACCEPT)
def on_cancel_button_clicked ( self, widget ):
dialog = self.calc_box.get_toplevel()
dialog.response(Gtk.ResponseType.REJECT)
def do_get_property( self, property ):
name = property.name.replace( '-', '_' )
if name in list(self.__gproperties.keys()):
return getattr( self, name )
else:
raise AttributeError( 'unknown property %s' % property.name )
def do_set_property( self, property, value ):
try:
name = property.name.replace( '-', '_' )
if name == 'is_editable':
self.set_editable( value )
if name == 'font':
self.set_font( value )
except:
pass
# for testing without glade editor:
def main():
window = Gtk.Dialog( "My dialog",
None,
modal=True, destroy_with_parent=True )
calc = Calculator()
window.vbox.add( calc )
window.connect( "destroy", Gtk.main_quit )
calc.set_value( 2.5 )
calc.set_font( "sans 25" )
calc.set_editable( True )
window.show_all()
response = window.run()
if response == Gtk.ResponseType.ACCEPT:
print(calc.get_value())
else:
print(calc.get_preset_value())
if __name__ == "__main__":
main()
|