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 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
|
#!/usr/bin/env python3
#------------------------------------------------------------------------------
# Copyright: 2013
# Author: Dewey Garrett <dgarrett@panix.com>
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#------------------------------------------------------------------------------
"""gremlin_view
Provide class: GremlinView for gremlin with buttons for simpler embedding
Standalone functionality if linuxcnc running
A default ui file (gremlin_view.ui) is provided for a default
button arrangement but a user may provide their own by supplying
the glade_file argument.
The following objects are mandatory:
'gremlin_view_window' toplevel window
'gremlin_view_hal_gremlin' hal_gremlin
'gremlin_view_box' HBox or VBox' containing hal_gremlin
Optional radiobutton group names:
'select_p_view'
'select_x_view'
'select_y_view'
'select_z_view'
'select_z2_view'
Optional Checkbuttons names:
'enable_dro'
'show_machine_speed
'show_distance_to_go'
'show_limits'
'show_extents'
'show_tool'
'show_metric'
Callbacks are provided for the following buttons actions
on_clear_live_plotter_clicked
on_enable_dro_clicked
on_zoomin_pressed
on_zoomout_pressed
on_pan_x_minus_pressed
on_pan_x_plus_pressed
on_pan_y_minus_pressed
on_pan_y_plus_pressed
on_show_tool_clicked
on_show_metric_clicked
on_show_extents_clicked
on_select_p_view_clicked
on_select_x_view_clicked
on_select_y_view_clicked
on_select_z_view_clicked
on_select_z2_view_clicked
on_show_distance_to_go_clicked
on_show_machine_speed_clicked
on_show_limits_clicked
"""
import gi
gi.require_version("Gtk","3.0")
from gi.repository import Gtk
from gi.repository import GObject
from gi.repository import GLib
import os
import sys
import gladevcp.hal_actions # reqd for Builder
import linuxcnc
import time
import subprocess
import gettext
import datetime
import glib # for glib.GError
g_ui_dir = linuxcnc.SHARE + "/linuxcnc"
g_periodic_secs = 1 # integer
g_delta_pixels = 10
g_move_delay_secs = 0.2
g_progname = os.path.basename(sys.argv[0])
g_verbose = False
LOCALEDIR = linuxcnc.SHARE + "/locale"
gettext.install("linuxcnc", localedir=LOCALEDIR)
def ini_check ():
"""set environmental variable and change directory"""
# Note:
# hal_gremlin gets INI file from os.environ (only)
# hal_gremlin expects cwd to be same as INI file
ini_filename = get_linuxcnc_ini_file()
if ini_filename is not None:
os.putenv('INI_FILE_NAME',ini_filename) # ineffective
os.environ['INI_FILE_NAME'] = ini_filename # need for hal_gremlin
os.chdir(os.path.dirname(ini_filename))
if g_verbose:
print(('ini_check: INI_FILENAME= %s' % ini_filename))
print(('ini_check: curdir= %s' % os.path.curdir))
return True # success
print((_('%s: LinuxCNC INI file not available') % g_progname))
return False # exit here crashes glade-gtk2
def get_linuxcnc_ini_file():
"""find LinuxCNC INI file with pgrep"""
ps = subprocess.Popen('ps -C linuxcncsvr --no-header -o args'.split(),
stdout=subprocess.PIPE
)
p,e = ps.communicate()
if p is not None: p=p.decode()
if e is not None: e=e.decode()
if ps.returncode:
print(_('get_linuxcnc_ini_file: stdout= %s') % p)
print(_('get_linuxcnc_ini_file: stderr= %s') % e)
return None
ans = p.split()[p.split().index('-ini')+1]
return ans
class GremlinView():
"""Implement a standalone gremlin with some buttons
and provide means to embed using a glade ui file"""
def __init__(self
,glade_file=None #None: use default ui
,parent=None
,width=None
,height=None
,alive=True
,gtk_theme_name="Follow System Theme"
):
self.alive = alive
linuxcnc_running = False
if ini_check():
linuxcnc_running = True
if not linuxcnc_running:
print("gremlin_view: LinuxCNC must be running")
sys.exit(1)
if (glade_file == None):
glade_file = os.path.join(g_ui_dir,'gremlin_view.ui')
print("gremlin_view glade_file=",glade_file)
bldr = Gtk.Builder()
try:
bldr.add_from_file(glade_file)
except glib.GError as detail:
print('\nGremlinView:%s\n' % detail)
raise glib.GError(detail) # re-raise
# required objects:
self.topwindow = bldr.get_object('gremlin_view_window')
self.gbox = bldr.get_object('gremlin_view_box')
self.halg = bldr.get_object('gremlin_view_hal_gremlin')
#self.halg.show_lathe_radius = 1 # for test, hal_gremlin default is Dia
if not linuxcnc_running:
# blanks display area:
self.halg.set_has_window(False)
# radiobuttons for selecting view: (expect at least one)
select_view_letters = ['p','x','y','z','z2']
for vletter in select_view_letters:
try:
obj = bldr.get_object('select_' + vletter + '_view')
self.my_view = vletter # first letter found is initial view
break
except:
continue
check_button_objects = ['enable_dro'
,'show_machine_speed'
,'show_distance_to_go'
,'show_limits'
,'show_extents'
,'show_tool'
,'show_metric'
]
for objname in check_button_objects:
obj = bldr.get_object(objname)
if obj is not None:
setattr(self,'objname',obj)
obj.set_active(True)
else:
if g_verbose:
print('%s: Optional object omitted <%s>'
% (__file__,objname))
# show_metric: use INI file
#FIXME show_metric,lunits s/b mandatory?
try:
objname = 'show_metric'
self.show_metric = bldr.get_object('show_metric')
lunits = self.halg.inifile.find('TRAJ','LINEAR_UNITS')
except AttributeError:
if g_verbose:
print('%s: Problem for <%s>' % (__file__,objname))
if linuxcnc_running:
if lunits == 'inch':
self.halg.metric_units = False
elif lunits == 'mm':
self.halg.metric_units = True
else:
raise AttributeError('%s: unknown [TRAJ]LINEAR_UNITS] <%s>'
% (__file__,lunits))
if self.halg.get_show_metric():
self.show_metric.set_active(True)
else:
self.show_metric.set_active(False)
if alive:
bldr.connect_signals(self)
# todo: to remove other signals on halg:
# bldr.disconnect(integer_handle_id)
# bldr.disconnect_by_func('func_name')
# bldr.handler_disconnect()
minwidth = 300 # smallest size
minheight = 300 # smallest size
if (width is None):
width = minwidth
else:
width = int(width)
if (height is None):
height = minheight
else:
height = int(height)
if width < minwidth:
width = minwidth
if height < minheight:
height = minheight
# err from gremlin if omit this
self.halg.width = width
self.halg.height = height
self.halg.set_size_request(width,height)
# self.x,self.y used in conjunction with pan buttons
# but using mouse may change internal values in gremlin
# resulting in unexpected movement if both mouse and
# pan buttons are used
self.x = 0
self.y = 0
# prevent flashing topwindow
self.topwindow.iconify()
self.topwindow.show_all()
self.topwindow.hide()
self.preview_file(None)
if linuxcnc_running:
try:
self.preview_file(None)
except linuxcnc.error as detail:
print('linuxcnc.error')
print(' detail=',detail)
try:
self.last_file = self.halg._current_file
except AttributeError:
self.last_file = None
self.last_file_mtime = None
self.parent = parent
if self.parent is None:
# topwindow (standalone) application
# print "TOP:",gtk_theme_name
screen = self.topwindow.get_screen()
else:
# print "REPARENT:",gtk_theme_name
screen = self.halg.get_screen()
# not valid for Gtk3:
# settings = Gtk.settings_get_for_screen(screen)
# systname = settings.get_property("gtk-theme-name")
# if ( (gtk_theme_name is None)
# or (gtk_theme_name == "")
# or (gtk_theme_name == "Follow System Theme")):
# gtk_theme_name = systname
# settings.set_string_property('gtk-theme-name',gtk_theme_name,"")
self.topwindow.connect('destroy',self._topwindowquit)
self.topwindow.show_all()
self.running = True
if self.last_file is not None:
self.topwindow.set_title(g_progname
+ ': ' + os.path.basename(self.last_file))
self.last_file_mtime = datetime.datetime.fromtimestamp(
os.path.getmtime(self.last_file))
self.ct = 0
if self.parent is None: self.topwindow.deiconify()
self._periodic('BEGIN')
GLib.timeout_add_seconds(g_periodic_secs,self._periodic,'Continue')
# or use GLib.timeout_add() interval units in mS
def _periodic(self,arg):
# print "_periodic:",self.ct,arg
self.ct +=1
self.halg.poll()
if (self.parent is not None) and (self.ct) == 2:
# not sure why delay is needed for reparenting
# but without, the display of the (rgb) axes
# and the cone to not appear in gremlin
# print "REPARENT:",self.gbox, self.parent
#-----------------------------------------------------------------------------
# determine if glade interface designer is running
# to avoid assertion error:
# gtk_widget_reparent_fixup_child: assertion failed: (client_data != NULL)
is_glade = False
if 'glade' in sys.argv[0] and 'gladevcp' not in sys.argv[0]:
for d in os.environ['PATH'].split(':'):
f = os.path.join(d,sys.argv[0])
if ( os.path.isfile(f)
and os.access(f, os.X_OK)):
is_glade = True
break
#-----------------------------------------------------------------------------
if (not is_glade):
self.gbox.reparent(self.parent)
self.gbox.show_all()
self.gbox.connect('destroy',self._gboxquit)
return True
try:
current_file = self.halg._current_file
except AttributeError:
current_file = None
if current_file is None:
return True # keep trying _periodic()
current_file_mtime = datetime.datetime.fromtimestamp(
os.path.getmtime(current_file))
if ( current_file != self.last_file
or current_file_mtime != self.last_file_mtime):
# print('old,new',self.last_file_mtime,current_file_mtime)
self.last_file = current_file
self.last_file_mtime = current_file_mtime
self.halg.hide()
self.halg.load()
getattr(self.halg,'set_view_%s' % self.my_view)()
self.halg.show()
if self.topwindow is not None:
self.topwindow.set_title(g_progname
+ ': ' + os.path.basename(self.last_file))
return True # repeat _periodic()
def preview_file(self,filename):
self.halg.hide()
# handle exception in case glade is running
try:
self.halg.load(filename or None)
except Exception as detail:
if self.alive:
print("file load fail:",Exception,detail)
pass
getattr(self.halg,'set_view_%s' % self.my_view)()
self.halg.show()
def _gboxquit(self,w):
self.running = False # stop periodic checks
def _topwindowquit(self,w):
self.running = False # stop periodic checks
Gtk.main_quit()
def expose(self):
self.halg.expose()
def on_zoomin_pressed(self,w):
while w.get_state() == Gtk.StateType.ACTIVE:
self.halg.zoomin()
time.sleep(g_move_delay_secs)
Gtk.main_iteration_do(blocking=0)
def on_zoomout_pressed(self,w):
while w.get_state() == Gtk.StateType.ACTIVE:
self.halg.zoomout()
time.sleep(g_move_delay_secs)
Gtk.main_iteration_do(blocking=0)
def on_pan_x_minus_pressed(self,w):
while w.get_state() == Gtk.StateType.ACTIVE:
self.x -= g_delta_pixels
self.halg.translate(self.x,self.y)
time.sleep(g_move_delay_secs)
Gtk.main_iteration_do(blocking=0)
def on_pan_x_plus_pressed(self,w):
while w.get_state() == Gtk.StateType.ACTIVE:
self.x += g_delta_pixels
self.halg.translate(self.x,self.y)
time.sleep(g_move_delay_secs)
Gtk.main_iteration_do(blocking=0)
def on_pan_y_minus_pressed(self,w):
while w.get_state() == Gtk.StateType.ACTIVE:
self.y += g_delta_pixels
self.halg.translate(self.x,self.y)
time.sleep(g_move_delay_secs)
Gtk.main_iteration_do(blocking=0)
def on_pan_y_plus_pressed(self,w):
while w.get_state() == Gtk.StateType.ACTIVE:
self.y -= g_delta_pixels
self.halg.translate(self.x,self.y)
time.sleep(g_move_delay_secs)
Gtk.main_iteration_do(blocking=0)
def on_clear_live_plotter_clicked(self,w):
self.halg.clear_live_plotter()
def on_enable_dro_clicked(self,w):
if w.get_active():
self.halg.enable_dro = True
else:
self.halg.enable_dro = False
self.expose()
def on_show_machine_speed_clicked(self,w):
if w.get_active():
self.halg.show_velocity = True
else:
self.halg.show_velocity = False
self.expose()
def on_show_distance_to_go_clicked(self,w):
if w.get_active():
self.halg.show_dtg = True
else:
self.halg.show_dtg = False
self.expose()
def on_show_limits_clicked(self,w):
if w.get_active():
self.halg.show_limits = True
else:
self.halg.show_limits = False
self.expose()
def on_show_extents_clicked(self,w):
if w.get_active():
self.halg.show_extents_option = True
else:
self.halg.show_extents_option = False
self.expose()
def on_show_tool_clicked(self,w):
if w.get_active():
self.halg.show_tool = True
else:
self.halg.show_tool = False
self.expose()
def on_show_metric_clicked(self,w):
if w.get_active():
self.halg.metric_units = True
else:
self.halg.metric_units = False
self.expose()
def on_select_p_view_clicked(self,w):
self.set_view_per_w(w,'p')
def on_select_x_view_clicked(self,w):
self.set_view_per_w(w,'x')
def on_select_y_view_clicked(self,w):
self.set_view_per_w(w,'y')
def on_select_z_view_clicked(self,w):
self.set_view_per_w(w,'z')
def on_select_z2_view_clicked(self,w):
self.set_view_per_w(w,'z2')
def set_view_per_w(self,w,vletter):
self.my_view = vletter
getattr(self.halg,'set_view_%s' % vletter)()
#-----------------------------------------------------------------------------
# Standalone (and demo) usage:
def standalone_gremlin_view():
import getopt
#---------------------------------------
def usage(msg=None):
print(("""\n
Usage: %s [options]\n
Options: [-h | --help]
[-v | --verbose]
[-W | --width] width
[-H | --height] height
[-f | --file] glade_file
Note: linuxcnc must be running on same machine
""") % g_progname)
if msg:
print('\n%s' % msg)
#---------------------------------------
glade_file = None
width = None
height = None
vbose = False
try:
options,remainder = getopt.getopt(sys.argv[1:]
, 'f:hH:vW:'
, ['file='
,'help'
,'width='
,'height='
]
)
except getopt.GetoptError as msg:
usage()
print('GetoptError: %s' % msg)
sys.exit(1)
for opt,arg in options:
if opt in ('-h','--help'):
usage(),sys.exit(0)
if opt in ('-v','--verbose'):
g_verbose = True
continue
if opt in ('-W','--width' ): width=arg
if opt in ('-H','--height'): height=arg
if opt in ('-f','--file'): glade_file=arg
if remainder:
usage('unknown argument:%s' % remainder)
sys.exit(1)
try:
g = GremlinView(glade_file=glade_file
,width=width
,height=height
)
Gtk.main()
except linuxcnc.error as detail:
Gtk.main()
print('linuxcnc.error:',detail)
usage()
# vim: sts=4 sw=4 et
|