Import LinuxCNC source tree

This commit is contained in:
Wang Dequan
2026-08-20 06:17:39 +08:00
commit 2c814634c3
9429 changed files with 10556013 additions and 0 deletions

View File

@@ -0,0 +1,15 @@
at the moment to use designer one must create links from (hardy),
Wheezy uses slightly different location
/usr/lib/qt4/designer/python/ (linuxcnc plugins)
to:
RIP_folder /lib/python/qtvcp_widgets/widget_plugins/ (linuxcnc plugins)
for testing purposes there are two test files in RIP_folder /lib/python/qtvcp.
test1.ui is for hal only widgets
loadusr qtvcp test1.ui
test2.ui is for testing/interacting with a running linuxcnc session.
test2 requires the handler file, qtvcp_handler to be loaded.
loadusr qtvcp -u qtvcp_handler test2.ui

View File

172
lib/python/qtvcp/core.py Normal file
View File

@@ -0,0 +1,172 @@
#!/usr/bin/env python3
# vim: sts=4 sw=4 et
import linuxcnc
from gi.repository import GObject
import inspect
import _hal
import hal
import traceback
from qtpy.QtCore import QObject, QTimer, Signal
from common.hal_glib import GStat
from common.iniinfo import _IStat as IStatParent
from qtvcp.qt_halobjects import Qhal as QHAL
from qtvcp.qt_halobjects import QPin as QPIN
# Set up logging
from common import logger
log = logger.getLogger(__name__)
# Force the log level for this module
# log.setLevel(logger.INFO) # One of DEBUG, INFO, WARNING, ERROR, CRITICAL, VERBOSE
# The order of these classes is importanr, otherwise - circular imports.
# the some of the later classes reference the earlier classes
################################################################
# IStat class
################################################################
class Info(IStatParent):
_instance = None
_instanceNum = 0
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = IStatParent.__new__(cls, *args, **kwargs)
return cls._instance
# get filter extensions in QT format
def get_qt_filter_extensions(self):
all_extensions = []
try:
for k, v in self.PROGRAM_FILTERS:
k = k.replace('.', ' *.')
k = k.replace(',', ' ')
all_extensions.append((';;%s (%s)' % (v, k)))
all_extensions.append((';;All (*)'))
temp = ''
for i in all_extensions:
temp = '%s %s' % (temp, i)
return temp
except Exception as e:
log.warning('Qt filter Extension Parsing Error: {}\n Using Default: ALL (*)'.format(e))
return ('All (*)')
###############################################################
# HAL Object clases
###############################################################
class QPin(QPIN):
def __init__(self, *a, **kw):
super(QPin, self).__init__(*a, **kw)
class Qhal(QHAL):
def __init__(self, comp=None, hal=None):
super(Qhal, self).__init__(comp, hal)
################################################################
# GStat class
################################################################
# use the same Gstat as gladeVCP uses
# by subclassing it
class Status(GStat):
_instance = None
_instanceNum = 0
__gsignals__ = {
'toolfile-stale': (GObject.SignalFlags.RUN_FIRST, GObject.TYPE_NONE, (GObject.TYPE_PYOBJECT,)),
}
# only make one instance of the class - pass it to all other
# requested instances
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = GStat.__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self):
# only initialize once for all instances
if self.__class__._instanceNum >= 1:
return
GObject.Object.__init__(self)
self.__class__._instanceNum += 1
super(GStat, self).__init__()
# can only have ONE error channel instance in qtvcp
self.ERROR = linuxcnc.error_channel()
self._block_polling = False
# we override this function from hal_glib
# add replace it with setTimer()
def set_timer(self, cycleTime=None):
pass
def setTimer(self, cycleTime=None):
GObject.threads_init()
GObject.timeout_add(int(cycleTime), self.update)
# error polling is usually set up by screen_option widget
# to call this function
# but when using MDI subprograms, the subprogram must be the only
# polling instance.
# this is done by blocking the main screen polling until the
# subprogram is done.
def poll_error(self):
if self._block_polling: return None
return self.ERROR.poll()
def block_error_polling(self, name=''):
if name: print(name,'block')
self._block_polling = True
def unblock_error_polling(self,name=''):
if name: print(name,'unblock')
self._block_polling = False
################################################################
# PStat class
################################################################
from qtvcp.qt_pstat import _PStat as _PStatParent
class Path(_PStatParent):
_instance = None
_instanceNum = 0
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = _PStatParent.__new__(cls, *args, **kwargs)
return cls._instance
################################################################
# Lcnc_Action class
################################################################
from qtvcp.qt_action import _Lcnc_Action as _ActionParent
class Action(_ActionParent):
_instance = None
_instanceNum = 0
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = _ActionParent.__new__(cls, *args, **kwargs)
return cls._instance
################################################################
# TStat class
################################################################
from qtvcp.qt_tstat import _TStat as _TStatParent
class Tool(_TStatParent):
_instance = None
_instanceNum = 0
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = _TStatParent.__new__(cls, *args, **kwargs)
return cls._instance

View File

@@ -0,0 +1,59 @@
Installation requirements for using QtVCP screens and panels.
All the requirements listed below can be installed by using the install_script located in the same directory as this file.
Recommended packages for viewing QtVCP screens or panels:
gstreamer1.0-tools
espeak
espeak-ng
sound-theme-freedesktop
python3-qtpy
python3-opengl
python3-pyqt5
python3-pyqt5.qsci
python3-pyqt5.qtsvg
python3-pyqt5.qtopengl
python3-opencv
python3-dbus
python3-dbus.mainloop.pyqt5
python3-espeak
python3-pyqt5.qtwebengine
python3-xlib
python3-numpy
python3-cairo
python3-gi-cairo
python3-poppler-qt5
pyqt5-dev-tools
-------------------------------------------------------------------------------
Below are requirements for using Designer to edit or create new QtVCP screens or panels:
Required packages:
qttools5-dev
qttools5-dev-tools
libpython3-dev
To enable LinuxCNC specific widgets to appear in Designer:
1. Create the plugin directory for designer to search:
mkdir -p ~/.designer/plugins/python
2. Copy the <pluginfile> to the above directory:
cp <pluginfile> ~/.designer/plugins/python/
The <pluginfile> is dependent on the type of LinuxCNC installation.
For a package installation:
/usr/lib/python3/dist-packages/qtvcp/plugins/qtvcp_plugin.py
For a RIP installation:
~/linuxcnc-dev/lib/python/qtvcp/plugins/qtvcp_plugin.py
Designer can now be run and the LinuxCNC widgets will be available.
For a RIP install only:
source ~/linuxcnc-dev/scripts/rip-environment
Start designer with:
designer -qt=5

View File

@@ -0,0 +1,116 @@
#!/bin/bash
# install base packages for displaying qtvcp screens and sounds
echo -e '\ninstalling common base packages'
sudo apt-get install -y gstreamer1.0-tools espeak espeak-ng sound-theme-freedesktop
echo -e '\ninstalling base packages for python3'
sudo apt-get install -y python3-qtpy python3-opengl python3-pyqt5 python3-pyqt5.qsci python3-pyqt5.qtsvg python3-pyqt5.qtopengl python3-opencv python3-dbus python3-dbus.mainloop.pyqt5 python3-espeak python3-pyqt5.qtwebengine python3-xlib python3-numpy python3-cairo python3-gi-cairo python3-poppler-qt5
echo -e '\ninstalling python3 tools'
sudo apt-get install -y pyqt5-dev-tools
# prompt to install designer
while true; do
# clear
echo -e '\nDo you wish to install Qt Designer for creating or modifying a GUI'
echo ' 1 = No, exit'
echo ' 2 = Yes, for a Run In Place installation'
echo ' 3 = Yes, for a package installation'
read -r -p $'\nSelection? ' response
case $response in
[1]* ) echo -e '\nInstallation complete, QtVCP screens are now available.\n'
exit;;
[2]* ) break;;
[3]* ) break;;
* ) echo -e '\nInstallation complete, QtVCP screens are now available.\n'
exit;;
esac
done
# install tools
#clear
echo -e '\ninstalling common tools'
sudo apt-get install -y qttools5-dev qttools5-dev-tools
echo -e '\ninstalling python3 tools'
sudo apt-get install -y libpython3-dev
# get the correct plugin file to copy
# for run in place LinuxCNC installation
if [ "$response" -eq 2 ]; then
if [ -f ~/linuxcnc-dev/lib/python/qtvcp/plugins/qtvcp_plugin.py ]; then
pifile=~/linuxcnc-dev/lib/python/qtvcp/plugins/qtvcp_plugin.py
else
while true; do
# clear
echo -e '\nrun in place installation not found'
echo 'Enter base directory name e.g. linuxcnc-2.9'
echo 'X to exit'
read -r -p $'\nDirectory? ' basedir
case $basedir in
[Xx]* ) clear
exit;;
* ) if [ -f ~/"$basedir"/lib/python/qtvcp/plugins/qtvcp_plugin.py ]; then
pifile=~/"$basedir"/lib/python/qtvcp/plugins/qtvcp_plugin.py
break
fi
;;
esac
done
fi
# for full LinuxCNC installation
elif [ "$response" -eq 3 ]; then
# check for valid plugin file
if [ -f /usr/lib/python3/dist-packages/qtvcp/plugins/qtvcp_plugin.py ]; then
pifile=/usr/lib/python3/dist-packages/qtvcp/plugins/qtvcp_plugin.py
else
# clear
echo -e '\n'"$pifile "'not found in /usr/lib/python3/dist-packages/qtvcp/plugins/'
echo -e '\ncannot continue designer installation\n'
exit
fi
fi
# create users plugin directory
mkdir -p ~/.designer/plugins/python
# link to plugins
if [ -f ~/.designer/plugins/python/qtvcp_plugin.py ]; then
sudo rm ~/.designer/plugins/python/qtvcp_plugin.py
fi
echo -e '\ncreate plugin link at:\n~/.designer/plugins/python/\n'
ln -s "$pifile" ~/.designer/plugins/python/
arch=$(uname -m)
sopath=/usr/lib/$arch-linux-gnu/qt5/plugins/designer/
p2sofile=libpyqt5_py2.so
p3sofile=libpyqt5.so
# ensure we have a python3 .so file
if [ ! -f "$sopath/$p3sofile" ]; then
# check if we have a python3 .so backup file from a python2 installation
if [ -f "$sopath/$p3sofile.old" ]; then
echo -e '\nrename libpyqt5.so.old file to libpyqt5.so'
sudo mv "$sopath/$p3sofile.old" "$sopath/$p3sofile"
# otherwise report an error
else
echo -e '\nlibpyqt5.so is missing from:'
echo -e '/usr/lib/x86_64-linux-gnu/qt5/plugins/designer/'
echo -e '\ndesigner installation aborted...\n'
exit
fi
fi
# remove python2 .so file if it exists
if [ -f "$sopath/$p2sofile" ]; then
echo -e '\nremove python2 .so file'
sudo rm "$sopath/$p2sofile"
fi
#clear
echo -e '\nInstallation complete, designer can be started with:'
echo -e '\ndesigner -qt=5\n'
if [ "$response" -eq 2 ]; then
echo -e 'After setting the rip-environment\n'
fi

View File

View File

@@ -0,0 +1,298 @@
#!/usr/bin/env python3
# qtVcp library audio player
#
# Copyright (c) 2017 Chris Morley <chrisinnanaimo@hotmail.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.
# This library is used to play sounds launched from STATUS messages
# it has uses OS builtin sounds or can play arbritray files
#######################################################################
# Set up logging
from qtvcp import logger
LOG = logger.getLogger(__name__)
import os
import subprocess
# try to add ability for audio feedback to user.
PY_LIB_GOOD = GST_LIB_GOOD = True
try:
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst
Gst.init(None)
except Exception as e:
print(e)
LOG.warning('audio alerts - Is python3-gst1.0 installed?')
PY_LIB_GOOD = False
p = subprocess.Popen('gst-launch-1.0', shell=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, close_fds=True)
output, error = p.communicate()
if p.returncode > 1:
LOG.warning('no audio alerts available - Is gstreamer-1.0-tools installed?')
GST_LIB_GOOD = False
from qtvcp.core import Status
# Instaniate the libraries with global reference
# STATUS gives us status messages from linuxcnc
STATUS = Status()
ESPEAK = False
try:
from espeak import espeak
import queue
esQueue = queue.Queue()
espeak.set_voice("m3")
espeak.set_parameter(espeak.Parameter.Rate,160)
espeak.set_parameter(espeak.Parameter.Pitch,1)
ESPEAK = True
except:
LOG.warning('audio alerts - Is python3-espeak installed? (sudo apt install python3-espeak)')
try:
subprocess.check_output('''espeak --help''', shell=True)
ESPEAK = True
except:
LOG.warning('audio alerts - Is espeak installed? (sudo apt install espeak)')
LOG.warning('Text to speech output not available. ')
def speak_synth_callback(*args):
# when sentences ends, start the next one, until there are none.
if args[0] == espeak.event_MSG_TERMINATED:
if not esQueue.empty():
espeak.synth(esQueue.get())
# the player class does the work of playing the audio hints
# http://pygstdocs.berlios.de/pygst-tutorial/introduction.html
class Player:
def __init__(self):
self.set_sounds()
if PY_LIB_GOOD:
self.player = Gst.ElementFactory.make("playbin", "player")
self.player.set_property("uri", "file://" + self.error)
# Enable message bus to check for errors in the pipeline
bus = self.player.get_bus()
bus.add_signal_watch()
bus.connect("message", self.on_message)
try:
espeak.set_SynthCallback(speak_synth_callback)
except Exception as e:
pass
# set sounds based on distribution
def set_sounds(self):
try:
import distro
if 'mint' in distro.id().lower():
self.error = '/usr/share/sounds/LinuxMint/stereo/dialog-error.ogg'
self.warning ='/usr/share/sounds/freedesktop/stereo/dialog-warning.oga'
self.ready = '/usr/share/sounds/LinuxMint/stereo/dialog-information.ogg'
self.done = '/usr/share/sounds/LinuxMint/stereo/system-ready.ogg'
self.attention = '/usr/share/sounds/LinuxMint/stereo/dialog-question.wav'
self.ring = '/usr/share/sounds/LinuxMint/stereo/phone-incoming-call.ogg'
self.login = '/usr/share/sounds/LinuxMint/stereo/desktop-login.ogg'
self.logout = '/usr/share/sounds/LinuxMint/stereo/desktop-logout.ogg'
self.bell = '/usr/share/sounds/freedesktop/stereo/bell.oga'
if not os.path.exists(self.error):
LOG.error('Audio player - Mint sound File not found {}'.format(self.error))
return
except:
pass
self.error = '/usr/share/sounds/freedesktop/stereo/dialog-error.oga'
self.warning ='/usr/share/sounds/freedesktop/stereo/dialog-warning.oga'
self.ready = '/usr/share/sounds/freedesktop/stereo/message.oga'
self.done = '/usr/share/sounds/freedesktop/stereo/complete.oga'
self.attention = '/usr/share/sounds/freedesktop/stereo/suspend-error.oga'
self.ring = '/usr/share/sounds/freedesktop/stereo/phone-incoming-call.oga'
self.login = '/usr/share/sounds/freedesktop/stereo/service-login.oga'
self.logout = '/usr/share/sounds/freedesktop/stereo/service-logout.oga'
self.bell = '/usr/share/sounds/freedesktop/stereo/bell.oga'
if not os.path.exists(self.error):
LOG.error('Audio player - Default sound File not found {}'.format(self.error))
# play sounds on these messages from GStat
# play-sound allows an arbrtrary absolute file name
# play-alert uses internal builtins
# use the function name les 'play_'
def _register_messages(self):
if PY_LIB_GOOD:
STATUS.connect('play-sound', self.jump)
elif GST_LIB_GOOD:
STATUS.connect('play-sound', self.os_jump)
# jump to a builtin alert sound
# This uses the system to play the sound because gst is not available
# this can still fail if gstreamer/tools are not available
def os_jump(self, w, f):
if 'beep' in f.lower():
self[f.lower()]()
return
elif 'speak' in f.lower():
self.os_speak(f)
return
path = os.path.expanduser(f)
if not os.path.exists(path):
path = self[f.lower()]
if not os.path.exists(path):
LOG.error('Audio player using system - file not found {}'.format(path))
return
try:
cmd = '''gst-launch-1.0 playbin uri='file://%s' ''' % path
self.p = subprocess.Popen(cmd, shell=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, close_fds=True)
except:
LOG.error('Audio player using system - file not found {}'.format(f))
# jump to a builtin alert sound
# we use this so we can trap errors easily
def jump(self, w, f):
if 'beep' in f.lower():
self[f.lower()]()
return
elif 'speak' in f.lower():
self.os_speak(f)
return
if self.player.get_state(Gst.State.NULL) == Gst.State.PLAYING:
self.player.set_state(Gst.State.NULL)
sfile = os.path.expanduser(f)
if os.path.exists(sfile):
self.player.set_property("uri", "file://" + sfile)
self.player.set_state(Gst.State.PLAYING)
else:
try:
self['play_%s' % f.lower()]()
except:
LOG.error('Audio player - Canned alert not found {}: {}'.format(f, self[f.lower()]))
# this gets messages back from GStreamer to control playback
def on_message(self, bus, message):
t = message.type
if t == Gst.MessageType.EOS:
# file ended, stop
self.player.set_state(Gst.State.NULL)
elif t == Gst.MessageType.ERROR:
# Error occurred, print and stop
self.player.set_state(Gst.State.NULL)
err, debug = message.parse_error()
LOG.error('Audio player - Error {}'.format(err, debug))
# print "Error: %s" % err, debug
# play builtin alert sounds
def play_error(self):
self.player.set_property("uri", "file://" + self.error)
self.player.set_state(Gst.State.PLAYING)
def play_warning(self):
self.player.set_property("uri", "file://" + self.warning)
self.player.set_state(Gst.State.PLAYING)
def play_ready(self):
self.player.set_property("uri", "file://" + self.ready)
self.player.set_state(Gst.State.PLAYING)
def play_attention(self):
self.player.set_property("uri", "file://" + self.attention)
self.player.set_state(Gst.State.PLAYING)
def play_ring(self):
self.player.set_property("uri", "file://" + self.ring)
self.player.set_state(Gst.State.PLAYING)
def play_done(self):
self.player.set_property("uri", "file://" + self.done)
self.player.set_state(Gst.State.PLAYING)
def play_login(self):
self.player.set_property("uri", "file://" + self.logout)
self.player.set_state(Gst.State.PLAYING)
def play_logout(self):
self.player.set_property("uri", "file://" + self.login)
self.player.set_state(Gst.State.PLAYING)
def play_bell(self):
self.player.set_property("uri", "file://" + self.bell)
self.player.set_state(Gst.State.PLAYING)
################
# beep functions
################
def beep_ring(self):
os.system('''for n in 1 2 3 ; do
for f in 1 2 1 2 1 2 1 2 1 2 ; do
beep -f ${f}000 -l 20
done
done''')
def beep_start(self):
os.system('''beep -f165.4064 -l100 -n -f130.813 -l100 -n \
-f261.626 -l100 -n -f523.251 -l100 -n -f1046.50 -l100 \
-n -f2093.00 -l100 -n -f4186.01 -l10''')
def beep(self):
os.system("beep -f 555 ")
###################
# Espeak functions
###################
def os_speak(self, f):
cmd = f.lower().lstrip('speak')
if ESPEAK:
if '_kill_' in cmd:
if espeak.is_playing():
self.speak_cancel()
return
try:
# uses a queue so doesn't speak over it's self.
esQueue.put(cmd)
if not espeak.is_playing():
espeak.synth(esQueue.get())
except Exception as e:
#print ('oops',e)
# fallback call the system espeak - no queue used
os.system('''espeak -s 160 -v m3 -p 1 "%s" &''' % cmd)
def speak_cancel(self):
espeak.cancel()
##############################
# required class boiler code #
##############################
def __getitem__(self, item):
return getattr(self, item)
def __setitem__(self, item, value):
return setattr(self, item, value)
if __name__ == "__main__":
import gi
from gi.repository import GLib
try:
test = Player()
test.play_error()
test.os_speak("hello world")
test.os_speak("goodbye")
print('done')
G = GLib.MainLoop()
G.run()
except Exception as e:
print(e)

View File

@@ -0,0 +1,234 @@
#!/usr/bin/env python3
# Qtvcp workpiece height measurement
#
# Copyright (c) 2022 Jim Sloot <persei802@gmail.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.
import sys
import os
import linuxcnc
import json
from qtpy import QtCore, QtGui, QtWidgets, uic
from qtpy.QtWidgets import QMessageBox
from qtpy.QtCore import QProcess
from qtvcp.core import Info, Status, Action, Path
from qtvcp import logger
INFO = Info()
STATUS = Status()
ACTION = Action()
PATH = Path()
LOG = logger.getLogger(__name__)
HERE = os.path.dirname(os.path.abspath(__file__))
#current_dir = os.path.dirname(__file__)
#SUBPROGRAM = os.path.abspath(os.path.join(current_dir, 'height_subprog.py'))
SUBPROGRAM = os.path.join(PATH.LIBDIR, 'touchoff_subprogram.py')
class Auto_Measure(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Auto_Measure, self).__init__(parent)
self.w = parent
self.stat = linuxcnc.stat()
self.proc = None
if INFO.MACHINE_IS_METRIC:
self.valid = QtGui.QDoubleValidator(-999.999, 999.999, 3)
else:
self.valid = QtGui.QDoubleValidator(-999.9999, 999.9999, 4)
# Load the widgets UI file:
self.filename = os.path.join(HERE, 'auto_height.ui')
try:
self.instance = uic.loadUi(self.filename, self)
except AttributeError as e:
print("Error: ", e)
self.send_dict = {}
self.parm_list = ['search_vel',
'probe_vel',
'max_probe',
'retract_distance',
'z_safe_travel',
'pos_x1',
'pos_y1',
'pos_z1',
'pos_x2',
'pos_y2',
'pos_z2']
# define validators for all lineEdit widgets
for i in self.parm_list:
self['lineEdit_' + i].setValidator(self.valid)
# initialize input values
self.lineEdit_search_vel.setText("0.0")
self.lineEdit_probe_vel.setText("0.0")
self.lineEdit_max_probe.setText("0.0")
self.lineEdit_retract_distance.setText("0.0")
self.lineEdit_z_safe_travel.setText("0.0")
self.lineEdit_pos_x1.setText("100.0")
self.lineEdit_pos_y1.setText("100.0")
self.lineEdit_pos_z1.setText("20.0")
self.lineEdit_pos_x2.setText("200.0")
self.lineEdit_pos_y2.setText("200.0")
self.lineEdit_pos_z2.setText("10.0")
self.lineEdit_height.setText('---')
# set up Help messagebox
help_file = open(os.path.join(HERE,"auto_height.txt"), "r")
help_text = help_file.read()
self.mb = QMessageBox()
self.mb.setIcon(QMessageBox.Information)
self.mb.setWindowTitle("Auto Workpiece Height Measurement")
self.mb.setText("Auto Height Measure")
self.mb.setInformativeText(help_text)
self.mb.setStandardButtons(QMessageBox.Ok)
# signal connections
self.chk_enable_set.stateChanged.connect(self.chk_enable_changed)
self.btn_read_settings.pressed.connect(self.btn_read_pressed)
self.btn_set_wp.clicked.connect(self.set_position_clicked)
self.btn_set_machine.clicked.connect(self.set_position_clicked)
self.btn_start.clicked.connect(self.start)
self.btn_help.clicked.connect(lambda obj: self.mb.show())
def _hal_init(self):
self.actionbutton_abort.hal_init()
def homed_on_status():
return (STATUS.machine_is_on() and (STATUS.is_all_homed() or INFO.NO_HOME_REQUIRED))
STATUS.connect('state_off', lambda w: self.setEnabled(False))
STATUS.connect('state_estop', lambda w: self.setEnabled(False))
STATUS.connect('interp-idle', lambda w: self.setEnabled(homed_on_status()))
STATUS.connect('all-homed', lambda w: self.setEnabled(True))
def start_process(self):
self.proc = QProcess()
self.proc.setReadChannel(QProcess.StandardOutput)
self.proc.started.connect(self.process_started)
self.proc.readyReadStandardOutput.connect(self.read_stdout)
self.proc.readyReadStandardError.connect(self.read_stderror)
self.proc.finished.connect(self.process_finished)
self.proc.start('python3 {}'.format(SUBPROGRAM))
def process_started(self):
LOG.info("Height_subprogram started with PID {}\n".format(self.proc.processId()))
self.add_status("Height measurement process started")
def read_stdout(self):
qba = self.proc.readAllStandardOutput()
line = qba.data()
self.parse_input(line)
def read_stderror(self):
qba = self.proc.readAllStandardError()
line = qba.data()
self.parse_input(line)
def process_finished(self, exitCode, exitStatus):
LOG.verbose(("Probe Process finished - exitCode {} exitStatus {}".format(exitCode, exitStatus)))
self.add_status("Height measurement process finished")
self.proc = None
def parse_input(self, line):
line = line.decode("utf-8")
LOG.verbose("Raw returned Line={}".format(line))
if "INFO" in line:
pass
# print(line)
elif "ERROR" in line:
STATUS.unblock_error_polling()
ACTION.SET_ERROR_MESSAGE('Height measurement process finished in error')
# print(line)
elif "DEBUG" in line:
pass
#print(line)
elif "COMPLETE" in line:
STATUS.unblock_error_polling()
LOG.info("Probing routine completed without errors")
return_data = line.rstrip().split('$')
data = json.loads(return_data[1])
self.show_result(data)
else:
LOG.error("Error parsing return data from sub_processor. Line={}".format(line))
def chk_enable_changed(self, state):
self.btn_set_wp.setEnabled(state)
self.btn_set_machine.setEnabled(state)
def btn_read_pressed(self):
self.lineEdit_search_vel.setText(self.w.lineEdit_search_vel.text())
self.lineEdit_probe_vel.setText(self.w.lineEdit_probe_vel.text())
self.lineEdit_max_probe.setText(self.w.lineEdit_max_probe.text())
self.lineEdit_retract_distance.setText(self.w.lineEdit_retract_distance.text())
self.lineEdit_z_safe_travel.setText(self.w.lineEdit_z_safe_travel.text())
def set_position_clicked(self):
btn = self.sender().property('btn')
xyz = []
self.stat.poll()
pos = self.stat.actual_position
off = self.stat.g5x_offset
tlo = self.stat.tool_offset
for i in range(3):
xyz.append(pos[i] - off[i] - tlo[i])
if btn == "wp":
self.lineEdit_pos_x1.setText(format(xyz[0], '.3f'))
self.lineEdit_pos_y1.setText(format(xyz[1], '.3f'))
self.lineEdit_pos_z1.setText(format(xyz[2], '.3f'))
self.add_status("Probe position 1 set (X {} Y {} Z {})".format(
format(xyz[0], '.3f'),format(xyz[1], '.3f'),format(xyz[2], '.3f')))
elif btn == "mp":
self.lineEdit_pos_x2.setText(format(xyz[0], '.3f'))
self.lineEdit_pos_y2.setText(format(xyz[1], '.3f'))
self.lineEdit_pos_z2.setText(format(xyz[2], '.3f'))
self.add_status("Probe position 2 set (X {} Y {} Z {})".format(
format(xyz[0], '.3f'),format(xyz[1], '.3f'),format(xyz[2], '.3f')))
def start(self):
if float(self.lineEdit_z_safe_travel.text()) <= float(self.lineEdit_pos_z1.text()):
self.add_status("ERROR: Travel height less than P1 Z height")
return
if float(self.lineEdit_z_safe_travel.text()) <= float(self.lineEdit_pos_z2.text()):
self.add_status("ERROR: Travel height less than P2 Z height")
return
if self.proc is not None:
self.add_status("Height measurement process is busy")
return
self.start_process()
self.send_dict = {key: self['lineEdit_' + key].text() for key in (self.parm_list)}
string_to_send = 'probe_z' + '$' + json.dumps(self.send_dict) + '\n'
# print("String to send ", string_to_send)
STATUS.block_error_polling()
self.proc.writeData(bytes(string_to_send, 'utf-8'))
def show_result(self, data):
diff = float(data['z1']) - float(data['z2'])
self.lineEdit_height.setText(format(diff, '.3f'))
if self.chk_autofill.isChecked():
self.w.lineEdit_work_height.setText(format(diff, '.3f'))
self.add_status("Height measurement successfully completed with {}".format(format(diff, '.3f')))
def add_status(self, message):
self.lbl_status.setText(message)
STATUS.emit('update-machine-log', message, 'TIME')
# required code for subscriptable iteration
def __getitem__(self, item):
return getattr(self, item)
def __setitem__(self, item, value):
return setattr(self, item, value)
# for standalone testing
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = Auto_Measure()
w.show()
sys.exit( app.exec() )

View File

@@ -0,0 +1,39 @@
This program probes 2 user specified locations in the Z axis and calculates the difference in heights.
Enable Probe Position Set Buttons
- when checked, the SET buttons are enabled
- this allows the user to automatically fill in the X, Y and Z parameters with the current position as displayed on the DROs.
Autofill Workpiece Height on Main Screen
- when checked, the calculated height is automatically transferred to the Workpice Height field in the main screen.
- otherwise, the main screen is not affected
Workpiece Probe At
- the X, Y and Z coordinates specify where the first probing routine should start, in current WCS
Machine Probe At
- the X, Y and Z coordinates specify where the second probing routine should start, in current WCS
Z Safe Travel Height
- the machine is raised to the Z safe travel height before jogging to the X and Y coordinates
- the spindle then lowers to the specified Z coordinate
- it should be selected so that the tool clears all obstructions while jogging
START button
- the machine will jog to the first location and then probe down
- the machine then jogs to the second location and probes down again
- the difference in probed values is reported as Calculated Workpiece Height
- the parameters for search velocity, probe velocity, maximum probe distance and return distance are read from the main GUI Settings page.
ABORT button
- causes all jog and probe routines currently executing to stop
HELP button
- displays this help file
* NOTE: Any 2 points within the machine operating volume can be specified.
If the first point is higher than the second, the calculated height will be a positive number.
If the first point is lower than the second, the calculated height will be a negative number.
Units are irrelevant in this program. The probed values are not saved and only the difference is reported.
* CAUTION: Setting incorrect values can lead to crashes into fixtures on the machine work surface. Initial testing with no tool and safe heights is recommended.

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

View File

@@ -0,0 +1,127 @@
import hal
import os
import subprocess
import threading
import time
from qtvcp.core import Action, Path
ACTION = Action()
PATH = Path()
# path to TCL for external programs eg. halshow
try:
TCLPATH = os.environ['LINUXCNC_TCL_DIR']
INIPATH = os.environ.get('INI_FILE_NAME', '/dev/null')
except:
pass
class Aux_program_loader:
def _init_(self):
pass
# check for classicladder realtime if so load the user GUI
def load_ladder(self, *args):
if hal.component_exists('classicladder_rt'):
p = os.popen("classicladder &", "w")
else:
ACTION.SET_ERROR_MESSAGE("Classiclader's realtime component is not present\n So the user component will not be loaded.")
def load_gcode_ripper(self,*args):
if args:
pass
else:
p = os.popen('python3 {}'.format(os.path.join(PATH.LIBDIR, 'ripper/gcode_ripper.py')))
# opens halshow
def load_halshow(self, *args):
if args:
self.load_haltool_args('halshow', args)
else:
p = os.popen("tclsh %s/bin/halshow.tcl &" % (TCLPATH))
# opens the calibration program
def load_calibration(self):
p = os.popen("tclsh %s/bin/emccalib.tcl -- -ini %s > /dev/null &" % (TCLPATH, INIPATH), "w")
# opens the linuxcnc status program
def load_status(self, *args):
p = os.popen("linuxcnctop > /dev/null &", "w")
# opens a halmeter
def load_halmeter(self, *args):
if args:
self.load_haltool_args('halmeter', args)
else:
p = os.popen("halmeter &")
# opens the halscope
def load_halscope(self, *args):
if args:
self.load_haltool_args('halscope', args)
else:
p = os.popen("halscope > /dev/null &", "w")
# open linuxcnc standard tool edit program
def load_tooledit(self, filepath):
p = os.popen("tooledit %s" % (filepath))
def load_test_button(self, *args):
if args:
p = os.popen("qtvcp {} test_button".format(args), "w")
else:
p = os.popen("qtvcp test_button", "w")
def load_test_led(self, *args):
if args:
p = os.popen("qtvcp {} test_led".format(args), "w")
else:
p = os.popen("qtvcp test_led", "w")
def load_test_dial(self, *args):
if args:
p = os.popen("qtvcp {} test_dial".format(args), "w")
else:
p = os.popen("qtvcp test_dial", "w")
def keyboard_onboard(self, args="", width="", height=""):
try:
self.ob = subprocess.Popen(["onboard", args, width, height],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
close_fds=True)
if 'xid' in args:
idnum = self.ob.stdout.readline()
return idnum
else:
return True
except:
print('Onboard keyboard could not be loaded by aux_program_loader')
return False
def new_thread(self, args):
try:
reply = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except Exception as e:
pass
stdout, stderr = reply.communicate()
if stdout:
self.threadError = stdout.decode()
if stderr:
self.threadError = stderr.decode()
# used via above functions to open halshow, halmeter, or halscope with arguments
def load_haltool_args(self, tool, args):
args = args[0].split()
args.insert(0, tool)
self.threadError = ''
t = threading.Thread(target=self.new_thread, args=(args,), daemon=True)
t.start()
#this delay is necessary to allow the thread to finish on error
time.sleep(0.5)
if self.threadError:
if 'Cannot read file' in self.threadError:
err = 'AUX LOAD ERROR:\nCannot open \'{}\'\n'.format(args[1:][0])
elif 'is not a valid probe type' in self.threadError:
err = 'AUX LOAD ERROR:\n\'{}\' is not a valid probe type\n'.format(args[1:][0])
ACTION.SET_ERROR_MESSAGE(err)

View File

@@ -0,0 +1,149 @@
#!/usr/bin/env python3
# Copyright (c) 2017 Kurt Jacobson
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import re
from copy import copy
from logging import Formatter
PREFIX = '\033['
SUFFIX = '\033[0m'
COLORS = {
'black': 30,
'red': 31,
'green': 32,
'yellow': 33,
'blue': 34,
'magenta': 35,
'cyan': 36,
'white': 37,
'bgred': 41,
'bggreen': 42,
'bgyellow': 43,
'bggrey': 100
}
MAPPING = {
'VERBOSE': 'bggrey',
'DEBUG': 'blue',
'INFO': 'cyan',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bgred',
}
# Returns `text` warped in ASCII escape codes to produce `color`
def COLORIZE(text, color=None):
seq = COLORS.get(color, 37) # default to white
return '{0}{1}m{2}{3}'.format(PREFIX, seq, text, SUFFIX)
# Matches only the first `color<text>` occurrence
# ^(.*?)<([^)]+)>
# Matches all `color<text>` occurrences, both take the same number of steps
# ([^<\s]+)<([^>]+)>
# (\w+)<([^>]+)>
RE = re.compile(r'(\w+)<([^>]+)>')
class ColoredFormatter(Formatter):
def __init__(self, pattern):
Formatter.__init__(self, pattern)
# Override the Formatter's format method to add ASCII colors
# to the levelname and any marked words in the log message.
def format(self, record):
colored_record = copy(record)
# Add colors to levelname
levelname = colored_record.levelname
color = MAPPING.get(levelname, 'white')
colored_record.levelname = COLORIZE(levelname, color)
# Add colors to tagged message text
msg = colored_record.getMessage()
plain_msg, color_msg = self.color_words(msg)
record.msg = plain_msg
colored_record.msg = color_msg
return Formatter.format(self, colored_record)
# Replace `color<message>` in the log message with ASCII codes to colorize
# the word or phrase in the terminal log handler. Also return a cleaned
# version of the message with the tags removed for use by the file handler.
def color_words(self, raw_msg):
plain_msg = color_msg = raw_msg
if '<' in raw_msg: # If no tag don't try to match
iterator = RE.finditer(raw_msg)
if iterator:
for match in iterator:
group = match.group()
color = match.group(1)
word = match.group(2)
# Could be optimized, but will rarely have more than one match
color_msg = color_msg.replace(group, COLORIZE(word, color))
plain_msg = plain_msg.replace(group, word)
return plain_msg, color_msg
# ----------------------- E X A M P L E -----------------------
if __name__ == '__main__':
import logging
# Create logger
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
# Add console handler
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
cf = ColoredFormatter("[%(name)s][%(levelname)s] %(message)s (%(filename)s:%(lineno)d)")
ch.setFormatter(cf)
log.addHandler(ch)
# Add file handler
fh = logging.FileHandler('demo.log')
fh.setLevel(logging.DEBUG)
ff = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(ff)
log.addHandler(fh)
# Log some stuff
log.debug("Logging demo has green<STARTED>")
log.info("Logging to yellow<demo.log> in the script dir")
log.warning("This is my last warning, red<take heed>")
log.error("This is an error")
log.critical("He's dead, Jim")
# Example exception logging
try:
print(False + "True")
except Exception as e:
log.debug('That did not work!', exc_info=e)

View File

@@ -0,0 +1,466 @@
#!/usr/bin/env python3
import sys
import os
import numpy as np
import tempfile
import atexit
import shutil
from qtpy import QtGui, QtWidgets, uic
from qtpy.QtCore import QFile, QRegularExpression
from qtpy.QtWidgets import QFileDialog, QMessageBox
from linuxcnc import OPERATOR_ERROR, NML_ERROR
from qtvcp.core import Info, Status, Action, Path
INFO = Info()
STATUS = Status()
ACTION = Action()
PATH = Path()
HERE = os.path.dirname(os.path.abspath(__file__))
IMAGES = os.path.join(PATH.IMAGEDIR, 'gcode_utility')
class Facing(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Facing, self).__init__(parent)
# Load the widgets UI file:
self.filename = os.path.join(HERE, 'facing.ui')
try:
self.instance = uic.loadUi(self.filename, self)
except AttributeError as e:
print("Error: ", e)
# set up Help messagebox
help_file = open(os.path.join(HERE,"facing_help.txt"), "r")
help_text = help_file.read()
self.mb = QMessageBox()
self.mb.setIcon(QMessageBox.Information)
self.mb.setWindowTitle("Facing Help")
self.mb.setText(help_text)
self.mb.setStandardButtons(QMessageBox.Ok)
STATUS.connect('forced-update',lambda w:self.init())
def init(self):
# Initial values
self._tmp = None
self.unit_code = "G21"
if not STATUS.is_metric_mode():
self.unit_code = "G20"
self.rbtn_inch.click()
self.rpm = INFO.get_error_safe_setting("DISPLAY", "DEFAULT_SPINDLE_0_SPEED", 500)
self.size_x = 100
self.size_y = 100
self.feedrate = 0
self.stepover = 5 if STATUS.is_metric_mode() else 0.5
self.tool_dia = 10 if STATUS.is_metric_mode() else 1
self.safe_z = 20.0 if STATUS.is_metric_mode() else 1
self.valid = True
self.units_text = ''
self.units_changed()
# set defaults
self.lineEdit_tool.setText(str(self.tool_dia))
self.lineEdit_spindle.setText(str(self.rpm))
self.lineEdit_feedrate.setText(str(self.feedrate))
self.lineEdit_stepover.setText(str(self.stepover))
self.lineEdit_size_x.setText(str(self.size_x))
self.lineEdit_size_y.setText(str(self.size_y))
self.lineEdit_comment.setText('Face slabbing Program')
self.checked = QtGui.QPixmap(os.path.join(IMAGES, 'checked.png'))
self.unchecked = QtGui.QPixmap(os.path.join(IMAGES, 'unchecked.png'))
# signal connections
self.btn_validate.clicked.connect(self.validate)
self.btn_create.clicked.connect(self.create_program)
self.btn_send.clicked.connect(self.send_program)
self.rbtn_mm.clicked.connect(self.units_changed)
self.rbtn_inch.clicked.connect(self.units_changed)
self.rbtn_raster_0.clicked.connect(self.raster_changed)
self.rbtn_raster_45.clicked.connect(self.raster_changed)
self.rbtn_raster_90.clicked.connect(self.raster_changed)
self.rbtn_raster_climb_across.clicked.connect(self.raster_changed)
self.rbtn_raster_climb_in.clicked.connect(self.raster_changed)
self.btn_help.clicked.connect(lambda obj: self.mb.show())
self.validate()
self.raster_changed()
def units_changed(self):
if self.rbtn_inch.isChecked():
text = "IN"
self.unit_code = "G20"
self.safe_z = 1.0
else:
text = "MM"
self.unit_code = "G21"
self.safe_z = 20.0
self.lbl_feed_unit.setText(text + "/MIN")
self.lbl_tool_unit.setText(text)
self.lbl_stepover_unit.setText(text)
self.lbl_size_unit.setText(text)
self.units_text = ("**NOTE - All units are in {}".format(text))
self.set_validator()
def set_validator(self):
# set valid input formats for lineEdits
if self.rbtn_inch.isChecked():
valid_size = QtGui.QRegularExpressionValidator(QRegularExpression('[0-9]{0,6}[.][0-9]{0,4}'))
valid_step = QtGui.QRegularExpressionValidator(QRegularExpression('[0-9]{0,6}[.][0-9]{0,2}'))
valid_feed = QtGui.QRegularExpressionValidator(QRegularExpression('[0-9]{0,6}[.][0-9]{0,3}'))
else:
valid_size = QtGui.QRegularExpressionValidator(QRegularExpression('[0-9]{0,6}[.][0-9]{0,3}'))
valid_step = QtGui.QRegularExpressionValidator(QRegularExpression('[0-9]{0,5}[.][0-9]{0,1}'))
valid_feed = QtGui.QRegularExpressionValidator(QRegularExpression('[0-9]{0,5}[.][0-9]{0,1}'))
self.lineEdit_tool.setValidator(valid_size)
self.lineEdit_spindle.setValidator(QtGui.QRegularExpressionValidator(QRegularExpression('[0-9]{0,5}')))
self.lineEdit_feedrate.setValidator(valid_feed)
self.lineEdit_stepover.setValidator(valid_step)
self.lineEdit_size_x.setValidator(valid_size)
self.lineEdit_size_y.setValidator(valid_size)
def raster_changed(self):
if self.rbtn_raster_0.isChecked():
pixmap = QtGui.QPixmap(os.path.join(IMAGES, 'raster_0.png'))
elif self.rbtn_raster_45.isChecked():
pixmap = QtGui.QPixmap(os.path.join(IMAGES, 'raster_45.png'))
elif self.rbtn_raster_90.isChecked():
pixmap = QtGui.QPixmap(os.path.join(IMAGES, 'raster_90.png'))
elif self.rbtn_raster_climb_across.isChecked():
pixmap = QtGui.QPixmap(os.path.join(IMAGES, 'raster_climb_across.png'))
elif self.rbtn_raster_climb_in.isChecked():
pixmap = QtGui.QPixmap(os.path.join(IMAGES, 'raster_climb_in.png'))
self.lbl_image.setPixmap(pixmap)
def validate(self):
self.valid = True
# check for valid size
try:
self.size_x = float(self.lineEdit_size_x.text())
self.size_y = float(self.lineEdit_size_y.text())
if self.size_x > 0.0 and self.size_y > 0.0:
self.lbl_size_ok.setPixmap(self.checked)
else:
self.lbl_size_ok.setPixmap(self.unchecked)
except:
self.valid = False
self.lbl_size_ok.setPixmap(self.unchecked)
# check for valid spindle rpm
try:
self.rpm = int(self.lineEdit_spindle.text())
if self.rpm == 0:
self.valid = False
self.lbl_spindle_ok.setPixmap(self.unchecked)
else:
self.lbl_spindle_ok.setPixmap(self.checked)
except:
self.valid = False
self.lbl_spindle_ok.setPixmap(self.unchecked)
# check for valid feedrate
try:
self.feedrate = float(self.lineEdit_feedrate.text())
if self.feedrate == 0.0:
self.valid = False
self.lbl_feed_ok.setPixmap(self.unchecked)
else:
self.lbl_feed_ok.setPixmap(self.checked)
except:
self.valid = False
self.lbl_feed_ok.setPixmap(self.unchecked)
# check for valid tool
try:
tool = float(self.lineEdit_tool.text())
if tool == 0:
self.valid = False
self.lbl_tool_ok.setPixmap(self.unchecked)
else:
self.lbl_tool_ok.setPixmap(self.checked)
except:
tool = 0.0
self.valid = False
self.lbl_tool_ok.setPixmap(self.unchecked)
self.tool_dia = tool
# check for valid stepover
try:
self.stepover = float(self.lineEdit_stepover.text())
if self.stepover == 0 \
or self.stepover > self.tool_dia \
or (self.stepover * 2) > min(self.size_x, self.size_y):
self.valid = False
self.lbl_stepover_ok.setPixmap(self.unchecked)
else:
self.lbl_stepover_ok.setPixmap(self.checked)
except:
self.valid = False
self.lbl_stepover_ok.setPixmap(self.unchecked)
def create_program(self):
self.validate()
if self.valid is False:
print("There are errors in input fields")
STATUS.emit('error', OPERATOR_ERROR, "Facing: There are errors in the input fields")
return
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getSaveFileName(self,"Save to file","","All Files (*);;ngc Files (*.ngc)", options=options)
if fileName:
self.calculate_toolpath(fileName)
else:
print("Program creation aborted")
def send_program(self):
self.validate()
if self.valid is False:
print("There are errors in input fields")
STATUS.emit('error', OPERATOR_ERROR, "Facing: There are errors in the input fields")
return
self._mktemp()
if self._tmp:
mp = os.path.join(self._tmp, os.path.basename('face.ngc'))
self.calculate_toolpath(mp)
ACTION.OPEN_PROGRAM(mp)
else:
print("send creation aborted")
def calculate_toolpath(self, fname):
comment = self.lineEdit_comment.text()
self.line_num = 5
self.file = open(fname, 'w')
# opening preamble
self.file.write("%\n")
self.file.write("({})\n".format(comment))
self.file.write("({})\n".format(self.units_text))
self.file.write("(Area: X {} by Y {})\n".format(self.size_x,self.size_y))
self.file.write("({} Tool Diameter with {} Stepover)\n".format(self.tool_dia, self.stepover))
self.file.write("\n")
self.next_line("{} G40 G49 G64 P0.03".format(self.unit_code))
self.next_line("G17")
self.next_line("G0 Z{}".format(self.safe_z))
# self.next_line("G0 X0.0 Y0.0")
self.next_line("S{} M3".format(self.rpm))
# self.next_line("G0 Z{}".format(self.safe_z / 2))
# self.next_line("G1 Z0.0 F{}".format(self.feedrate / 2))
# main section
if self.rbtn_raster_0.isChecked():
self.next_line("G0 X0.0 Y0.0")
self.next_line("G0 Z{}".format(self.safe_z / 2))
self.next_line("G1 Z0.0 F{}".format(self.feedrate / 2))
self.raster_0()
elif self.rbtn_raster_45.isChecked():
self.next_line("G0 X0.0 Y0.0")
self.next_line("G0 Z{}".format(self.safe_z / 2))
self.next_line("G1 Z0.0 F{}".format(self.feedrate / 2))
self.raster_45()
elif self.rbtn_raster_90.isChecked():
self.next_line("G0 X0.0 Y0.0")
self.next_line("G0 Z{}".format(self.safe_z / 2))
self.next_line("G1 Z0.0 F{}".format(self.feedrate / 2))
self.raster_90()
elif self.rbtn_raster_climb_across.isChecked():
start_x = self.size_x + self.tool_dia
# start_y = 0.0 - self.stepover
start_y = 0.0
self.next_line("G0 X{} Y{}".format(start_x, start_y))
self.next_line("G0 Z{}".format(self.safe_z / 2))
self.next_line("G1 Z0.0 F{}".format(self.feedrate / 2))
self.raster_climb_across()
elif self.rbtn_raster_climb_in.isChecked():
start_x = self.size_x + self.tool_dia
start_y = 0.0
self.next_line("G0 X{} Y{}".format(start_x, start_y))
self.next_line("G0 Z{}".format(self.safe_z / 2))
self.next_line("G1 Z0.0 F{}".format(self.feedrate / 2))
self.raster_climb_in()
else:
print("Fatal error occurred - exiting")
sys.exit()
# closing section
self.next_line("G0 Z{}".format(self.safe_z))
self.next_line("M2")
self.file.write("%\n")
self.file.close()
def btn_help_clicked(self, state):
self.mb.show()
def raster_0(self):
i = 1
x = (0.0, self.size_x)
next_x = self.size_x
next_y = 0.0
self.next_line("G1 X{} F{}".format(next_x, self.feedrate))
while next_y < self.size_y:
i ^= 1
next_x = x[i]
next_y = min(next_y + self.stepover, self.size_y)
self.next_line("Y{}".format(next_y))
self.next_line("X{}".format(next_x))
def raster_45(self):
# calculate coordinate arrays
ysteps = int(self.size_y // self.stepover)
xsteps = int(self.size_x // self.stepover)
left = np.empty(shape=(ysteps,2), dtype=float)
right = np.empty(shape=(ysteps,2), dtype=float)
bottom = np.empty(shape=(xsteps,2), dtype=float)
top = np.empty(shape=(xsteps,2), dtype=float)
ycoord = self.stepover
for i in range(ysteps):
left[i][0] = 0.0
left[i][1] = ycoord
ycoord += self.stepover
xcoord = ycoord - self.size_y
for i in range(xsteps):
top[i][0] = xcoord
top[i][1] = self.size_y
xcoord += self.stepover
xcoord = self.stepover
for i in range(xsteps):
bottom[i][0] = xcoord
bottom[i][1] = 0.0
xcoord += self.stepover
ycoord = xcoord - self.size_x
for i in range(ysteps):
right[i][0] = self.size_x
right[i][1] = ycoord
ycoord += self.stepover
# concatenate (left, top) and (bottom, right)
array1 = np.concatenate((left, top))
array2 = np.concatenate((bottom, right))
# move to start position
self.next_line("G1 Y{} F{}".format(array1[0][1], self.feedrate))
i = 0
# calculate toolpath
while 1:
self.next_line("X{} Y{}".format(array2[i][0], array2[i][1]))
if array2[i][1] == 0.0: # bottom row
if array2[i][0] == self.size_x: # bottom right corner
self.next_line("Y{}".format(self.stepover))
elif (array2[i][0] + self.stepover) <= self.size_x:
self.next_line("G91 X{}".format(self.stepover))
self.next_line("G90")
else:
self.next_line("X{}".format(self.size_x))
self.next_line("Y{}".format(right[0][1]))
elif array2[i][0] == self.size_x: # right side
if (array2[i][1] + self.stepover) <= self.size_y:
self.next_line("G91 Y{}".format(self.stepover))
self.next_line("G90")
else:
self.next_line("Y{}".format(self.size_y))
else:
print("FATAL ERROR")
return
i += 1
if i == len(array1 + 1): break
self.next_line("X{} Y{}".format(array1[i][0], array1[i][1]))
if array1[i][0] == 0.0: # left side
if array1[i][1] == self.size_y: # top left corner
self.next_line("X{}".format(self.stepover))
elif (array1[i][1] + self.stepover) <= self.size_y:
self.next_line("G91 Y{}".format(self.stepover))
self.next_line("G90")
else:
self.next_line("Y{}".format(self.size_y))
self.next_line("X{}".format(top[0][0]))
elif array1[i][1] == self.size_y: # top row
if (array1[i][0] + self.stepover) <= self.size_x:
self.next_line("G91 X{}".format(self.stepover))
self.next_line("G90")
else:
self.next_line("X{}".format(self.size_x))
else:
print("FATAL ERROR")
return
i += 1
if i == len(array1): break
def raster_90(self):
i = 1
y = (0.0, self.size_y)
next_x = 0.0
next_y = self.size_y
self.next_line("G1 Y{} F{}".format(next_y, self.feedrate))
while next_x < self.size_x:
i ^= 1
next_y = y[i]
next_x = min(next_x + self.stepover, self.size_x)
self.next_line("X{}".format(next_x))
self.next_line("Y{}".format(next_y))
def raster_climb_across(self):
# Remember 0,0 is at the lower left
start_x = self.size_x + self.tool_dia
end_x = 0.0 - self.tool_dia
# next_y = 0.0 - self.stepover
next_y = 0.0
self.next_line("G1 X{} F{}".format(end_x, self.feedrate))
while next_y < self.size_y:
# i ^= 1
# next_x = x[i]
# lift the spindle
self.next_line("G0 Z{} F{}".format(self.safe_z,self.feedrate))
next_y = min(next_y + self.stepover, self.size_y)
# Move back to the starting side (right)
self.next_line("G0 X{} Y{} F{}".format(start_x,next_y,self.feedrate))
# lower the spindle
self.next_line("G1 Z0.0 F{}".format(self.feedrate / 2))
# facing cut
self.next_line("G1 X{} F{}".format(end_x, self.feedrate))
def raster_climb_in(self):
# Remember 0,0 is at the lower left
left_x = 0.0
back_y = self.size_y
front_y = 0.0
right_x = self.size_x
# Walk around the outside (I'm assuming the stepover is 1/2 tool diameter)
while front_y < self.size_y/2:
self.next_line("G1 X{} F{}".format(left_x, self.feedrate)) # Front edge
front_y = front_y + self.stepover
self.next_line("G1 Y{}".format(back_y)) # Left edge
left_x = left_x + self.stepover
self.next_line("G1 X{}".format(right_x)) # Back edge
back_y = back_y - self.stepover
self.next_line("G1 Y{}".format(front_y)) # Right edge, stop before you get all the way to Y 0
right_x = right_x - self.stepover
# lift the spindle when done
self.next_line("G0 Z{} F{}".format(self.safe_z,self.feedrate))
def next_line(self, text):
self.file.write("N{} ".format(self.line_num) + text + "\n")
self.line_num += 5
def _mktemp(self):
if self._tmp:
return
self._tmp = tempfile.mkdtemp(prefix='emcBCD-', suffix='.d')
atexit.register(lambda: shutil.rmtree(self._tmp))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = Facing()
w.show()
sys.exit( app.exec() )

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,23 @@
This program creates a gcode file that can be loaded into linuxnc to run a rectangular facing operation.
Validate Inputs
- checks that there are no blank entries.
- checks that stepover is not larger than tool diameter
- checks that Size X and Size Y are at least 2x stepover value
- checks that the spindle RPM is not 0
- checks that the feedrate is not 0
- checks that the tool diameter is not 0
Create Program
- checks for valid input fields
- creates a gcode program according to the Raster setting
- if a red X remains in the display, the program will not be created
The machine should be X and Y zeroed at the lower left corner of the workpiece.
The program is designed to run the selected raster pattern at a Z value of 0 in machine units.
The safe travel Z level defaults to 20 mm for metric or 1 inch in imperial. These can be modified by modifying the source code.
The feedrate for Z travel defaults to 1/2 the feedrate entered for X and Y.
**NB** It is up to the user to ensure that all entered parameters are compatible with the machine settings that the program will run on.

View File

@@ -0,0 +1,400 @@
#!/usr/bin/env python3
import sys
import os
import math
import tempfile
import atexit
import shutil
from qtpy import QtGui, QtWidgets, uic
from qtpy.QtCore import QPoint, QPointF, QLine, QRect, QFile, Qt, QEvent, QRegularExpression
from qtpy.QtWidgets import QFileDialog, QMessageBox
from qtpy.QtGui import QPainter, QBrush, QPen, QColor
from linuxcnc import OPERATOR_ERROR, NML_ERROR
from qtvcp.core import Info, Status, Action, Path
INFO = Info()
STATUS = Status()
ACTION = Action()
PATH = Path()
HERE = os.path.dirname(os.path.abspath(__file__))
IMAGES = os.path.join(PATH.IMAGEDIR, 'gcode_utility')
class Preview(QtWidgets.QWidget):
def __init__(self):
super(Preview, self).__init__()
self.num_holes = 0
self.first_angle = 0.0
def paintEvent(self, event):
painter = QPainter(self)
painter.setBrush(QColor(200, 200, 200, 255))
painter.drawRect(event.rect())
self.draw_main_circle(event, painter)
self.draw_crosshair(event, painter)
self.draw_holes(event, painter)
painter.end()
def draw_main_circle(self, event, qp):
size = self.size()
w = size.width()/2
h = size.height()/2
center = QPointF(w, h)
radius = min(w, h) - 35
qp.setPen(QPen(Qt.black, 1))
qp.drawEllipse(center, radius, radius)
def draw_crosshair(self, event, qp):
size = self.size()
cx = int(size.width()/2)
cy = int(size.height()/2)
L = min(cx, cy) - 25
qp.setPen(QPen(Qt.black, 1))
p1 = QPoint(cx + L, cy)
p2 = QPoint(cx, cy - L)
p3 = QPoint(cx - L, cy)
p4 = QPoint(cx, cy + L)
qp.drawLine(p1, p3)
qp.drawLine(p2, p4)
br1 = QRect(cx + L, cy-6, 30, 12)
br2 = QRect(cx-15, cy - L - 12, 30, 12)
br3 = QRect(cx - L - 30, cy-6, 30, 12)
br4 = QRect(cx-15, cy + L, 30, 12)
qp.drawText(br1, Qt.AlignHCenter|Qt.AlignVCenter, "0")
qp.drawText(br2, Qt.AlignHCenter|Qt.AlignVCenter, "90")
qp.drawText(br3, Qt.AlignHCenter|Qt.AlignVCenter, "180")
qp.drawText(br4, Qt.AlignHCenter|Qt.AlignVCenter, "270")
def draw_holes(self, event, qp):
size = self.size()
w = size.width()
h = size.height()
center = QPointF(w/2, h/2)
r = (min(w, h) - 70)/2
qp.setPen(QPen(Qt.red, 2))
for i in range(self.num_holes):
if i ==1:
qp.setPen(QPen(Qt.black, 2))
theta = ((360.0/self.num_holes) * i) + self.first_angle
x = r * math.cos(math.radians(theta))
y = r * math.sin(math.radians(theta))
x = round(x, 3)
y = -round(y, 3) # need this to make it go CCW
p = QPointF(x, y) + center
qp.drawEllipse(p, 6, 6)
def set_num_holes(self, num):
self.num_holes = num
def set_first_angle(self, angle):
self.first_angle = angle
class Hole_Circle(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Hole_Circle, self).__init__(parent)
# Load the widgets UI file:
self.filename = os.path.join(HERE, 'hole_circle.ui')
try:
self.instance = uic.loadUi(self.filename, self)
except AttributeError as e:
print("Error: ", e)
self.preview = Preview()
self.layout_preview.addWidget(self.preview)
# set up Help messagebox
help_file = open(os.path.join(HERE,"hole_circle_help.txt"), "r")
help_text = help_file.read()
self.mb = QMessageBox()
self.mb.setIcon(QMessageBox.Information)
self.mb.setWindowTitle("Hole Circle Help")
self.mb.setText(help_text)
self.mb.setStandardButtons(QMessageBox.Ok)
# Initial values
self._tmp = None
self.unit_code = "G21"
self.rpm = 500
self.num_holes = 4
self.radius = 10.0
self.first = 0.0
self.safe_z = 1.0
self.start = .5
self.depth = 1.0
self.drill_feed = 1.0
self.units_text = ''
self.units_changed()
# set valid input formats for lineEdits
self.lineEdit_spindle.setText(str(self.rpm))
self.lineEdit_num_holes.setText(str(self.num_holes))
self.lineEdit_radius.setText(str(self.radius))
self.lineEdit_first.setText(str(self.first))
self.lineEdit_safe_z.setText(str(self.safe_z))
self.lineEdit_start_height.setText(str(self.start))
self.lineEdit_depth.setText(str(self.depth))
self.lineEdit_drill_feed.setText(str(self.drill_feed))
self.lineEdit_comment.setText('Hole Circle Program')
self.checked = QtGui.QPixmap(os.path.join(IMAGES, 'checked.png'))
self.unchecked = QtGui.QPixmap(os.path.join(IMAGES,'unchecked.png'))
self.valid = True
self.units_changed()
self.validate()
# signal connections
self.btn_validate.clicked.connect(self.validate)
self.btn_create.clicked.connect(self.create_program)
self.btn_send.clicked.connect(self.send_program)
self.btn_mm.clicked.connect(self.units_changed)
self.btn_inch.clicked.connect(self.units_changed)
self.btn_help.clicked.connect(lambda obj: self.mb.show())
def units_changed(self):
if self.btn_inch.isChecked():
unit = "IMPERIAL"
self.unit_code = "G20"
else:
unit = "METRIC"
self.unit_code = "G21"
self.units_text = "**NOTE - All units are in {}".format(unit)
self.set_validator()
def set_validator(self):
# set valid input formats for lineEdits
if self.btn_inch.isChecked():
valid_size = QtGui.QRegularExpressionValidator(QRegularExpression(r'^((\d+(\.\d{,4})?)|(\.\d{,4}))$'))
valid_radius = QtGui.QRegularExpressionValidator(QRegularExpression(r'^((\d{1,3}(\.\d{1,4})?)|(\.\d{1,4}))$'))
valid_feed = QtGui.QRegularExpressionValidator(QRegularExpression('[0-9]{0,6}[.][0-9]{0,3}'))
else:
valid_size = QtGui.QRegularExpressionValidator(QRegularExpression(r'^((\d+(\.\d{,3})?)|(\.\d{,3}))$'))
valid_radius = QtGui.QRegularExpressionValidator(QRegularExpression(r'^((\d{1,4}(\.\d{1,3})?)|(\.\d{1,3}))$'))
valid_feed = QtGui.QRegularExpressionValidator(QRegularExpression(r'\d{0,5}[.]\d{0,1}'))
self.lineEdit_spindle.setValidator(QtGui.QRegularExpressionValidator(QRegularExpression(r'\d{0,5}')))
self.lineEdit_num_holes.setValidator(QtGui.QDoubleValidator(0, 99, 0))
self.lineEdit_radius.setValidator(valid_radius)
self.lineEdit_first.setValidator(QtGui.QRegularExpressionValidator(QRegularExpression(r'\d{0,3}[.]\d{0,2}')))
self.lineEdit_safe_z.setValidator(valid_size)
self.lineEdit_start_height.setValidator(valid_size)
self.lineEdit_depth.setValidator(valid_size)
self.lineEdit_drill_feed.setValidator(valid_feed)
def clear_all(self):
self.lbl_spindle_ok.setPixmap(self.unchecked)
self.lbl_num_holes_ok.setPixmap(self.unchecked)
self.lbl_radius_ok.setPixmap(self.unchecked)
self.lbl_first_ok.setPixmap(self.unchecked)
self.lbl_safe_z_ok.setPixmap(self.unchecked)
self.lbl_start_height_ok.setPixmap(self.unchecked)
self.lbl_depth_ok.setPixmap(self.unchecked)
self.lbl_drill_feed_ok.setPixmap(self.unchecked)
def validate(self):
self.valid = True
self.clear_all()
try:
self.rpm = int(self.lineEdit_spindle.text())
if self.rpm > 0:
self.lbl_spindle_ok.setPixmap(self.checked)
else:
self.valid = False
except:
self.valid = False
try:
self.num_holes = int(self.lineEdit_num_holes.text())
if self.num_holes > 0:
self.lbl_num_holes_ok.setPixmap(self.checked)
else:
self.valid = False
except:
self.valid = False
try:
self.radius = float(self.lineEdit_radius.text())
if self.radius > 0.0:
self.lbl_radius_ok.setPixmap(self.checked)
else:
self.valid = False
except:
self.valid = False
try:
angle = (180/self.num_holes)
chord_length = (2 * self.radius) * math.sin(math.radians(angle))
self.label_chord_length.setText('{:.3f}'.format(chord_length))
except Exception as e:
print(e)
self.label_chord_length.setText('')
try:
self.first = float(self.lineEdit_first.text())
if self.first < 360.0:
self.lbl_first_ok.setPixmap(self.checked)
else:
self.valid = False
except:
self.valid = False
try:
self.safe_z = float(self.lineEdit_safe_z.text())
if self.safe_z > 0.0:
self.lbl_safe_z_ok.setPixmap(self.checked)
else:
self.valid = False
except:
self.valid = False
try:
self.start = float(self.lineEdit_start_height.text())
if self.start > 0.0:
self.lbl_start_height_ok.setPixmap(self.checked)
else:
self.valid = False
except:
self.valid = False
try:
self.depth = float(self.lineEdit_depth.text())
if self.depth > 0.0:
self.lbl_depth_ok.setPixmap(self.checked)
else:
self.valid = False
except:
self.valid = False
try:
self.drill_feed = float(self.lineEdit_drill_feed.text())
if self.drill_feed > 0.0:
self.lbl_drill_feed_ok.setPixmap(self.checked)
else:
self.valid = False
except:
self.valid = False
if self.valid is True:
self.preview.set_num_holes(self.num_holes)
self.preview.set_first_angle(self.first)
self.update()
def create_program(self):
self.validate()
if self.valid is False:
print("There are errors in input fields")
STATUS.emit('error', OPERATOR_ERROR, "Hole Circle: There are errors in input fields")
return
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getSaveFileName(self,"Save to file","","All Files (*);;ngc Files (*.ngc)", options=options)
if fileName:
self.calculate_toolpath(fileName)
else:
print("Program creation aborted")
def send_program(self):
self.validate()
if self.valid is False:
print("There are errors in input fields")
STATUS.emit('error', OPERATOR_ERROR, "Hole Circle: There are errors in input fields")
return
self._mktemp()
if self._tmp:
mp = os.path.join(self._tmp, os.path.basename('bhc.ngc'))
self.calculate_toolpath(mp)
ACTION.OPEN_PROGRAM(mp)
else:
print("send creation aborted")
def calculate_toolpath(self, fname):
comment = self.lineEdit_comment.text()
self.line_num = 5
self.file = open(fname, 'w')
# opening preamble
self.file.write("%\n")
self.file.write("({})\n".format(comment))
self.file.write("({} Holes on {} Diameter)\n".format(self.num_holes,self.radius *2))
self.file.write("({})\n".format(self.units_text))
self.file.write("({})\n".format('XY origin at circle center'))
self.file.write("({})\n".format('Z origin at top face of surface'))
self.file.write("\n")
self.next_line("{} G40 G49 G64 P0.03".format(self.unit_code))
self.next_line("G17")
self.next_line("G0 Z{}".format(self.safe_z))
self.next_line("G0 X0.0 Y0.0")
self.next_line("S{} M3".format(self.rpm))
# main section
for i in range(self.num_holes):
next_angle = ((360.0/self.num_holes) * i) + self.first
next_angle = round(next_angle, 3)
self.next_line("G0 @{} ^{}".format(self.radius, next_angle))
self.next_line("Z{}".format(self.start))
self.next_line("G1 Z-{} F{}".format(self.depth, self.drill_feed))
self.next_line("G0 Z{}".format(self.safe_z))
# closing section
self.next_line("G0 x0.0 Y0.0")
self.next_line("M2")
self.file.write("%\n")
self.file.close()
def output_program(self, dummy):
def next_line(text):
sys.stdout.write(text + "\n")
self.validate()
if self.valid is False:
print("There are errors in input fields")
return
comment = self.lineEdit_comment.text()
# opening preamble
sys.stdout.write("%\n")
sys.stdout.write("({})\n".format(comment))
next_line("{} G40 G49 G64 P0.03".format(self.unit_code))
next_line("G17")
next_line("G0 Z{}".format(self.safe_z))
next_line("G0 X0.0 Y0.0")
next_line("S{} M3".format(self.rpm))
# main section
for i in range(self.num_holes):
next_angle = ((360.0/self.num_holes) * i) + self.first
next_angle = round(next_angle, 3)
next_line("G0 @{} ^{}".format(self.radius, next_angle))
next_line("Z{}".format(self.start))
next_line("G1 Z-{} F{}".format(self.depth, self.drill_feed))
next_line("G0 Z{}".format(self.safe_z))
# closing section
next_line("G0 x0.0 Y0.0")
next_line("M2")
sys.stdout.write("%\n")
sys.exit(0)
def _mktemp(self):
if self._tmp:
return
self._tmp = tempfile.mkdtemp(prefix='emcBCD-', suffix='.d')
atexit.register(lambda: shutil.rmtree(self._tmp))
def btn_help_clicked(self, state):
self.mb.show()
def next_line(self, text):
self.file.write("N{} ".format(self.line_num) + text + "\n")
self.line_num += 5
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
Hole_Circle.create_program = Hole_Circle.output_program
w = Hole_Circle()
w.show()
sys.exit( app.exec() )

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,23 @@
This program creates a gcode file that can be loaded into linuxnc to run a hole circle operation.
Validate Inputs
- checks that there are no blank entries.
- checks that spindle speed is greater than 0
- checks that circle radius is greater than 0
- checks that first hole angle is less than 360
- checks that Z travel height is greater than 0
- checks that hole start height is greater than 0
- checks that drill feedrate is greater than 0
Create Program
- checks for valid input fields
- if MM button is checked, the gcode program will be run in G21 mode, otherwise G20 mode
- if a red X remains in the display, the program will not be created
- if a program is successfully created, it can be saved to a user selectable location
The COMMENT field is simply a text line that will be inserted as a comment at the top of the gcode file.
The machine should be X and Y zeroed at the center of the desired hole circle.
The Z zero should be set to the top of the workpiece.
The diagram on the right side shows a preview of the hole positions to be drilled.
**NB** It is up to the user to ensure that all entered parameters are compatible with the machine settings that the program will run on.

View File

@@ -0,0 +1,385 @@
#!/usr/bin/env python3
# Copyright (c) 2023 Jim Sloot (persei802@gmail.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.
import sys
import os
import tempfile
import atexit
from qtpy import QtCore, QtGui, QtWidgets, uic
from qtpy.QtWidgets import QFileDialog, QMessageBox
from qtvcp.core import Info, Status, Action, Tool, Path
INFO = Info()
STATUS = Status()
ACTION = Action()
TOOL = Tool()
PATH = Path()
HERE = os.path.dirname(os.path.abspath(__file__))
HELP = os.path.join(HERE, "help_files")
class Hole_Enlarge(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Hole_Enlarge, self).__init__(parent)
self.tool_db = parent
self.units_text = ""
self.units_gcode = 'G21'
self.angle_inc = 4
self.line_num = 0
self.tool = 0
self.tool_dia = 0.0
self.spindle = 0
self.start_dia = 0.0
self.final_dia = 0.0
self.loops = 0
self.cut_depth = 0.0
self.z_safe = 0.0
self.feed = 0
self.minimum_speed = INFO.MIN_SPINDLE_SPEED
self.maximum_speed = INFO.MAX_SPINDLE_SPEED
self.parm_list = ["tool", "tool_dia", "spindle", "start_dia", "final_dia", "loops", "cut_depth", "z_safe", "feed"]
# Load the widgets UI file:
self.filename = os.path.join(HERE, 'hole_enlarge.ui')
try:
self.instance = uic.loadUi(self.filename, self)
except AttributeError as e:
print("Error: ", e)
self.lineEdit_tool.setValidator(QtGui.QRegularExpressionValidator(QtCore.QRegularExpression('[0-9]{0,5}')))
self.lineEdit_spindle.setValidator(QtGui.QRegularExpressionValidator(QtCore.QRegularExpression('[0-9]{0,5}')))
self.lineEdit_feed.setValidator(QtGui.QRegularExpressionValidator(QtCore.QRegularExpression('[0-9]{0,4}')))
self.lineEdit_tool_dia.setValidator(QtGui.QRegularExpressionValidator(QtCore.QRegularExpression('[0-9]{0,3}[.][0-9]{0,4}')))
self.lineEdit_start_dia.setValidator(QtGui.QRegularExpressionValidator(QtCore.QRegularExpression('[0-9]{0,5}[.][0-9]{0,4}')))
self.lineEdit_final_dia.setValidator(QtGui.QRegularExpressionValidator(QtCore.QRegularExpression('[0-9]{0,5}[.][0-9]{0,4}')))
self.lineEdit_loops.setValidator(QtGui.QRegularExpressionValidator(QtCore.QRegularExpression('[0-9]{0,2}')))
self.lineEdit_cut_depth.setValidator(QtGui.QRegularExpressionValidator(QtCore.QRegularExpression('[0-9]{0,4}[.][0-9]{0,4}')))
self.lineEdit_z_safe.setValidator(QtGui.QRegularExpressionValidator(QtCore.QRegularExpression('[0-9]{0,4}')))
self.red_border = "border: 2px solid red;"
self.black_border = "border: 2px solid black;"
if not self.validate():
self.lineEdit_status.setText("Enter valid data into input parameters")
# set up Help messagebox
help_path = os.path.join(HERE, "hole_enlarge_help.html")
with open(help_path) as file:
help_text = file.read()
self.mb = QMessageBox()
self.mb.setIcon(QMessageBox.Information)
self.mb.setWindowTitle("Hole Enlarge Help")
self.mb.setTextFormat(QtCore.Qt.RichText)
self.mb.setText(help_text)
self.mb.setStandardButtons(QMessageBox.Ok)
# signal connections
STATUS.connect('metric-mode-changed', lambda w, mode: self.units_changed(mode))
self.lineEdit_tool.editingFinished.connect(self.load_tool)
self.chk_direction.stateChanged.connect(lambda state: self.direction_changed(state))
self.chk_mist.stateChanged.connect(lambda state: self.mist_changed(state))
self.chk_flood.stateChanged.connect(lambda state: self.flood_changed(state))
self.btn_preview.pressed.connect(self.preview_program)
self.btn_create.pressed.connect(self.create_program)
self.btn_send.pressed.connect(self.send_program)
self.btn_help.pressed.connect(lambda : self.mb.show())
def create_program(self):
if not self.validate(): return
self.estimate_runtime()
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
sub_path = INFO.SUB_PATH_LIST
_dir = os.path.expanduser(sub_path[0])
fileName, _ = QFileDialog.getSaveFileName(self,"Save to file",_dir,"All Files (*);;ngc Files (*.ngc)", options=options)
if fileName:
self.calculate_program(fileName)
self.lineEdit_status.setText(f"{fileName} successfully created")
else:
self.lineEdit_status.setText("Program creation aborted")
def send_program(self):
if not self.validate(): return
self.estimate_runtime()
filename = self.make_temp()[1]
self.calculate_program(filename)
ACTION.OPEN_PROGRAM(filename)
self.lineEdit_status.setText("Hole enlarge program sent to Linuxcnc")
def preview_program(self):
if not self.validate(): return
self.estimate_runtime()
filename = self.make_temp()[1]
self.calculate_program(filename)
self.graphic_preview.set_view_signal('clear', None)
self.graphic_preview.load_program(self, filename)
def validate(self):
valid = True
for item in self.parm_list:
self['lineEdit_' + item].setStyleSheet(self.black_border)
try:
self.tool = int(self.lineEdit_tool.text())
if self.tool <= 0:
self.lineEdit_tool.setStyleSheet(self.red_border)
self.lineEdit_status.setText("Error - Tool Number must be > 0")
valid = False
except:
self.lineEdit_tool.setStyleSheet(self.red_border)
valid = False
try:
self.tool_dia = float(self.lineEdit_tool_dia.text())
if self.tool_dia <= 0.0:
self.lineEdit_tool_dia.setStyleSheet(self.red_border)
self.lineEdit_status.setText("Error - Tool diameter must be > 0.0")
valid = False
except:
self.lineEdit_tool_dia.setStyleSheet(self.red_border)
valid = False
try:
self.spindle = int(self.lineEdit_spindle.text())
if self.spindle < self.minimum_speed:
self.lineEdit_status.setText("Warning - Spindle RPM adjusted to minimum spindle speed")
self.lineEdit_spindle.setText(str(self.minimum_speed))
self.spindle = self.minimum_speed
elif self.spindle > self.maximum_speed:
self.lineEdit_status.setText("Warning - Spindle RPM adjusted to maximum spindle speed")
self.lineEdit_spindle.setText(str(self.maximum_speed))
self.spindle = self.maximum_speed
except:
self.lineEdit_spindle.setStyleSheet(self.red_border)
valid = False
try:
self.start_dia = float(self.lineEdit_start_dia.text())
if self.start_dia <= 0.0:
self.lineEdit_start_dia.setStyleSheet(self.red_border)
self.lineEdit_status.setText("Warning - Start diameter must be > 0.0")
valid = False
if self.start_dia <= self.tool_dia:
self.lineEdit_start_dia.setStyleSheet(self.red_border)
self.lineEdit_status.setText("Warning - Start diameter must be > tool diameter")
valid = False
except:
self.lineEdit_start_dia.setStyleSheet(self.red_border)
valid = False
try:
self.final_dia = float(self.lineEdit_final_dia.text())
if self.final_dia <= self.start_dia:
self.lineEdit_final_dia.setStyleSheet(self.red_border)
self.lineEdit_status.setText("Warning - Final diameter must be > start diameter")
valid = False
except:
self.lineEdit_final_dia.setStyleSheet(self.red_border)
valid = False
try:
self.loops = int(self.lineEdit_loops.text())
if self.loops <= 0:
self.lineEdit_loops.setStyleSheet(self.red_border)
self.lineEdit_status.setText("Warning - Number of loops must be > 0")
valid = False
except:
self.lineEdit_loops.setStyleSheet(self.red_border)
valid = False
try:
self.cut_depth = float(self.lineEdit_cut_depth.text())
if self.cut_depth < 0.0:
self.lineEdit_cut_depth.setStyleSheet(self.red_border)
self.lineEdit_status.setText("Warning - Cut depth cannot be negative")
valid = False
elif self.cut_depth == 0.0:
self.lineEdit_status.setText("Warning - Cut depth set to 0.0")
except:
self.lineEdit_cut_depth.setStyleSheet(self.red_border)
valid = False
try:
self.z_safe = float(self.lineEdit_z_safe.text())
if self.z_safe <= 0.0:
self.lineEdit_z_safe.setStyleSheet(self.red_border)
self.lineEdit_status.setText("Warning - Z Safe distance must be > 0.0")
valid = False
except:
self.lineEdit_z_safe.setStyleSheet(self.red_border)
valid = False
try:
self.feed = int(self.lineEdit_feed.text())
if self.feed <= 0:
self.lineEdit_feed.setStyleSheet(self.red_border)
self.lineEdit_status.setText("Warning - Feed rate must be > 0")
valid = False
except:
self.lineEdit_feed.setStyleSheet(self.red_border)
valid = False
return valid
def create_gcode(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
fileName, _ = QFileDialog.getSaveFileName(self,"Save to file","","All Files (*);;ngc Files (*.ngc)", options=options)
if fileName:
self.calculate_program(fileName)
self.lineEdit_status.setText(f"{fileName} successfully created")
else:
print("Program creation aborted")
def estimate_runtime(self):
pi = 3.141592
travel = (self.loops + 1) * (pi * self.final_dia)
# make sure there's no divide by zero
try:
time = int((travel * 60) / self.feed)
hours, remainder = divmod(time, 3600)
minutes, seconds = divmod(remainder, 60)
self.lineEdit_runtime.setText(f"{hours:02d}:{minutes:02d}:{seconds:02d}")
except Exception as e:
self.lineEdit_runtime.setText("****")
print(f"Error : {e}")
def load_tool(self):
#check for valid tool and populate rpm, dia and feed parameters
try:
self.tool = int(self.lineEdit_tool.text())
except:
self.tool = 0
if self.tool > 0:
info = TOOL.GET_TOOL_INFO(self.tool)
dia = info[11]
if STATUS.is_metric_mode():
dia = INFO.convert_machine_to_metric(dia)
else:
dia = INFO.convert_machine_to_imperial(dia)
self.lineEdit_tool_dia.setText(f"{dia:8.3f}")
# TODO integrate tool database
try:
rpm = self.tool_db.get_rpm(self.tool)
except:
rpm = self.minimum_speed
self.lineEdit_spindle.setText(str(rpm))
# TODO integrate tool database
try:
feed = self.tool_db.get_feed(self.tool)
except:
if STATUS.is_metric_mode():
feed = 25
else:
feed = 1
self.lineEdit_feed.setText(str(feed))
self.lineEdit_tool.setStyleSheet(self.black_border)
self.validate()
def calculate_program(self, fname):
comment = self.lineEdit_comment.text()
self.line_num = 5
self.file = open(fname, 'w')
# opening preamble
self.file.write("%\n")
self.file.write(f"({comment})\n")
self.file.write(f"(Start diameter is {self.start_dia})\n")
self.file.write(f"(Final diameter is {self.final_dia})\n")
self.file.write(f"(Depth of cut is {self.cut_depth})\n")
self.file.write(f"({self.units_text})")
self.file.write("\n")
self.next_line(f"G40 G49 G64 P0.03 M6 T{self.tool}")
self.next_line("G17 G90")
self.next_line(f"{self.units_gcode}")
if self.chk_mist.isChecked():
self.next_line("M7")
if self.chk_flood.isChecked():
self.next_line("M8")
self.next_line(f"G0 Z{self.z_safe}")
self.next_line(f'G0 X0 Y0')
offset = (self.start_dia - self.tool_dia) / 2
self.next_line(f"G0 X{offset} Y0")
self.next_line(f"M3 S{self.spindle}")
self.next_line("G91")
self.next_line(f"G1 Z-{self.z_safe + self.cut_depth} F{self.feed / 2}")
self.next_line(f"F{self.feed}")
steps = int((360 * self.loops) / self.angle_inc)
inc = (self.final_dia - self.start_dia) / (2 * steps)
angle = self.angle_inc if self.chk_direction.isChecked() else -self.angle_inc
# create the spiral
self.file.write(f"(Create spiral with {self.loops} loops)\n")
self.next_line(f"o100 repeat [{steps}]")
self.next_line(f"g91 g1 @{inc:8.4f} ^{angle}")
self.next_line("o100 endrepeat")
# final profile pass
offset = (self.final_dia - self.tool_dia) / 2
direction = "G3" if self.chk_direction.isChecked() else "G2"
self.file.write("(Profile pass)\n")
self.next_line(f"{direction} I-{offset} F{self.feed}")
# closing postamble
self.next_line("G90")
self.next_line(f"G0 Z{self.z_safe}")
self.next_line(f'G0 X0 Y0')
self.next_line("M9")
self.next_line("M5")
self.next_line("M2")
self.file.write("%\n")
self.file.close()
def units_changed(self, mode):
text = "MM" if mode else "IN"
self.units_gcode = 'G21' if mode else 'G20'
self.lbl_feed_unit.setText(text + "/MIN")
self.lbl_tool_dia_unit.setText(text)
self.lbl_start_dia_unit.setText(text)
self.lbl_final_dia_unit.setText(text)
self.lbl_cut_depth_unit.setText(text)
self.lbl_z_safe_unit.setText(text)
self.units_text = (f"**NOTE - All units are in {text}")
self.load_tool()
def direction_changed(self, state):
text = "CCW" if state else "CW"
self.chk_direction.setText(text)
def mist_changed(self, state):
text = "ON" if state else "OFF"
self.chk_mist.setText("MIST " + text)
def flood_changed(self, state):
text = "ON" if state else "OFF"
self.chk_flood.setText("FLOOD " + text)
def next_line(self, text):
self.file.write(f"N{self.line_num} " + text + "\n")
self.line_num += 5
def make_temp(self):
_tmp = tempfile.mkstemp(prefix='spindle_warmup', suffix='.ngc')
atexit.register(lambda: os.remove(_tmp[1]))
return _tmp
# required code for subscriptable objects
def __getitem__(self, item):
return getattr(self, item)
def __setitem__(self, item, value):
return setattr(self, item, value)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = Hole_Enlarge()
w.show()
sys.exit( app.exec() )

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,52 @@
<!DOCTYPE html>
<html class="writer-html5" lang="en" >
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Hole Enlarge Help</title>
</head>
<body>
<h1>SPIRAL HOLE ENLARGEMENT</h1>
<p>This program creates a gcode file that can be loaded into linuxnc to run a spiral hole enlargement program.
It is for cases where a hole that has already been made needs to be slightly enlarged for whatever reason.
</p>
<p>The machine should be X and Y zeroed at the center of the hole to be enlarged. This can be done manually or by
using the probe utility.</p>
<p>Machining will begin at the current radius of the hole and will then proceed to spiral outward to the desired
final radius.</p>
<p>The parameter units are set to whatever mode the machine is currently in, either metric or imperial.</p>
<h2>Validation of Inputs</h2>
<ul>
<li>checks that the tool number is > 0</li>
<li>checks that the tool diameter is > 0</li>
<li>checks that the spindle RPM is within operating range and adjusts if necessary</li>
<li>checks that the start diameter > 0</li>
<li>checks that the final diameter > start diameter</li>
<li>checks that the number of spiral loops > 0</li>
<li>checks that the cut depth > 0</li>
<li>checks that the Z safe travel height > 0</li>
<li>checks that the feed rate > 0</li>
</ul>
<h2>PREVIEW PROGRAM</h2>
<ul>
<li>checks for valid input fields</li>
<li>creates a gcode program according to the parameter setting and the checkboxes</li>
<li>displays the calculated toolpath in the preview pane</li>
</ul>
<h2>SAVE AS PROGRAM</h2>
<ul>
<li>checks for valid input fields</li>
<li>creates a gcode program according to the parameter setting and the checkboxes</li>
<li>opens a dialog window to get a filename to save the program</li>
</ul>
<h2>SEND TO LINUXCNC</h2>
<ul>
<li>checks for valid input fields</li>
<li>creates a gcode program according to the parameter setting and the checkboxes</li>
<li>creates a temporary file and loads it to linuxcnc</li>
<li>the temporary file is automatically deleted when linuxcnc exits</li>
</ul>
<p>If the parameters contain invalid fields, that field is shown with a red border.</p>
</body>
</html>

36
lib/python/qtvcp/lib/gcodes.py Executable file
View File

@@ -0,0 +1,36 @@
#!/usr/bin/env python3
from . import mdi_text as mdiText
from qtvcp.qt_makegui import VCPWindow
WIDGETS = VCPWindow()
class GCodes:
def __init__(self, widgets=None):
self.w = WIDGETS
def setup_list(self):
self.w.gcode_list.currentRowChanged.connect(self.list_row_changed)
titles = mdiText.gcode_titles()
for key in sorted(titles.keys()):
self.w.gcode_list.addItem(key + ' ' + titles[key])
self.w.gcode_description.setReadOnly(True)
def list_row_changed(self, row):
line = self.w.gcode_list.currentItem().text()
print(line)
text = line.split(' ')[0]
desc = mdiText.gcode_descriptions(text) or 'No Match'
self.w.gcode_description.clear()
self.w.gcode_description.insertPlainText(desc)
if text != 'null':
words = mdiText.gcode_words()
if text in words:
parm = text + ' '
for index, value in enumerate(words[text], start=0):
parm += value
self.w.gcode_parameters.setText(parm)
else:
self.w.gcode_parameters.setText('')

View File

@@ -0,0 +1,294 @@
# Qtscreen is Copyright (c) 2017 Chris Morley
#
# QTscreen 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.
#
# Gscreen 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.
# This holds/converts the generic function keyword to the actual function call name
# it returns this name so Qtscreen can call the function to actually do something.
# you can add or change these
import traceback
from qtpy.QtCore import Qt
# Set up logging
from qtvcp import logger
LOG = logger.getLogger(__name__)
# Set the log level for this module
# log.setLevel(logger.INFO) # One of DEBUG, INFO, WARNING, ERROR, CRITICAL
def key_pressed(event):
""" Handle key presses (on any window) """
keynum = int(event.key())
keys = {
Qt.Key_Escape: "Key_Escape",
Qt.Key_Tab: "Key_Tab",
Qt.Key_Backtab: "Key_Backtab",
Qt.Key_Backspace: "Key_Backspace",
Qt.Key_Return: "Key_Return",
Qt.Key_Enter: "Key_Enter",
Qt.Key_Insert: "Key_Insert",
Qt.Key_Delete: "Key_Delete",
Qt.Key_Pause: "Key_Pause",
Qt.Key_Print: "Key_Print",
Qt.Key_SysReq: "Key_SysReq",
Qt.Key_Clear: "Key_Clear",
Qt.Key_Home: "Key_Home",
Qt.Key_End: "Key_End",
Qt.Key_Left: "Key_Left",
Qt.Key_Up: "Key_Up",
Qt.Key_Right: "Key_Right",
Qt.Key_Down: "Key_Down",
Qt.Key_PageUp: "Key_PageUp",
Qt.Key_PageDown: "Key_PageDown",
Qt.Key_Shift: "Key_Shift",
Qt.Key_Control: "Key_Control",
Qt.Key_Meta: "Key_Meta",
# Qt.Key_Alt: "Key_Alt",
Qt.Key_AltGr: "Key_AltGr",
Qt.Key_CapsLock: "Key_CapsLock",
Qt.Key_NumLock: "Key_NumLock",
Qt.Key_ScrollLock: "Key_ScrollLock",
Qt.Key_F1: "Key_F1",
Qt.Key_F2: "Key_F2",
Qt.Key_F3: "Key_F3",
Qt.Key_F4: "Key_F4",
Qt.Key_F5: "Key_F5",
Qt.Key_F6: "Key_F6",
Qt.Key_F7: "Key_F7",
Qt.Key_F8: "Key_F8",
Qt.Key_F9: "Key_F9",
Qt.Key_F10: "Key_F10",
Qt.Key_F11: "Key_F11",
Qt.Key_F12: "Key_F12",
Qt.Key_F13: "Key_F13",
Qt.Key_F14: "Key_F14",
Qt.Key_F15: "Key_F15",
Qt.Key_F16: "Key_F16",
Qt.Key_F17: "Key_F17",
Qt.Key_F18: "Key_F18",
Qt.Key_F19: "Key_F19",
Qt.Key_F20: "Key_F20",
Qt.Key_F21: "Key_F21",
Qt.Key_F22: "Key_F22",
Qt.Key_F23: "Key_F23",
Qt.Key_F24: "Key_F24",
Qt.Key_F25: "Key_F25",
Qt.Key_F26: "Key_F26",
Qt.Key_F27: "Key_F27",
Qt.Key_F28: "Key_F28",
Qt.Key_F29: "Key_F29",
Qt.Key_F30: "Key_F30",
Qt.Key_F31: "Key_F31",
Qt.Key_F32: "Key_F32",
Qt.Key_F33: "Key_F33",
Qt.Key_F34: "Key_F34",
Qt.Key_F35: "Key_F35",
Qt.Key_Super_L: "Key_Super_L",
Qt.Key_Super_R: "Key_Super_R",
Qt.Key_Menu: "Key_Menu",
Qt.Key_Hyper_L: "Key_HYPER_L",
Qt.Key_Hyper_R: "Key_Hyper_R",
Qt.Key_Help: "Key_Help",
Qt.Key_Direction_L: "Key_Direction_L",
Qt.Key_Direction_R: "Key_Direction_R",
Qt.Key_Space: "Key_Space",
Qt.Key_Any: "Key_Any",
Qt.Key_Exclam: "Key_Exclam",
Qt.Key_QuoteDbl: "Key_QuoteDdl",
Qt.Key_NumberSign: "Key_NumberSign",
Qt.Key_Dollar: "Key_Dollar",
Qt.Key_Percent: "Key_Percent",
Qt.Key_Ampersand: "Key_Ampersand",
Qt.Key_Apostrophe: "Key_Apostrophe",
Qt.Key_ParenLeft: "Key_ParenLeft",
Qt.Key_ParenRight: "Key_ParenRight",
Qt.Key_Asterisk: "Key_Asterisk",
Qt.Key_Plus: "Key_Plus",
Qt.Key_Comma: "Key_Comma",
Qt.Key_Minus: "Key_Minus",
Qt.Key_Period: "Key_Period",
Qt.Key_Slash: "Key_Slash",
Qt.Key_0: "Key_0",
Qt.Key_1: "Key_1",
Qt.Key_2: "Key_2",
Qt.Key_3: "Key_3",
Qt.Key_4: "Key_4",
Qt.Key_5: "Key_5",
Qt.Key_6: "Key_6",
Qt.Key_7: "Key_7",
Qt.Key_8: "Key_8",
Qt.Key_9: "Key_9",
Qt.Key_Colon: "Key_Colon",
Qt.Key_Semicolon: "Key_Semicolon",
Qt.Key_Less: "Key_Less",
Qt.Key_Equal: "Key_Equal",
Qt.Key_Greater: "Key_Greater",
Qt.Key_Question: "Key_Question",
Qt.Key_At: "Key_At",
Qt.Key_A: "Key_",
Qt.Key_B: "Key_",
Qt.Key_C: "Key_",
Qt.Key_D: "Key_",
Qt.Key_E: "Key_",
Qt.Key_F: "Key_",
Qt.Key_G: "Key_",
Qt.Key_H: "Key_",
Qt.Key_I: "Key_",
Qt.Key_J: "Key_",
Qt.Key_K: "Key_",
Qt.Key_L: "Key_",
Qt.Key_M: "Key_",
Qt.Key_N: "Key_",
Qt.Key_O: "Key_",
Qt.Key_P: "Key_",
Qt.Key_Q: "Key_",
Qt.Key_R: "Key_",
Qt.Key_S: "Key_",
Qt.Key_T: "Key_",
Qt.Key_U: "Key_",
Qt.Key_V: "Key_",
Qt.Key_W: "Key_",
Qt.Key_X: "Key_",
Qt.Key_Y: "Key_",
Qt.Key_Z: "Key_",
Qt.Key_BracketLeft: "Key_BracketLeft",
Qt.Key_Backslash: "Key_Backslash",
Qt.Key_BracketRight: "Key_BracketRight",
Qt.Key_AsciiCircum: "Key_AsciiCircum",
Qt.Key_Underscore: "Key_Underscore",
Qt.Key_QuoteLeft: "Key_QuoteLeft",
Qt.Key_BraceLeft: "Key_BraceLeft",
Qt.Key_Bar: "Key_Bar",
Qt.Key_BraceRight: "Key_BraceRight",
Qt.Key_AsciiTilde: "Key_AsciiTilde",
}
char = keys.get(keynum, '<unknown - {}>'.format(keynum))
mods = []
if event.modifiers() & Qt.AltModifier:
mods.append("Alt")
# For letters we want upper and lower in the keyname
# if control was used the keyname uses an upper letter
# we will also not add +shift to the keyname
if (keynum >= 65) and (keynum <= 90):
if event.modifiers() & Qt.ControlModifier:
char = char + chr(event.key())
else:
char = char + event.text()
txt = "+".join(mods) + (mods and "+" or "") + char
return txt
# list of keyname, function name, optional value
# value can be used when calling one function with multiple keys
class _Keycalls:
def __init__(self):
self.Key_F1 = ['on_keycall_ESTOP', None]
self.Key_F2 = ['on_keycall_POWER', None]
self.Key_Home = ['on_keycall_HOME', None]
self.Key_Escape = ['on_keycall_ABORT', None]
self.Key_Left = ['on_keycall_XNEG', None]
self.Key_Right = ['on_keycall_XPOS', None]
self.Key_Up = ['on_keycall_YPOS', None]
self.Key_Down = ['on_keycall_YNEG', None]
self.Key_PageUp = ['on_keycall_ZPOS', None]
self.Key_PageDown = ['on_keycall_ZNEG', None]
self.Key_BracketLeft = ['on_keycall_APOS', None]
self.Key_BracketRight = ['on_keycall_ANEG', None]
self.Key_BraceLeft = ['on_keycall_APOS', None]
self.Key_BraceRight = ['on_keycall_ANEG', None]
def __getitem__(self, item):
return getattr(self, item)
def __setitem__(self, item, value):
return setattr(self, item, value)
# These is the public methods for key conversion to function call name.
class Keylookup:
def __init__(self):
self.keycall = _Keycalls()
# This looks up the function named based from the keynumber and then calls
# the function in the handler file
def call(self, handler_instance, event, state, shift, cntrl):
try:
function_name, value = self.convert(event)
except TypeError:
raise NameError('No KeyCall binding defiimport tracebackned for %s' % key_pressed(event))
if value is None:
handler_instance[function_name](event, state, shift, cntrl)
else:
# has option value so function signature is different
handler_instance[function_name](event, state, shift, cntrl, value)
return True
# convert a Qt event to a function name
def convert(self, event):
try:
b = key_pressed(event)
f, v = self.keycall[b]
return f, v
except:
raise NameError("no function name conversion for QT Event: '{}'".format(b))
# get a function name from a keyname
def get_call(self, binding):
try:
a, v = self.keycall[binding]
return a, v
except:
raise NameError("No key function call")
# add a keyname and function name
def add_call(self, binding, function, value=None):
try:
self.keycall[binding] = [function, value]
except:
raise NameError("Binding %s could not be added" % binding)
# remove a keyname binding
def del_call(self, binding):
try:
delattr(self.keycall, binding)
except AttributeError:
raise NameError("Binding %s could not be found" % binding)
except Exception as e:
raise NameError("Binding %s could not be removed: %s" % (binding, e))
def manage_function_calls(self, handler, event, is_pressed, key, shift, cntrl):
try:
b = self.call(handler, event, is_pressed, shift, cntrl)
except NameError as e:
if is_pressed:
LOG.debug('Exception in KEYBINDING: {}'.format(e))
if LOG.getEffectiveLevel() == LOG.VERBOSE:
formatted_lines = traceback.format_exc().splitlines()
for i in range(5, len(formatted_lines)):
print(formatted_lines[i])
except Exception as e:
if is_pressed:
formatted_lines = traceback.format_exc().splitlines()
# LOG.debug('Exception in KEYBINDING:', exc_info=e)
print("""Key Binding Error for key '%s' calling function: %s in handler file:""" % (
key, self.convert(event)))
if LOG.getEffectiveLevel() == LOG.VERBOSE:
for i in range(5, len(formatted_lines)):
print(formatted_lines[i])
event.accept()
return True

View File

@@ -0,0 +1,126 @@
from qtvcp.core import Status, Info
import os
import time
# Set up logging
from qtvcp import logger
log = logger.getLogger(__name__)
# Set the log level for this module
# log.setLevel(logger.INFO) # One of DEBUG, INFO, WARNING, ERROR, CRITICAL
STATUS = Status()
INFO = Info()
class MachineLogger():
def __init__(self):
STATUS.connect('update-machine-log', self.log_it)
self.mlp = os.path.expanduser(INFO.MACHINE_LOG_HISTORY_PATH)
self.initialFormat = "%a, %b %d %Y %X ---"
self.timeFormat = "%H:%M:%S "
self.dateFormat = "%a, %b %d %Y %X: "
self.logOn = True
def log_it(self, w, message='', option=None):
if option is None: option = ''
if option == 'DELETE':
self.delete_log()
return
if option == 'ON':
self.logOn = True
return
if option == 'OFF':
self.logOn = False
return
if self.logOn != True:
return
try:
message = message.rstrip('\n')
if 'TIME' in option:
self.log_message_time(message)
elif 'DATE' in option:
self.log_message_date(message)
elif 'INITIAL' in option:
self.initial_greeting()
else:
self.log_message(message)
except Exception as e:
log.exception('log_it function: {}'.format(e))
def initial_greeting(self):
try:
timestamp = time.strftime(self.initialFormat)
fp = open(self.mlp, 'a')
# fp.write(""" $$$$$$\ $$$$$$$$\ """)
# fp.write('\n')
# fp.write('''$$ __$$\ \__$$ __|''')
# fp.write('\n')
# fp.write('$$ / $$ | $$ | $$$$$$$\ $$$$$$$\ $$$$$$\ $$$$$$\ $$$$$$\ $$$$$$$\ ')
# fp.write('\n')
# fp.write('$$ | $$ | $$ | $$ _____|$$ _____|$$ __$$\ $$ __$$\ $$ __$$\ $$ __$$\ ')
# fp.write('\n')
# fp.write('$$ | $$ | $$ | \$$$$$$\ $$ / $$ | \__|$$$$$$$$ |$$$$$$$$ |$$ | $$ |')
# fp.write('\n')
# fp.write('$$ $$\$$ | $$ | \____$$\ $$ | $$ | $$ ____|$$ ____|$$ | $$ |')
# fp.write('\n')
# fp.write('\$$$$$$ / $$ | $$$$$$$ |\$$$$$$$\ $$ | \$$$$$$$\ \$$$$$$$\ $$ | $$ |')
# fp.write('\n')
# fp.write(' \___$$$\ \__| \_______/ \_______|\__| \_______| \_______|\__| \__|')
# fp.write('\n')
# fp.write(' \___| ')
fp.write('--- QtVCP Screen Started on: ' + timestamp + "\n")
fp.close()
except:
log.warning('machine log history: path valid?')
def log_message_time(self, message):
try:
timestamp = time.strftime(self.timeFormat)
fp = open(self.mlp, 'a')
for num,i in enumerate(message.split('\\n')):
if num == 0:
fp.write(timestamp + i + "\n")
else:
fp.write(i + "\n")
fp.close()
except:
log.warning('machine log history: path valid?: {}'.format(fp))
STATUS.emit('machine-log-changed')
def log_message_date(self, message):
try:
timestamp = time.strftime(self.dateFormat)
fp = open(self.mlp, 'a')
for num,i in enumerate(message.split('\\n')):
if num == 0:
fp.write(timestamp + i + "\n")
else:
fp.write(i + "\n")
fp.close()
except:
log.warning('machine log history: path valid?')
STATUS.emit('machine-log-changed')
def log_message(self, message):
try:
fp = open(self.mlp, 'a')
for i in message.split('\\n'):
fp.write(i + "\n")
fp.close()
except:
log.warning('machine log history: path valid?')
STATUS.emit('machine-log-changed')
def delete_log(self):
fp = open(self.mlp, 'w')
fp.write('')
fp.close()
STATUS.emit('machine-log-changed')

View File

@@ -0,0 +1,141 @@
#!/usr/bin/env python3
# Qtvcp MDI subprogram
#
# Copyright (c) 2018 Chris Morley <chrisinnanaimo@hotmail.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.
# This subprogram is used ACTION
import sys
import os
import hal
import json
from qtpy import QtGui, QtCore, QtWidgets, uic
from qtpy.QtCore import QObject
from qtpy.QtCore import QProcess, QEvent, Qt, Property
from qtvcp.core import Status, Action, Path
from qtvcp import logger
# Instantiate the libraries with global reference
# STATUS gives us status messages from linuxcnc
# LOG is for running code logging
STATUS = Status()
ACTION = Action()
PATH = Path()
LOG = logger.getLogger(__name__)
# Force the log level for this module
#LOG.setLevel(logger.DEBUG) # One of DEBUG, INFO, WARNING, ERROR, CRITICAL
current_dir = os.path.dirname(__file__)
SUBPROGRAM = os.path.abspath(os.path.join(current_dir, 'mdi_subprogram.py'))
class MDICommand(QObject):
def __init__(self):
super(MDICommand, self).__init__()
self.proc = None
#############################################
# process control
#############################################
def start_process(self):
self.proc = QProcess()
self.proc.setReadChannel(QProcess.StandardOutput)
self.proc.started.connect(self.process_started)
self.proc.readyReadStandardOutput.connect(self.read_stdout)
self.proc.readyReadStandardError.connect(self.read_stderror)
self.proc.finished.connect(self.process_finished)
self.proc.start('python3 {}'.format(SUBPROGRAM))
def run(self, function='mdi_command', cmdList={'LABEL':'General','COMMANDS':'g0x2'}):
if self.proc is not None:
LOG.info("MDI Routine processor is busy")
return
self.start_process()
string_to_send = function + '$' + json.dumps(cmdList) + '\n'
#print("String to send ", string_to_send)
STATUS.block_error_polling()
self.proc.writeData(bytes(string_to_send, 'utf-8'))
def process_started(self):
LOG.info("MDI command started with PID {}\n".format(self.proc.processId()))
def read_stdout(self):
qba = self.proc.readAllStandardOutput()
line = qba.data()
self.parse_input(line)
def read_stderror(self):
qba = self.proc.readAllStandardError()
line = qba.data()
self.parse_input(line)
def process_finished(self, exitCode, exitStatus):
LOG.info(("MDI Process finished - exitCode {} exitStatus {}".format(exitCode, exitStatus)))
self.proc = None
STATUS.unblock_error_polling()
def parse_input(self, line):
line = line.decode("utf-8")
if "ERROR INFO" in line:
ACTION.SET_ERROR_MESSAGE(line)
elif "ERROR" in line:
#print(line)
STATUS.unblock_error_polling()
ACTION.SET_ERROR_MESSAGE('MDI sub process finished in error')
elif "INFO" in line:
pass
elif "COMPLETE" in line:
STATUS.unblock_error_polling()
LOG.info("MDI routine completed without errors")
if LOG.getEffectiveLevel() < logger.INFO:
return_data = line.rstrip().split('$')
data = json.loads(return_data[1])
print('MDI Complete:',data)
elif "HISTORY" in line:
return_data = line.rstrip().split('$')
STATUS.emit('update-machine-log', return_data[1], 'TIME')
elif "DEBUG" in line:
pass
else:
LOG.error("Error parsing return data from sub_processor. Line={}".format(line))
########################################
# required boiler code
########################################
def __getitem__(self, item):
return getattr(self, item)
def __setitem__(self, item, value):
return setattr(self, item, value)
####################################
# Testing
####################################
if __name__ == "__main__":
from qtpy.QtWidgets import *
from qtpy.QtCore import *
from qtpy.QtGui import *
app = QtWidgets.QApplication(sys.argv)
mdi = MDICommand()
w = QWidget()
w.setGeometry(100, 100, 100, 100)
w.setWindowTitle('MDI Command')
layout = QtWidgets.QVBoxLayout()
button = QtWidgets.QPushButton()
button.clicked.connect(lambda : mdi.run())
layout.addWidget(button)
w.setLayout(layout)
w.show()
sys.exit( app.exec() )

View File

@@ -0,0 +1,153 @@
#!/usr/bin/env python3
# Qtvcp MDI subprogram
#
# Copyright (c) 2018 Chris Morley <chrisinnanaimo@hotmail.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.
# This subprogram is used ACTION
import sys
import time
import json
import linuxcnc
from qtpy.QtCore import QObject
from qtvcp.core import Status, Action, Info
# Instantiate the libraries with global reference
# STATUS gives us status messages from linuxcnc
STATUS = Status()
ACTION = Action()
INFO = Info()
class MDISubprog(QObject):
def __init__(self):
QObject.__init__(self)
self.send_dict = {'MESSAGE':'finished','CALLER':'Unknown'}
self.history_log = ""
self.process()
def process(self):
while 1:
try:
line = sys.stdin.readline()
except KeyboardInterrupt:
break
if line:
cmd = line
line = None
try:
error = self.process_command(cmd)
# block polling here 0 main program should start polling in their end
STATUS.block_error_polling()
# error = 1 means success,
# error = None means ignore,
# anything else is an error - a returned string is an error message
if error is not None:
if error != 1:
if type(error) == str:
sys.stdout.write("ERROR INFO MDI command: {}\n".format(error))
else:
sys.stdout.write("ERROR MDI routine returned with error\n")
else:
#self.collect_status()
sys.stdout.write("COMPLETE$" + json.dumps(self.send_dict) + "\n")
sys.stdout.flush()
sys.stdout.flush()
# print history
if self.history_log != "":
time.sleep(0.1)
sys.stdout.write("HISTORY$ {}\n".format(self.history_log))
self.history_log = ""
sys.stdout.flush()
except Exception as e:
sys.stdout.write("ERROR Command Error: {}\n".format(e))
sys.stdout.flush()
break
# check that the command is actually a method in our class else
# this message isn't for us - ignore it
def process_command(self, cmd):
cmd = cmd.rstrip().split('$')
if cmd[0] in dir(self):
if not STATUS.is_on_and_idle(): return None
pre = self.prechecks()
if pre is not None: return pre
parms = json.loads(cmd[1])
# start polling errors here - parent program should have blocked their polling
STATUS.unblock_error_polling()
error = self[cmd[0]](parms)
if (error != 1 or type(error)== str) and STATUS.is_on_and_idle():
pass
self.postreset()
return error
else:
return 'Command function {} not in mdi subprocess routines'.format(cmd[0])
# for possible future options
def prechecks(self):
# return 'ignore'
return None
# for possible future options
def postreset(self):
return None
# call each MDI command in this python process
def mdi_command(self, cmd):
label = cmd.get('LABEL')
self.send_dict['CALLER'] = label
cmdList = cmd.get('COMMANDS')
timeout = cmd.get('TIMEOUT', 10)
rtn = self.CALL_MDI_WAIT(cmdList,label,timeout)
self.history_log = '{} MDI Commands:\n {}'.format(label,cmdList)
return rtn
def CALL_MDI_WAIT(self, code, label, timeout = 10):
for l in code:
ACTION.CALL_MDI( l )
result = ACTION.cmd.wait_complete(timeout)
try:
# give a chance for the error message to get to stdin
time.sleep(.01)
error = STATUS.ERROR.poll()
if not error is None:
ACTION.ABORT()
return '{},\n {}\n Called from "{}"'.format(l,error[1],label)
except Exception as e:
ACTION.ABORT()
return '{}'.format(e)
if result == -1:
ACTION.ABORT()
return 'Command timed out: ({} second)'.format(timeout)
elif result == linuxcnc.RCS_ERROR:
ACTION.ABORT()
return 'MDI_COMMAND_WAIT RCS error'
return 1
########################################
# required boiler code
########################################
def __getitem__(self, item):
return getattr(self, item)
def __setitem__(self, item, value):
return setattr(self, item, value)
####################################
# Testing
####################################
if __name__ == "__main__":
w = MDISubprog()

View File

@@ -0,0 +1,990 @@
def gcode_titles():
titles = {'G0': 'Coordinated Motion at Rapid Rate',
'G1': 'Coordinated Motion at Feed Rate',
'G2': 'Coordinated CW Helical Motion at Feed Rate',
'G3': 'Coordinated CCW Helical Motion at Feed Rate',
'G4': 'Dwell',
'G5': 'Cubic Spline',
'G5.1': 'Quadratic B-Spline',
'G5.2': 'NURBS, add control point',
'G5.3': 'NURBS, close control point',
'G7': 'Diameter Mode (lathe)',
'G8': 'Radius Mode (lathe)',
'G10': 'Offsets L1, L2, L10, L11, L20',
'G10L1': 'Set Tool Table Entry',
'G10L2': 'Set Tool Table, Calculated, Workpiece',
'G10L10': 'Set Tool Table, Calculated, Fixture',
'G10L11': 'Coordinate System Origin Setting',
'G10L20': 'Coordinate System Origin Setting Calculated',
'G17': 'Plane Select XY',
'G18': 'Plane Select XZ',
'G19': 'Plane Select YZ',
'G17.1': 'Plane Select UV',
'G17.2': 'Plane Select WU',
'G17.3': 'Plane Select VW',
'G18.1': 'Plane Select WU',
'G20': 'Set Units to Inch',
'G21': 'Set Units to Millimeters',
'G28': 'Go to Predefined Position',
'G28.1': 'Set Predefined Position',
'G30': 'Go to Predefined Position',
'G30.1': 'Set Predefined Position',
'G33': 'Spindle Synchronized Motion',
'G33.1': 'Rigid Tapping',
'G38.2': 'Probing Toward Workpiece, Signal Error',
'G38.3': 'Probing Toward Workpiece',
'G38.4': 'Probing Away Workpiece, Signal Error',
'G38.5': 'Probing Away Workpiece',
'G40': 'Cancel Cutter Compensation',
'G41': 'Cutter Compensation, Left of Programmed Path',
'G41.1': 'Dynamic Cutter Compensation, Left of Path',
'G42': 'Cutter Compensation, Right of Programmed Path',
'G42.1': 'Dynamic Cutter Compensation, Right of Path',
'G43': 'Use Tool Length Offset from Tool Table',
'G43.1': 'Dynamic Tool Length Offset',
'G43.2': 'Apply additional Tool Length Offset',
'G49': 'Cancel Tool Length Offset',
'G52': 'Local Coordinate System Offset',
'G53': 'Move in Machine Coordinates',
'G54': 'Select Coordinate System 1',
'G55': 'Select Coordinate System 2',
'G56': 'Select Coordinate System 3',
'G57': 'Select Coordinate System 4',
'G58': 'Select Coordinate System 5',
'G59': 'Select Coordinate System 6',
'G59.1': 'Select Coordinate System 7',
'G59.2': 'Select Coordinate System 8',
'G59.3': 'Select Coordinate System 9',
'G61': 'Exact Path Mode',
'G61.1': 'Exact Stop Mode',
'G64': 'Path Control Mode with Tolerance',
'G73': 'Drilling Cycle with Chip Breaking',
'G74': 'Left-hand Tapping Cycle with Dwell',
'G76': 'Multi-pass Threading Cycle (Lathe)',
'G80': 'Cancel Motion Modes',
'G81': 'Drilling Cycle',
'G82': 'Drilling Cycle with Dwell',
'G83': 'Drilling Cycle with Peck',
'G84': 'Right-hand Tapping Cycle with Dwell',
'G85': 'Boring Cycle, No Dwell, Feed Out',
'G86': 'Boring Cycle, Stop, Rapid Out',
'G89': 'Boring Cycle, Dwell, Feed Out',
'G90': 'Absolute Distance Mode',
'G90.1': 'Absolute Distance Mode IJK Arc Offsets',
'G91': 'Incremental Distance Mode',
'G91.1': 'Incremental Distance Mode IJK Arc Offsets',
'G92': 'Coordinate System Offset',
'G92.1': 'Reset G92 Offsets, Reset Parameters',
'G92.2': 'Reset G92 Offsets, Keep Parameters ',
'G92.3': 'Restore G92 Offsets',
'G93': 'Feed Rate Inverse Time Mode',
'G94': 'Feed Rate Units per Minute Mode',
'G95': 'Feed Rate Units per Revolution Mode',
'G96': 'Spindle Control Constant Surface Speed Mode',
'G97': 'Spindle Control RPM Mode',
'G98': 'Canned Cycle Return Level',
'G99': 'Canned Cycle Return Level',
'M0': 'Program Pause',
'M1': 'Program Pause if Optional Stop is Enabled',
'M2, M30': 'Program End',
'M3': 'Spindle Start Clockwise',
'M4': 'Spindle Start Counterclockwise',
'M5': 'Spindle Stop',
'M6': 'Tool Change',
'M7': 'Mist Coolant On',
'M8': 'Flood Coolant On',
'M9': 'Flood and Mist Coolant Off',
'M19': 'Orient Spindle',
'M48': 'Enable Spindle Speed and Feed Rate Override',
'M49': 'Disable Spindle Speed and Feed Rate Override',
'M50': 'Feed Override Control',
'M51': 'Spindle Speed Override Control',
'M52': 'Adaptive Feed Control',
'M53': 'Feed Stop Control',
'M61': 'Set Current Tool',
'M62': 'Turn On Digital Output Synchronized with Motion',
'M63': 'Turn Off Digital Output Synchronized with Motion',
'M64': 'Turn On Digital Output Immediately',
'M65': 'Turn Off Digital Output Immediately',
'M66': 'Wait on Input',
'M67': 'Set an Analog Output Synchronized with Motion',
'M68': 'Set an Analog Output Immediately',
'M70': 'Save Modal State',
'M71': 'Invalidate Stored Modal State',
'M72': 'Restore Modal State',
'M73': 'Save and Autorestore Modal State',
'M98': 'Call Faunc Style Subroutine',
'M99': 'Return from Fanuc Style Subroutine', }
return titles
def gcode_words():
words = {'G0': ['X', 'Y', 'Z'],
'G1': ['X', 'Y', 'Z'],
'G2': ['X', 'Y', 'Z', 'I', 'J', 'K', 'R', 'P'],
'G3': ['X', 'Y', 'Z', 'I', 'J', 'K', 'R', 'P'],
'G4': ['P'],
'G5': ['I', 'J', 'P', 'Q'],
'G5.1': ['I', 'J'],
'G5.2': ['P', 'L'],
'G10': ['L'],
'G10L1': ['P', 'X', 'Y', 'Z', 'R', 'I', 'J', 'Q'],
'G10L2': ['P', 'X', 'Y', 'Z', 'R'],
'G10L10': ['P', 'X', 'Y', 'Z', 'R', 'I', 'J', 'Q'],
'G10L11': ['P', 'X', 'Y', 'Z', 'R', 'I', 'J', 'Q'],
'G10L20': ['P', 'X', 'Y', 'Z'],
'G33': ['X', 'Y', 'Z', 'K', '$'],
'G33.1': ['X', 'Y', 'Z', 'K', '$'],
'G38.2': ['X', 'Y', 'Z'],
'G38.3': ['X', 'Y', 'Z'],
'G38.4': ['X', 'Y', 'Z'],
'G38.5': ['X', 'Y', 'Z'],
'G41': ['D'],
'G41.1': ['D', 'L'],
'G42': ['D'],
'G42.1': ['D', 'L'],
'G43': ['H'],
'G43.1': ['X', 'Y', 'Z'],
'G43.2': ['H'],
'G52': ['X', 'Y', 'Z'],
'G53': ['X', 'Y', 'Z'],
'G64': ['P', 'Q'],
'G73': ['X', 'Y', 'Z', 'R', 'Q', 'L'],
'G74': ['X', 'Y', 'Z', 'R', 'L', 'P', '$'],
'G76': ['P', 'Z', 'I', 'J', 'K', 'Q', 'H', 'E', 'L', '$'],
'G81': ['X', 'Y', 'Z', 'R', 'L'],
'G82': ['X', 'Y', 'Z', 'R', 'L', 'P'],
'G83': ['X', 'Y', 'Z', 'R', 'L', 'Q'],
'G84': ['X', 'Y', 'Z', 'R', 'L', 'P', '$'],
'G85': ['X', 'Y', 'Z', 'R', 'L'],
'G86': ['X', 'Y', 'Z', 'R', 'L', 'P', '$'],
'G89': ['X', 'Y', 'Z', 'R', 'L', 'P'],
'G92': ['X', 'Y', 'Z'],
'G96': ['D', 'S', '$'],
'G97': ['S', '$'],
'M1': ['P', 'Q'],
'M3': ['S', '$'],
'M4': ['S', '$'],
'M19': ['R', 'Q', 'P', '$'],
'M50': ['P'],
'M51': ['P', '$'],
'M52': ['P'],
'M61': ['Q'],
'M62': ['P'],
'M63': ['P'],
'M64': ['P'],
'M65': ['P'],
'M66': ['P', 'E', 'L', 'Q'],
'M67': ['E', 'Q'],
'M68': ['E', 'Q'], }
return words
def gcode_descriptions(gcode):
gcodeTitle = {'G0': G0,
'G1': G1,
'G2': G2,
'G3': G3,
'G4': G4,
'G5': G5,
'G5.1': G5_1,
'G5.2': G5_2,
'G5.3': G5_3,
'G7': G7,
'G8': G8,
'G10L1': G10L1,
'G10L2': G10L2,
'G10L10': G10L10,
'G10L11': G10L11,
'G10L20': G10L20,
'G17': G17,
'G18': G18,
'G19': G19,
'G17.1': G17_1,
'G18.1': G18_1,
'G19.1': G19_1,
'G20': G20,
'G21': G21,
'G28': G28,
'G28.1': G28_1,
'G30': G30,
'G30.1': G30_1,
'G33': G33,
'G33.1': G33_1,
'G38.2': G38_2,
'G38.3': G38_3,
'G38.4': G38_4,
'G38.5': G38_5,
'G40': G40,
'G41': G41,
'G41.1': G41_1,
'G42': G42,
'G42.1': G42_1,
'G43': G43,
'G43.1': G43_1,
'G43.2': G43_2,
'G49': G49,
'G52': G52,
'G53': G53,
'G54': G54,
'G55': G55,
'G56': G56,
'G57': G57,
'G58': G58,
'G59': G59,
'G59.1': G59_1,
'G59.2': G59_2,
'G59.3': G59_3,
'G61': G61,
'G61.1': G61_1,
'G64': G64,
'G73': G73,
'G74': G74,
'G76': G76,
'G80': G80,
'G81': G81,
'G82': G82,
'G83': G83,
'G84': G84,
'G85': G85,
'G86': G86,
'G89': G89,
'G90': G90,
'G90.1': G90_1,
'G91': G91,
'G91.1': G91_1,
'G92': G92,
'G92.1': G92_1,
'G92.2': G92_2,
'G92.3': G92_3,
'G93': G93,
'G94': G94,
'G95': G95,
'G96': G96,
'G97': G97,
'G98': G98,
'G99': G99, }
if gcode in gcodeTitle:
return gcodeTitle[gcode]
else:
return ''
# Maximum Width is 58
G0 = """G0 axes
Coordinated motion at maximum speed
"""
G1 = """G1 axes
Coordinated motion at feed speed
"""
G2 = """G2 Coordinated CW Helical Motion at Feed Rate
Center Format G2 axes offsets <P>
XY plane (G17) Z = helix I = X offset J = Y offset
XZ plane (G18) Y = helix I = X offset K = Z offset
YZ plane (G19) X = helix J = Y offset K = Z offset
P = Number of Turns
Radius Format G2 axes R <P>
R = Radius from Current Position
"""
G3 = """G3 Coordinated CCW Helical Motion at Feed Rate
Center Format G3 axes offsets <P>
XY plane (G17) Z = helix I = X offset J = Y offset
XZ plane (G18) Y = helix I = X offset K = Z offset
YZ plane (G19) X = helix J = Y offset K = Z offset
P = Number of Turns
Radius Format G3 axes R <P>
R = Radius from Current Position
"""
G4 = """G4 P
Dwell program for P seconds, floating point.
"""
G5 = """G5 Cubic Spline
G5 X Y <I J> P Q
I = X incremental offset from start point to first
control point
J = Y incremental offset from start point to first
control point
P = X incremental offset from end point to second
control point
Q = Y incremental offset from end point to second
control point
G5 creates a cubic B-spline in the XY plane with
the X and Y axes only.
P and Q must both be specified for every G5
command.
"""
G5_1 = """G5.1 Quadratic Spline
G5.1 X Y I J
I = X incremental offset from start point to
control point
J = Y incremental offset from start point to
control point
G5.1 creates a quadratic B-spline in the XY plane
with the X and Y axis only. Not specifying I or J
gives zero offset for the unspecified axis, so one
or both must be given.
"""
G5_2 = """G5.2 is for opening the data block defining a NURBS
"""
G5_3 = """G5.3 is for closing the data block defining a NURBS
"""
G7 = """G7 Lathe Diameter Mode
"""
G8 = """G8 Lathe Radius Mode
"""
G10L1 = """G10 L1 Set Tool Table
G10 L1 P axes <R I J Q>
Set Tool Table
P = tool number
R = radius of tool
I = front angle (lathe)
J = back angle (lathe)
Q = orientation (lathe)
G10 L1 sets the tool table for the P tool number
to the values of the words.
"""
G10L2 = """G10 L2 Set Coordinate System
G10 L2 P <axes R>
P = coordinate system (0-9)
R = rotation about the Z axis
G10 L2 offsets the origin of the axes in the
coordinate system specified to the value of the
axis word.
"""
G10L10 = """G10 L10 Set Tool Table
G10 L10 P axes <R I J Q>
P =- tool number
R = radius of tool
I = front angle (lathe)
J = back angle (lathe)
Q = orientation (lathe)
G10 L10 changes the tool table entry for tool P so
that if the tool offset is reloaded, with the
machine in its current position and with the
current G5x and G52/G92 offsets active, the
current coordinates for the given axes will become
the given values.
"""
G10L11 = """G10 L11 Set Tool Table
G10 L11 P axes <R I J Q>
P = tool number
R = radius of tool
I = front angle (lathe)
J = back angle (lathe)
Q = orientation (lathe)
G10 L11 is just like G10 L10 except that instead
of setting the entry according to the current
offsets, it is set so that the current coordinates
would become the given value if the new tool
offset is reloaded and the machine is placed in
the G59.3 coordinate system without any G52/G92
offset active.
"""
G10L20 = """G10 L20 Set Coordinate System
G10 L20 P- axes
P - coordinate system (0-9)
G10 L20 is similar to G10 L2 except that instead
of setting the offset/entry to the given value, it
is set to a calculated value that makes the
current coordinates become the given value.
"""
G17 = """G17 Plane Select
G17 = XY Plane
"""
G18 = """G18 Plane Select
G18 = ZX Plane
"""
G19 = """G19 Plane Select
G19 = YZ Plane
"""
G17_1 = """G17.1 Plane Select
G17.1 = UV Plane
The UV plane does not support arcs.
"""
G18_1 = """G18.1 Plane Select
G18.1 = WU Plane
The WU plane does not support arcs.
"""
G19_1 = """G19.1 Plane Select
G19.1 = VW Plane
The VW plane does not support arcs.
"""
G20 = """G20 Inch Units
"""
G21 = """G21 Millimeter Units
"""
G28 = """G28 Go to Predefined Position
G28 uses the values stored in parameters 5161-5169
as the X Y Z A B C U V W final point to move to.
The parameter values are absolute machine
coordinates in the native machine units as
specified in the INI file. All axes defined in the
INI file will be moved when a G28 is issued. If no
positions are stored with G28.1 then all axes will
go to the machine origin.
G28 - makes a rapid move from the current position
to the absolute position of the values in
parameters 5161-5166.
G28 axes - makes a rapid move to the position
specified by axes including any offsets, then will
make a rapid move to the absolute position of the
values in parameters 5161-5166 for all axes
specified. Any axis not specified will not move.
"""
G28_1 = """G28.1 Set Predefined Position
G28.1 - stores the current absolute position into
parameters 5161-5166.
"""
G30 = """G30 Go to Predefined Position
G30 uses the values stored in parameters 5181-5189
as the X Y Z A B C U V W final point to move to.
The parameter values are absolute machine
coordinates in the native machine units as
specified in the INI file. All axes defined in the
INI file will be moved when a G28 is issued. If no
positions are stored with G28.1 then all axes will
go to the machine origin.
G30 parameters will be used to move the tool when
a M6 is programmed if TOOL_CHANGE_AT_G30=1 is in
the [EMCIO] section of the INI file.
G30 - makes a rapid move from the current position
to the absolute position of the values in
parameters 5181-5189.
G30 axes - makes a rapid move to the position
specified by axes including any offsets, then will
make a rapid move to the absolute position of the
values in parameters 5181-5189 for all axes
specified. Any axis not specified will not move.
"""
G30_1 = """G30.1 Set Predefined Position
G30.1 - stores the current absolute position into
parameters 5181-5189.
"""
G33 = """G33 Spindle Synchronized Motion
G33 X Y Z K $
K = Distance per revolution
$ = Spindle to use, optional
For spindle-synchronized motion in one direction,
code G33 X- Y- Z- K- where K gives the distance
moved in XYZ for each revolution of the spindle.
"""
G33_1 = """Rigid Tapping
G33.1 X Y Z K I $
K = distance per revolution
I = optional spindle speed multiplier for faster
return
$ = optional spindle selector
G33.1 moves from the current coordinate to the
specified coordinate, synchronized with the
selected spindle at the given ratio and starting
from the current coordinate with a spindle index
pulse.
Note: To tap a straight hole a pre-position move
to the desired X Y coordinates before issuing a
G33.1.
"""
G38_2 = """G38.2 Straight Probe
G38.2 axes
G38.2 - probe toward workpiece, stop on contact,
signal error if failure
Program G38.2 axes to perform a straight probe
operation. The axis words are optional, except
that at least one of them must be used. The axis
words together define the destination point that
the probe will move towards, starting from the
current location. If the probe is not tripped
before the destination is reached G38.2 will
signal an error.
"""
G38_3 = """G38.3 Straight Probe
G38.3 axes
G38.3 - probe toward workpiece, stop on contact
Program G38.2 axes to perform a straight probe
operation. The axis words are optional, except
that at least one of them must be used. The axis
words together define the destination point that
the probe will move towards, starting from the
current location. If the probe is not tripped
before the destination is reached G38.2 will
signal an error.
"""
G38_4 = """G38.4 Straight Probe
G38.4 axes
G38.4 = probe away from workpiece, stop on loss of
contact, signal error if failure
Program G38.4 axes to perform a straight probe
operation. The axis words are optional, except
that at least one of them must be used. The axis
words together define the destination point that
the probe will move towards, starting from the
current location. If the probe is not tripped
before the destination is reached G38.4 will
signal an error.
"""
G38_5 = """G38.5 Straight Probe
G38.5 axes
G38.5 = probe away from workpiece,
stop on loss of contact
Program G38.5 axes to perform a straight probe
operation. The axis words are optional, except
that at least one of them must be used. The axis
words together define the destination point that
the probe will move towards, starting from the
current location.
"""
G40 = """G40 Cutter Compensation Off
G40 - turn cutter compensation off. If tool
compensation was on the next move must be a linear
move and longer than the tool diameter.
"""
G41 = """G41 Cutter Compensation Left of Path
G41 D
D = tool number
The D word is optional; if there is no D word the
radius of the currently loaded tool will be used
(if no tool is loaded and no D word is given,
a radius of 0 will be used).
"""
G41_1 = """G41.1 Dynamic Cutter Compensation Left of Path
G41.1 D L
D = cutter diameter
L = lathe tool orientation
"""
G42 = """G42 Cutter Compensation Right of Path
G42 D
D = tool number
The D word is optional; if there is no D word the
radius of the currently loaded tool will be used
(if no tool is loaded and no D word is given,
a radius of 0 will be used).
"""
G42_1 = """G42.1 Dynamic Cutter Compensation Right of Path
G41.1 D L
D = cutter diameter
L = lathe tool orientation
"""
G43 = """G43 Tool Length Offset
G43 Hn
n = tool number, Hn is optional
G43 enables tool length compensation. G43 changes
subsequent motions by offsetting the axis
coordinates by the length of the offset. G43 does
not cause any motion. The next time a compensated
axis is moved, that axis's endpoint is the
compensated location.
G43 without an H word uses the currently loaded
tool from the last Tn M6.
G43 Hn uses the offset for tool n.
"""
G43_1 = """G43.1 Dynamic Tool Length Offset
G43.1 axes
G43.1 axes - change subsequent motions by
replacing the current offset(s) of axes. G43.1
does not cause any motion. The next time a
compensated axis is moved, that axis's endpoint is
the compensated location.
"""
G43_2 = """G43.2 Apply additional Tool Length Offset
G43.2 H
H - tool number
G43.2 applies an additional simultaneous tool
offset.
You can sum together an arbitrary number of
offsets by calling G43.2 more times. There are no
built-in assumptions about which numbers are
geometry offsets and which are wear offsets, or
that you should have only one of each.
Like the other G43 commands, G43.2 does not cause
any motion. The next time a compensated axis is
moved, that axis's endpoint is the compensated
location.
"""
G49 = """G49 Cancel Tool Length Compensation
"""
G52 = """G52 Local Coordinate System Offset
G53 axes
G52 is used in a part program as a temporary
"local coordinate system offset" within the
workpiece coordinate system.
"""
G53 = """G53 Move in Machine Coordinates
G53 axes
To move in the machine coordinate system, program
G53 on the same line as a linear move. G53 is not
modal and must be programmed on each line. G0 or
G1 does not have to be programmed on the same
line if one is currently active.
"""
G54 = """G54 Select Coordinate System
G54 = select coordinate system 1
"""
G55 = """G55 Select Coordinate System
G55 = select coordinate system 2
"""
G56 = """G56 Select Coordinate System
G56 = select coordinate system 3
"""
G57 = """G57 Select Coordinate System
G57 = select coordinate system 4
"""
G58 = """G58 Select Coordinate System
G58 = select coordinate system 5
"""
G59 = """G59 Select Coordinate System
G59 = select coordinate system 6
"""
G59_1 = """G59.1 Select Coordinate System
G59.1 = select coordinate system 7
"""
G59_2 = """G59.2 Select Coordinate System
G59.2 = select coordinate system 8
"""
G59_3 = """G59.3 Select Coordinate System
G59.3 = select coordinate system 9
"""
G61 = """G61 Exact Path Mode
G61 = Exact path mode, movement exactly as
programmed. Moves will slow or stop as needed to
reach every programmed point. If two sequential
moves are exactly co-linear movement will not stop
"""
G61_1 = """G61.1 Exact Stop Mode
G61.1 - Exact stop mode, movement will stop at the
end of each programmed segment.
"""
G64 = """G64 Path Blending
G64 P Q
P = motion blending tolerance
Q = naive cam tolerance
G64 - without P means to keep the best speed
possible, no matter how far away from the
programmed point you end up.
The P tolerance means that the actual path will be
no more than P away from the programmed endpoint.
The velocity will be reduced if needed to maintain
the path.
G64 P- Q- turns on the naive cam detector. When
there are a series of linear XYZ feed moves at the
same feed rate that are less than Q away from
being collinear, they are collapsed into a single
linear move.
"""
G73 = """G73 Drilling Cycle with Chip Breaking
G73 X Y Z R Q L
R = retract position along the Z axis
Q = delta increment along the Z axis
L = repeat
The G73 cycle is drilling or milling with chip
breaking. This cycle takes a Q number which
represents a delta increment along the Z axis.
Motion Sequence
If the current Z position is below the R position,
The Z axis does a rapid move to the R position.
Move to the X Y coordinates.
Move the Z-axis only at the current feed rate
downward by delta or to the Z position, whichever
is less deep.
Rapid up a bit.
Repeat steps 2 and 3 until the Z position is
reached at step 2.
The Z axis does a rapid move to the R position.
"""
G74 = """G74 Left-hand Tapping Cycle, Dwell
G74 (X Y Z) or (U V W) R L P $
R = retract position along the Z axis
L = repeat
P = dwell
$ = spindle
The G74 cycle is for tapping with floating chuck
and dwell at the bottom of the hole.
"""
G76 = """Lathe Threading Cycle
G76 P Z I J R K Q H E L $
P = The thread pitch in distance per revolution.
Z = The final position of threads.
I = The thread peak offset from the drive line.
J = A positive value specifying the initial cut
depth.
K = A positive value specifying the full thread
depth.
Optional settings
$ = spindle to which the motion will be
synchronised.
R = The depth degression. R1.0 selects constant
depth on successive threading passes.
Q = The compound slide angle is the angle
(in degrees) describing to what extent
successive passes should be offset along the
drive line.
H = The number of spring passes.
E = Specifies the distance along the drive line
used for the taper.
L = Specifies which ends of the thread get the
taper.
L0 for no taper (the default)
L1 for entry taper
L2 for exit taper
L3 for both entry and exit tapers
"""
G80 = """Cancel Canned Cycle
"""
G81 = """G81 Drilling Cycle
G81 X Y Z or (U V W) R L
R = retract position along the Z axis
L = repeat
"""
G82 = """G82 Drilling Cycle, Dwell
G82 X Y Z or (U V W) R L P
R = retract position along the Z axis
L = repeat
P = dwell
"""
G83 = """G83 Peck Drilling Cycle
G83 X Y Z or (U V W) R L Q
R = retract position along the Z axis
L = repeat
Q = delta increment along the Z axis
"""
G84 = """G84 Right-hand Tapping Cycle, Dwell
G84 X Y Z or (U V W) R L P $
R = retract position along the Z axis
L = repeat
P = dwell
$ = spindle
"""
G85 = """G85 Boring Cycle, Feed Out
G85 X Y Z or (U V W) R L
R = retract position along the Z axis
L = repeat
"""
G86 = """G86 Boring Cycle, Spindle Stop, Rapid Move Out
G84 X Y Z or (U V W) R L P $
R = retract position along the Z axis
L = repeat
P = dwell
$ = spindle
"""
G89 = """G89 Boring Cycle, Dwell, Feed Out
G89 X Y Z or (U V W) R L P
R = retract position along the Z axis
L = repeat
P = dwell
"""
G90 = """G90 Absolute Distance Mode
In absolute distance mode, axis numbers
(X, Y, Z, A, B, C, U, V, W) usually represent
positions in terms of the currently active
coordinate system.
"""
G90_1 = """G90.1 Absolute Distance Mode
for I, J & K offsets
"""
G91 = """G91 Incremental Distance Mode
In incremental distance mode axis numbers usually
represent increments from the current coordinate.
"""
G91_1 = """G91.1 Incremental Distance Mode
for I, J & K offsets
"""
G92 = """G92 Coordinate System Offset
G92 axes
G92 makes the current point have the coordinates
you want (without motion), where the axis words
contain the axis numbers you want. All axis words
are optional, except that at least one must be
used. If an axis word is not used for a given
axis, the offset for that axis will be zero.
"""
G92_1 = """G92.1 Turn Off G92, Reset
G92.1 turns off G92 offsets and resets
parameters 5211 - 5219 to zero.
"""
G92_2 = """G92.2 Turn Off G92
G92.2 turns off G92 offsets and does not
change parameters 5211 - 5219.
"""
G92_3 = """G92.3 Restore G92 Offsets
G92.3 sets the G92 offset to the values
saved in parameters 5211 to 5219.
"""
G93 = """G93 Inverse Time Feed Mode
G93 inverse time feed rate mode, an F word means
the move should be completed in [one divided by
the F number of minutes.
When the inverse time feed rate mode is active, an
F word must appear on every line which has a G1,
G2, or G3 motion, and an F word on a line that
does not have G1, G2, or G3 is ignored.
"""
G94 = """G94 Units per Minute Feed Mode
G94 units per minute feed mode, an F word is
interpreted to mean the controlled point should
move at a certain number of inches per minute,
millimeters per minute, or degrees per minute,
depending upon what length units are being used
and which axis or axes are moving.
"""
G95 = """G95 Units per Revolution Feed Mode
G95 units per revolution mode, an F word is
interpreted to mean the controlled point should
move a certain number of inches per revolution of
the spindle, depending on what length units are
being used and which axis or axes are moving.
"""
G96 = """G96 Spindle Constant Surface Speed Mode
G96 D S $
D = maximum spindle RPM
S = surface speed
$ = spindle
"""
G97 = """G97 Spindle RPM Mode
G97 selects RPM mode.
"""
G98 = """G98 Canned Cycle Return Level
G98 - retract to the position that axis was in
just before this series of one or more contiguous
canned cycles was started.
"""
G99 = """G99 Canned Cycle Return Level
G99 - retract to the position specified
by the R word of the canned cycle.
"""

View File

@@ -0,0 +1,298 @@
from qtpy.QtWidgets import *
from qtpy.QtCore import Qt
from qtpy.QtGui import QColor
from qtvcp.core import Status, Info
from qtvcp.widgets.dialog_widget import LcncDialog
import hal
# Set up logging
from qtvcp import logger
log = logger.getLogger(__name__)
# Instantiate the libraries with global reference
# STATUS gives us status messages from linuxcnc
STATUS = Status()
INFO = Info()
DEFAULT = 0
WARNING = 1
CRITICAL = 2
class Message:
def __init__(self):
self.QUESTION = QMessageBox.Question
self.INFO = QMessageBox.Information
self.WARNING = QMessageBox.Warning
self.CRITICAL = QMessageBox.Critical
self._color = QColor(0, 0, 0, 150)
self.focus_text = ' '
self.play_sounds = True
self.alert_sound = 'ATTENTION'
self.use_focus_overlay = True
# search for and set up user requested message system.
# status displays on the statusbar and requires no acknowledge.
# dialog displays a Messagebox with yes or no buttons
# okdialog displays a Messagebox with an ok button
# dialogs require an answer before focus is sent back to main screen
def message_setup(self, hal_comp, window=None, notify=None):
self.HAL_GCOMP_ = hal_comp
self.NOTIFY = notify
# if no notify supplied, make our owm
if not notify is None:
self.notify_normal = self.NOTIFY.new_normal()
if INFO.ZIPPED_USRMESS:
for boldtext, text, pinname, details, name, icon in (INFO.ZIPPED_USRMESS):
if not ("status" in details)\
and not ("dialog" in details):
log.info('invalid message type {} in INI File [DISPLAY] section'.format(details))
continue
if icon.upper() == 'CRITICAL': icon = QMessageBox.Critical
elif icon.upper() == 'INFO': icon = QMessageBox.Information
elif icon.upper() == 'WARNING': icon = QMessageBox.Warning
else: icon = QMessageBox.Question
if not name == None:
D = self['dialog-{}'.format(name)] = LcncDialog(window)
D._request_name = 'INI_MESSAGE_{}'.format(name)
D._geoName = name+'-geometry'
D.hal_init(HAL_NAME=name)
D.pinname = name
# this is how we make a pin that can be connected to a callback
if ("none" in details):
D._halpin = self.HAL_GCOMP_.newpin(name, hal.HAL_BIT, hal.HAL_IN)
else:
D._halpin = self.HAL_GCOMP_.newpin(name, hal.HAL_BIT, hal.HAL_IO)
D._halpin.value_changed.connect(self.messageCallback(self['dialog-{}'.format(name)],
D._halpin, name, boldtext, text, pinname, details, icon))
if ("dialog" in details) and not ("nonedialog" in details):
self.HAL_GCOMP_.newpin(name + "-waiting", hal.HAL_BIT, hal.HAL_OUT)
if not ("ok" in details):
self.HAL_GCOMP_.newpin(name + "-response", hal.HAL_BIT, hal.HAL_OUT)
self.HAL_GCOMP_.newpin(name + "-response-s32", hal.HAL_S32, hal.HAL_OUT)
self.HAL_GCOMP_[name + "-response-s32"] = -1 # undetermined
if not INFO.USRMULTIMESS_ID is None:
for name in INFO.USRMULTIMESS_ID:
mess = INFO['{}_MULTIMESS'.format(name)]
D = self['dialog-MULTIMESSAGE-{}'.format(name)] = LcncDialog(window)
D._request_name = 'INI_MULTIMESSAGE_{}'.format(name)
D._geoName = name+'-geometry'
D.hal_init(HAL_NAME=name)
D.pinname = name
D._halpin = self.HAL_GCOMP_.newpin(name, hal.HAL_S32, hal.HAL_IN)
D._halpin.value_changed.connect(self.multiMessageCallback(D,
D._halpin, name, mess, ))
if ("dialog" in details) and not ("nonedialog" in details):
self.HAL_GCOMP_.newpin(name + "-waiting", hal.HAL_BIT, hal.HAL_OUT)
# This weird code is so we can get access to proper variables.
# using clicked.connect( self.on_printmessage(pin,name,bt,t,c) ) apparently doesn't easily
# add user data - it seems you only get the last set added
# found this closure technique hack on the web
# truly weird black magic
def messageCallback(self, dialog, pin, pinname, boldtext, text, details, type, icon):
def calluser():
self.on_printmessage(dialog, pin, pinname, boldtext, text, details, type, icon)
return calluser
def multiMessageCallback(self, dialog, pin, name, messages):
def calluser():
mess = messages.get(pin.get())
# no message? hide dialog and return
if mess is None:
dialog.record_geometry()
dialog.hide()
if self.use_focus_overlay:
STATUS.emit('focus-overlay-changed', False, None, None)
return
# extract info from message
messtype, title, text, details, icon, options = mess
self.on_printmessage(dialog, pin, name, title, text, details, messtype, icon, options)
return calluser
# This is part of the user message system
# There is status that prints to the status bar
# There is Okdialog that prints a dialog that the user must acknowledge
# there is yes/no dialog where the user must choose between yes or no
# you can combine status and dialog messages so they print to the status bar
# and pop a dialog
# This gets called as the HAL pin changes state
def on_printmessage(self, dialog, pin, pinname, boldtext, text, details, type, icon, options={}):
# hide a no button dialog if pin goes False
if not pin.get():
if dialog.style == LcncDialog.NONE:
dialog.record_geometry()
dialog.hide()
return
if self.play_sounds:
STATUS.emit('play-sound', self.alert_sound)
if boldtext == "NONE": boldtext = ''
if "status" in type:
mess = {}
mess['TITLE']=boldtext
mess["SHORTTEXT"]=text
mess['DETAILS']=details
STATUS.emit('status-message', mess, options)
# (NOTIFY object injected from screenoption widget)
if not self.NOTIFY is None:
if "ok" in type:
self.NOTIFY.notify_ok( boldtext, text, '',5, self.okReturn)
else:
self.NOTIFY.update(self.notify_normal, boldtext, text)
if "dialog" in type or "okdialog" in type:
if self.use_focus_overlay:
STATUS.emit('focus-overlay-changed', True, self.focus_text, self._color)
if "nonedialog" in type: style = LcncDialog.NONE
elif "okdialog" in type: style = LcncDialog.OK
elif "yesnodialog" in type: style = LcncDialog.YESNO
elif "okcancel" in type: style = LcncDialog.OKCANCEL
elif "closeprompt" in type: style = LcncDialog.CLOSEPROMPT
dialog.style = style
if style != LcncDialog.NONE:
self.HAL_GCOMP_[pinname + "-waiting"] = True
if style != LcncDialog.OK:
if pin.get():
self.HAL_GCOMP_[pinname + "-response"] = False
self.HAL_GCOMP_[pinname + "-response-s32"] = -1
self.showDialog(dialog, boldtext, text, details, style, icon, pinname)
def showDialog(self, dialog, message, more_info=None, details=None, display_type='OK',
icon=QMessageBox.Information, pinname=None, focus_text=None,
focus_color=None, play_alert=None, nblock= False,
return_callback = None, flags = None, setflags = None,
title = None):
if type(icon) == str:
if icon.upper() == 'CRITICAL': icon = QMessageBox.Critical
elif icon.upper() == 'INFO': icon = QMessageBox.Information
elif icon.upper() == 'WARNING': icon = QMessageBox.Warning
else: icon = QMessageBox.Question
if return_callback == None:
return_callback = self.dialog_return
flags = (Qt.Tool | Qt.Dialog | Qt.WindowStaysOnTopHint\
| Qt.WindowSystemMenuHint | Qt.CustomizeWindowHint)
title = 'User Message'
setFlags = {Qt.WindowCloseButtonHint: False}
dialog.showdialog( message, more_info=more_info, details=details, display_type=display_type,
icon=icon, pinname=pinname, focus_text=None,
focus_color=None, play_alert=None, nblock= nblock,
return_callback = return_callback, flags = flags, setflags = setFlags,
title = title,geoname=dialog._geoName)
def okReturn(self, data):
print(data)
# for testing, could be overridden
def msgbtn(self, i):
pass
# print "Button pressed is:",i.text()
# a hacky way to adjust future options
# using it to adjust runtime options from a preference file in screenoptions (presently)
# 'with great power comes ....'
# screenOptions injects the NOTICE library this way
def message_option(self, option, data):
try:
self[option] = data
except:
pass
# message dialog returns a response here
# update any hand shaking pins
# this is called by LcncDialog using callback mechanism
def dialog_return(self, dialog, result):
if not dialog.style == LcncDialog.NONE:
if dialog.pinname:
self.HAL_GCOMP_[dialog.pinname + "-waiting"] = False
if not dialog.style == LcncDialog.OK:
self.HAL_GCOMP_[dialog.pinname + "-response"] = result
if result:
num = 1
else:
num = 0
self.HAL_GCOMP_[dialog.pinname + "-response-s32"] = num
# reset the HAL IO pin so it can fire again
self.HAL_GCOMP_[dialog.pinname] = False
if self.use_focus_overlay:
STATUS.emit('focus-overlay-changed', False, None, None)
##############################
# required class boiler code #
##############################
def __getitem__(self, item):
return getattr(self, item)
def __setitem__(self, item, value):
return setattr(self, item, value)
if __name__ == '__main__':
import sys
from qtpy.QtCore import *
def callreturn(dialog, btn, pinname):
result = dialog.qualifiedReturn(btn)
print(dialog, ' = ', result)
m = Message()
app = QApplication(sys.argv)
w = QWidget()
dialogb = LcncDialog()
b = QPushButton(w)
b.setText("Show Y/N\n message!")
b.move(10, 0)
b.clicked.connect(lambda data: m.showDialog(dialogb, 'This is a question message',
more_info='Pick yes or no', icon=m.QUESTION,
display_type=LcncDialog.YESNO,
return_callback = callreturn))
dialogc = LcncDialog()
c = QPushButton(w)
c.setText("Show OK\n message!")
c.move(10, 40)
c.clicked.connect(lambda data: m.showDialog(dialogc, 'This is an OK message',
display_type=LcncDialog.OK, return_callback = callreturn))
dialogd = LcncDialog()
d = QPushButton(w)
d.setText("Show warning\n message!")
d.move(10, 80)
d.clicked.connect(lambda data: m.showDialog(dialogd,'This is a Warning message',
details='There seems to be something wrong\n feel free to ignore', icon=m.WARNING,
display_type=LcncDialog.OK, return_callback = callreturn))
dialoge = LcncDialog()
e = QPushButton(w)
e.setText("Show critical\n persistent message!")
e.move(10, 120)
e.clicked.connect(lambda data: m.showDialog(dialoge, 'This is a Critical persistent message',
details='There seems to be something wrong\n You must fix it to clear message', icon=m.CRITICAL,
display_type=LcncDialog.NONE,return_callback = callreturn, nblock=True))
w.setWindowTitle("PyQt Dialog demo")
w.setGeometry(300, 300, 300, 150)
w.show()
sys.exit(app.exec())

View File

@@ -0,0 +1,334 @@
# try to add a notify system so messages use the
# nice integrated pop-ups
# Ubuntu kinda wrecks this be not following the
# standard - you can't set how long the message stays up for.
# I suggest fixing this with a PPA off the net
# https://launchpad.net/~leolik/+archive/leolik?field.series_filter=lucid
# callback work around:
# http://stackoverflow.com/questions/8727937/callbacks-and-gtk-main-loop
from qtvcp.core import Status, Info
from qtvcp.lib import sys_notify
# Set up logging
from qtvcp import logger
log = logger.getLogger(__name__)
STATUS = Status()
INFO = Info()
sys_notify.init('notify')
class Notify:
YESNO = 'yesNo'
JOGPAUSED = 'jogPaused'
OKCANCEL = 'okCancel'
CLOSE = 'close'
LASTFIVE = 'lastFive'
CLEARALL = 'clearAll'
BACKGROUND = 'background'
def __init__(self):
self.statusbar = None
self.lastnum = 0
self.notify_list = []
self.alarmpage = []
self.critical_message = None
self.normal_message = None
self.hard_limits_message = None
self.clicked = None
STATUS.connect('shutdown', self.cleanup)
# This prints a message in the status bar (if available)
# the system notifier (if available)
# adds an entry to the alarm page (if available)
def notify(self, title, message, icon="", status_timeout=0, timeout=2):
messageid = None
try:
self.show_status(message, status_timeout)
except:
pass
try:
n = self.build_general_notification(title, message, icon, timeout=timeout)
n.show()
except Exception as e:
log.warning('build_generalnotification error:', exc_info=e)
return n
# Screenoption uses this for errors / operator messages
# they stay up till cleared
# self.critical_message gives reference for external controls
def new_critical(self, icon=""):
messageid = None
try:
self.critical_message = self.build_error_notification(icon)
except Exception as e:
log.warning('New_critical error:', exc_info=e)
return self.critical_message
# Screenoption uses this for hard limit errors
# they stay up till cleared
# self.critical_message gives reference for external controls
def new_hard_limits(self, icon="", callback=None):
messageid = None
try:
self.hard_limits_message = self.build_hard_limits_notification(icon, callback)
except Exception as e:
log.warning('New_critical error:', exc_info=e)
return self.hard_limits_message
# Screenoption uses this for errors / operator messages
# they stay up till cleared
# self.critical_message gives reference for external controls
def new_normal(self, icon=""):
messageid = None
try:
self.normal_message = self.build_general_notification(icon)
except Exception as e:
log.warning('New_critical error:', exc_info=e)
return self.normal_message
# messages that require yes/no response.
def notify_yn(self, title, message, icon, timeout, function_callback):
try:
self.show_yn_notification(title, message, icon, timeout, function_callback)
except Exception as e:
log.warning('build_generalnotification_yn error:', exc_info=e)
# message that require acknowledgement
def notify_ok(self, title, message, icon, timeout, function_callback):
try:
self.show_ok_notification(title, message, icon, timeout, function_callback)
except Exception as e:
log.warning('build_generalnotification_ok error:', exc_info=e)
#####################################################
# actually build the notices
#####################################################
def build_error_notification(self, icon=None):
n = sys_notify.Notification('', '', icon)
n.setUrgency(sys_notify.Urgency.CRITICAL)
n.setTimeout(0)
n.addAction("action_click", "Show Last Five", self.last5_callback)
n.onClose(self.handle_closed)
n.addAction('destroy_clicked', 'Clear All', self.destroyClicked)
n.addAction('close_clicked', 'Close', self.closeClicked)
self.notify_list.append(n)
return n
def build_hard_limits_notification(self, icon=None, callback=None):
self._hardLimitsCallback = callback
n = sys_notify.Notification('', '', icon)
n.setUrgency(sys_notify.Urgency.CRITICAL)
n.setTimeout(0)
n.addAction("action_click", "Override Limits", self._hardLimitsCallback)
n.onClose(self.handle_closed)
n.addAction('close_clicked', 'Close', self.closeClicked)
self.notify_list.append(n)
return n
def build_general_notification(self, title='', message='', icon=None, timeout=2):
n = sys_notify.Notification(title, message, icon)
n.setUrgency(sys_notify.Urgency.NORMAL)
n.setTimeout(int(timeout * 1000))
n.addAction("action_click", "Show Last Five", self.last5_callback)
n.addAction('destroy_click', 'Clear All', self.destroyClicked)
n.addAction('close_clicked', 'Close', self.closeClicked)
n.onClose(self.handle_closed)
self.notify_list.append(n)
return n
def show_yn_notification(self, title, message, icon, timeout, callback):
self._callback = callback
n = sys_notify.Notification(title, message, icon)
n.setUrgency(sys_notify.Urgency.CRITICAL)
n.setTimeout(timeout * 1000)
n.addAction("Yes", "Yes", self.yesClicked, callback)
n.onClose(self.handle_closed)
n.addAction('No', 'No', self.noClicked, callback)
n.show()
self.notify_list.append(n)
def show_ok_notification(self, title, message, icon, timeout, callback):
n = sys_notify.Notification(title, message, icon)
n.setUrgency(sys_notify.Urgency.CRITICAL)
n.setTimeout(timeout * 1000)
n.addAction("Ok", "ok", self.okClicked, callback)
n.onClose(self.handle_closed)
n.addAction('Cancel', 'cancel', self.cancelClicked, callback)
n.show()
self.notify_list.append(n)
def show_toolchange_notification(self, title, message, icon, timeout, callback, jogpause=False):
n = sys_notify.Notification(title, message, icon)
n.setUrgency(sys_notify.Urgency.CRITICAL)
n.setTimeout(0)
n.addAction("action_click", "Ok", self.okClicked, callback)
n.onClose(lambda w:self.okClicked(w, None, callback))
if jogpause:
n.addAction('close_clicked', 'jogPause', self.jogPauseClicked)
n.show()
self.notify_list.append(n)
return n
################################################
# callback mechanism
################################################
def yesClicked(self, n, action, callback):
callback(True)
STATUS.emit('system_notify_button_pressed', Notify.YESNO, True)
def noClicked(self, n, action, callback):
callback(False)
STATUS.emit('system_notify_button_pressed', Notify.YESNO, True)
def okClicked(self, n, action, callback):
callback(True)
STATUS.emit('system_notify_button_pressed', Notify.OKCANCEL, True)
def cancelClicked(self, n, action, callback):
callback(False)
STATUS.emit('system_notify_button_pressed', Notify.OKCANCEL, True)
def jogPauseClicked(self, n, action, callback):
callback(-1)
STATUS.emit('system_notify_button_pressed', Notify.JOGPAUSE, True)
def handle_closed(self, n):
if not self.clicked in [Notify.CLEARALL, Notify.CLOSE, Notify.LASTFIVE]:
STATUS.emit('system_notify_button_pressed', Notify.BACKGROUND, True)
STATUS.emit('play-sound', 'SPEAK _KILL_')
self.clicked = None
def closeClicked(self, n, text):
self.clicked = Notify.CLOSE
n.close()
STATUS.emit('system_notify_button_pressed', Notify.CLOSE, True)
STATUS.emit('play-sound', 'SPEAK _KILL_')
def OnClicked(self, n, signal_text):
print(f'1: {str(n)}')
print(f'2: {str(signal_text)}')
n.close()
def action_callback(self, *args, **kwds):
print('\nAll recorded messages:')
for num, i in enumerate(self.alarmpage):
print(num, i)
# pop up last five critical errors
def last5_callback(self, n, signal_text):
self.clicked = Notify.LASTFIVE
icon = getattr(n, 'icon', None)
n = self.build_error_notification(icon=icon)
n.body = ''
for i in range(1, 6):
num = len(self.alarmpage) - i
if i > len(self.alarmpage): break
n.body = f'{n.body}\nREVIEW #{num + 1} of {len(self.alarmpage)}\n{self.alarmpage[num][1]}'
n.show()
STATUS.emit('system_notify_button_pressed', Notify.LASTFIVE, True)
def destroyClicked(self, n, signal_text):
self.clicked = Notify.CLEARALL
self.alarmpage = []
n.body = ''
STATUS.emit('system_notify_button_pressed', Notify.CLEARALL, True)
STATUS.emit('play-sound', 'SPEAK _KILL_')
#####################################################
# General work functions
#####################################################
# update the critical message display
# this adds the new message to the old
# show a max of 10 messages on screen
def update(self, n, icon='', title='', message='', status_timeout=5, timeout=None, msgs=10):
if title is not None:
n.title = title
if icon:
n.icon = icon
if self.alarmpage ==[]:
n.body = f'{title}\n{message}'
elif len(self.alarmpage) < (msgs - 1):
n.body = ''
for i in range(len(self.alarmpage)):
n.body += f'\n{self.alarmpage[i][1]}'
n.body += f'\n{title}\n{message}'
else:
n.body = ''
for i in range(len(self.alarmpage) - (msgs - 1), len(self.alarmpage)):
n.body += f'\n{self.alarmpage[i][1]}'
n.body += f'\n{title}\n{message}'
if timeout is not None:
n.setTimeout(timeout * 1000)
n.show()
try:
self.show_status(message, status_timeout)
except:
pass
try:
self.add_alarm_entry(n, message)
except:
pass
# try to update a status bar if we were given reference to it
def show_status(self, message, timeout=4):
if self.statusbar is not None:
try:
messageid = self.statusbar.showMessage(message, timeout * 1000)
except:
try:
messageid = self.statusbar.setText(message)
except Exception as e:
log.verbose(f'Error adding msg to statusbar: {e}')
# show the previous critical messages that popped up
# Currently alarm page doesn't keep track of what
# notice made the alarm so we might get question dialogs too.
def show_last(self):
num = len(self.alarmpage) - 1 - self.lastnum
if self.critical_message is not None:
if self.alarmpage:
n = self.alarmpage[num][0]
n.body = f'Review #{self.lastnum + 1} of {len(self.alarmpage)}\n{self.alarmpage[num][1]}'
n.show()
self.show_status(n.body)
# ready for next message if there is one, other wise reset counter
self.lastnum += 1
if self.lastnum >= len(self.alarmpage):
n.body = ''
self.lastnum = 0
def find_visible(self):
for n,i in enumerate(self.notify_list):
if i.isVisible:
return i
return None
def get_list(self):
return self.notify_list
def external_close(self):
if self.critical_message is not None:
n = self.critical_message
n.body = ''
n.close()
if self.normal_message is not None:
self.normal_message.close()
self.lastnum = 0
# update the system alarm page, if there is one
# this should be sent to STATUS message I think?
def add_alarm_entry(self, mobject, message):
if message == None: message = ''
try:
self.alarmpage.append((mobject, message))
except:
pass
# close any remaining messages when we shutdown qtvcp
def cleanup(self, w):
for i in self.notify_list:
i.close()

View File

@@ -0,0 +1,90 @@
# Touchy is Copyright (c) 2009 Chris Radek <chris@timeguy.com>
#
# Touchy 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.
#
# Touchy 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 os
import configparser
cp = configparser.RawConfigParser
cp.optionxform = str
class Access(cp):
types = {
bool: cp.getboolean,
float: cp.getfloat,
int: cp.getint,
str: cp.get,
repr: lambda self, section, option: eval(cp.get(self, section, option)),
}
def __init__(self, path=None):
cp.__init__(self)
if not path:
path = "~/.qtscreen_preferences"
self.fn = os.path.expanduser(path)
try:
fp = open(self.fn)
except:
print('preference file does not exist -makeing file - {}'.format(self.fn))
# If not exists, create the file
fp = open(self.fn, 'w+')
self.read(self.fn)
def getpref(self, option, default=False, type=bool, section="DEFAULT"):
m = self.types.get(type)
if m is None:
m = self.types.get(repr)
try:
o = m(self, section, option)
except Exception as detail:
print(detail)
try:
self.set(section, option, default)
except configparser.NoSectionError:
print('Adding section %s' % section)
# Create non-existent section
self.add_section(section)
self.set(section, option, default)
self.write(open(self.fn, "w"))
if type in (bool, float, int):
o = type(default)
else:
o = default
return o
def getall(self, section='DEFAULT'):
store = {}
try:
for key, value in cp.items(self, section):
store[key] = value
return store
except configparser.NoSectionError:
self.add_section(section)
return store
def putpref(self, option, value, type=bool, section="DEFAULT"):
try:
self.set(section, option, type(value))
except configparser.NoSectionError:
print('Adding section %s' % section)
# Create non-existent section
self.add_section(section)
self.set(section, option, type(value))
self.write(open(self.fn, "w"))
def removepref(self, option, section):
try:
self.remove_option(section, option)
except configparser.NoSectionError:
print('Section {} does not exist'.format(section))

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,734 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>1028</width>
<height>414</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="spacing">
<number>0</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3" stretch="0,0">
<property name="spacing">
<number>4</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<item>
<widget class="QFrame" name="frame_info">
<property name="minimumSize">
<size>
<width>350</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>300</width>
<height>16777215</height>
</size>
</property>
<layout class="QVBoxLayout" name="layout_left" stretch="0,0,0,0,0,0">
<property name="spacing">
<number>4</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<property name="spacing">
<number>2</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<item>
<widget class="QCheckBox" name="chk_expand">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>30</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>30</height>
</size>
</property>
<property name="toolTip">
<string>Expand subroutines when created</string>
</property>
<property name="text">
<string>EXPAND SUB</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chk_autosend">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>30</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>30</height>
</size>
</property>
<property name="toolTip">
<string>Send to linuxcnc instead of file</string>
</property>
<property name="text">
<string>AUTOSEND</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chk_save">
<property name="toolTip">
<string>Always save when code is finalized</string>
</property>
<property name="text">
<string>Save?</string>
</property>
<property name="checked">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="chk_add_m2">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>30</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>30</height>
</size>
</property>
<property name="toolTip">
<string>Append M2 to end of gcode files</string>
</property>
<property name="text">
<string>ADD M2</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_4">
<property name="spacing">
<number>4</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="lbl_preamble">
<property name="minimumSize">
<size>
<width>40</width>
<height>30</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>40</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>PRE</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_preamble">
<property name="minimumSize">
<size>
<width>0</width>
<height>30</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>30</height>
</size>
</property>
<property name="toolTip">
<string>Preamble filename</string>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_6">
<property name="spacing">
<number>4</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="lbl_post">
<property name="minimumSize">
<size>
<width>40</width>
<height>30</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>40</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>POST</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_postamble">
<property name="minimumSize">
<size>
<width>0</width>
<height>30</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>30</height>
</size>
</property>
<property name="toolTip">
<string>Postamble filename</string>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="spacing">
<number>4</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="features">
<property name="minimumSize">
<size>
<width>0</width>
<height>30</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>30</height>
</size>
</property>
<property name="text">
<string>SECTION
FEATURES</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lbl_features">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>60</width>
<height>30</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>60</width>
<height>30</height>
</size>
</property>
<property name="maxLength">
<number>4</number>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="features_total">
<property name="text">
<string>TOTAL
FEATURES</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lbl_features_total">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>60</width>
<height>30</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>60</width>
<height>30</height>
</size>
</property>
<property name="maxLength">
<number>4</number>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QLabel" name="lbl_image">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Expanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>Image label</string>
</property>
<property name="scaledContents">
<bool>true</bool>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QTextEdit" name="textEdit_status">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>60</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>100</height>
</size>
</property>
<property name="horizontalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="readOnly">
<bool>true</bool>
</property>
<property name="placeholderText">
<string>Status messages</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<widget class="QFrame" name="frame_tabs">
<layout class="QVBoxLayout" name="layout_tab_widget">
<property name="spacing">
<number>4</number>
</property>
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>-1</number>
</property>
<property name="tabsClosable">
<bool>true</bool>
</property>
<property name="movable">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QWidget" name="widget_controls" native="true">
<property name="minimumSize">
<size>
<width>0</width>
<height>50</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>50</height>
</size>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_5">
<property name="spacing">
<number>4</number>
</property>
<property name="leftMargin">
<number>2</number>
</property>
<property name="topMargin">
<number>2</number>
</property>
<property name="rightMargin">
<number>2</number>
</property>
<property name="bottomMargin">
<number>2</number>
</property>
<item>
<widget class="QPushButton" name="btn_add_tab">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>NEW
TAB</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btn_select_pre">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>SELECT
PREAMBLE</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btn_select_sub">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="toolTip">
<string>Add subroutine file to this section</string>
</property>
<property name="text">
<string>SELECT
SUBFILE</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btn_select_pst">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="text">
<string>SELECT
POST</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btn_reread">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="toolTip">
<string>Reread subroutine file</string>
</property>
<property name="text">
<string>REREAD
FILE</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btn_create">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="toolTip">
<string>Create gcode features</string>
</property>
<property name="text">
<string>CREATE
FEATURE</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btn_restart">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="toolTip">
<string>Clear all features for current tab</string>
</property>
<property name="text">
<string>RESTART
FEATURES</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btn_finalize">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>16777215</height>
</size>
</property>
<property name="toolTip">
<string>Assemble all features into gcode file</string>
</property>
<property name="text">
<string>FINALIZE
GCODE</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

View File

@@ -0,0 +1,163 @@
import sys
import os
from qtpy import QtGui, QtWidgets
from qtpy.QtCore import Qt
# Set up logging
from qtvcp import logger
LOG = logger.getLogger(__name__)
USE_QTPDF = False
USE_POPPLER = False
import qtpy
if qtpy.PYQT6:
try:
from qtpy.QtPdf import QPdfDocument, QPdfDocumentRenderOptions
_QTPDF_RENDER_OPTS = QPdfDocumentRenderOptions()
_QTPDF_RENDER_OPTS.setRenderFlags(
QPdfDocumentRenderOptions.RenderFlag.Annotations
)
USE_QTPDF = True
except Exception as e:
LOG.warning('PDFViewer - QtPdf is not available, install python3-pyqt6.qtpdf')
print(e)
elif qtpy.PYQT5:
try:
import popplerqt5
USE_POPPLER = True
except Exception:
LOG.warning('PDFViewer - Poppler qt5 is not available, install python3-poppler-qt5')
LIB_BAD = not USE_QTPDF and not USE_POPPLER
class PDFView(QtWidgets.QScrollArea):
def __init__(self, parent=None):
super(PDFView, self).__init__(parent)
self.setWidgetResizable(True)
self.widget = QtWidgets.QWidget()
self.setWidget(self.widget)
self.vbox = QtWidgets.QVBoxLayout()
self.widget.setLayout(self.vbox)
self._zoom = 1.0
self._doc = None
if LIB_BAD:
label = QtWidgets.QLabel('<b>Missing PDF backend: install python3-poppler-qt5 or use Qt6 with QtPdf</b>')
self.vbox.addWidget(label)
def loadSample(self, name):
n = os.path.join(os.path.dirname(__file__),name+'.pdf')
if os.path.exists(n):
self.loadView(n)
else:
LOG.warning('Sample {}, does not exists at: {}'.format(name, n))
def loadView(self, path):
filename = os.path.expanduser(path)
if not os.path.exists(filename):
print('No path:', filename)
return
if LIB_BAD:
return
if USE_QTPDF:
if self._doc is None:
self._doc = QPdfDocument(self)
self._doc.load(filename)
else:
self._doc = popplerqt5.Poppler.Document.load(filename)
self._doc.setRenderHint(popplerqt5.Poppler.Document.Antialiasing)
self._doc.setRenderHint(popplerqt5.Poppler.Document.TextAntialiasing)
self.refreshPages()
def refreshPages(self):
if self._doc is None:
return
# clear layout of pages
for i in reversed(range(self.vbox.count())):
self.vbox.itemAt(i).widget().setParent(None)
# convert pages to images in a label
if USE_QTPDF:
for i in range(self._doc.pageCount()):
label = QtWidgets.QLabel()
label.setScaledContents(True)
page_size = self._doc.pagePointSize(i)
render_size = (page_size * self._zoom).toSize()
image = self._doc.render(i, render_size, _QTPDF_RENDER_OPTS)
label.setPixmap(QtGui.QPixmap.fromImage(image))
self.vbox.addWidget(label)
else:
for i in range(self._doc.numPages()):
label = QtWidgets.QLabel()
label.setScaledContents(True)
page = self._doc.page(i)
image = page.renderToImage(72.0 * self._zoom, 72.0 * self._zoom)
label.setPixmap(QtGui.QPixmap.fromImage(image))
self.vbox.addWidget(label)
def zoomFactor(self):
return self._zoom
def setZoomFactor(self, factor):
if factor > 3: factor = 3.0
if factor < .5: factor = .5
self._zoom = factor
self.refreshPages()
def pdf_view(filename):
"""Return a Scrollarea showing the pages of the specified PDF file."""
filename = os.path.expanduser(filename)
if not os.path.exists(filename):
print('No path:', filename)
area = QtWidgets.QScrollArea()
area.setWidgetResizable(True)
widget = QtWidgets.QWidget()
vbox = QtWidgets.QVBoxLayout()
if USE_QTPDF:
doc = QPdfDocument()
doc.load(filename)
for i in range(doc.pageCount()):
label = QtWidgets.QLabel()
label.setScaledContents(True)
page_size = doc.pagePointSize(i)
image = doc.render(i, page_size.toSize(), _QTPDF_RENDER_OPTS)
label.setPixmap(QtGui.QPixmap.fromImage(image))
vbox.addWidget(label)
else:
doc = popplerqt5.Poppler.Document.load(filename)
doc.setRenderHint(popplerqt5.Poppler.Document.Antialiasing)
doc.setRenderHint(popplerqt5.Poppler.Document.TextAntialiasing)
for i in range(doc.numPages()):
label = QtWidgets.QLabel()
label.setScaledContents(True)
page = doc.page(i)
image = page.renderToImage()
label.setPixmap(QtGui.QPixmap.fromImage(image))
vbox.addWidget(label)
widget.setLayout(vbox)
area.setWidget(widget)
return area
def main():
app = QtWidgets.QApplication(sys.argv)
argv = QtWidgets.QApplication.arguments()
if len(argv) < 2:
filename = '~/emc/nc_files/3D_Chips.pdf'
else:
filename = argv[-1]
view = pdf_view(filename)
view.show()
sys.exit(app.exec())
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,71 @@
Converting vismach to qt_vimach:
The code lines may look a little different in
each case, but the premise is the same.
#######################################################
Qt uses different imported libraries
#######################################################
change:
from vismach import *
to:
from qtvcp.lib.qt_vismach.qt_vismach import *
#######################################################
Invoking script directly from python3 requires changes.
#######################################################
change:
main(model, tooltip, work, size=1500,lat=-65, lon=45)
to:
if __name__ == '__main__':
main(model, tooltip, work, size=1500,lat=-65, lon=45)
####################################################################
Invoking the script from Qtvcp requires a window object to be added.
#####################################################################
Add: (usually just above 'if __name__ == '__main__':')
# we want to embed with qtvcp so build a window to display
# the model
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.glWidget = GLWidget()
v = self.glWidget
v.set_latitudelimits(-180, 180)
# remove HUD cde if no HUD
v.hud = myhud
# HUD needs to know where to draw
v.hud.app = v
world = Capture()
v.model = Collection([model, world])
size = 600
v.distance = size * 3
v.near = size * 0.01
v.far = size * 10.0
v.tool2view = tooltip
v.world2view = world
v.work2view = work
mainLayout = QHBoxLayout()
mainLayout.addWidget(self.glWidget)
self.setLayout(mainLayout)
#################################################################
might also want to look at removing the component pins and read
HAL pins directly. Nice not to have to connect pins for the model
to work.
##################################################################

View File

@@ -0,0 +1,223 @@
#!/usr/bin/python3
#
# 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.
# graphic model of a Unimate Puma 560
# according to the dimensions from: http://www.juve.ro/blog/puma/
# the obj files can be downloaded there, and may be included in emc2 later
import os
from qtvcp.lib.qt_vismach.qt_vismach import *
import hal
# object ('fanuc_200f_obj') folder needs to be in same folder as this file
BASEPATH = os.path.join(os.path.dirname(__file__), 'fanuc_200f_obj')
c = hal.component("fanuc_200f")
c.newpin("joint1", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("joint2", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("joint3", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("joint4", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("joint5", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("joint6", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("grip", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("plotclear", hal.HAL_BIT, hal.HAL_IN)
c.ready()
# add a XYZ cross for debug
#floor = Collection([
# Box(-100,-100,-0.1,100,100,0),
# Box(-10,-0.1,-10,10,0,10),
# Box(-0.1,-10,-10,0,10,10),
## Color([0,1,0,1],[Box(-10,-10,9.9,10,10,10)]),
# Color([1,0,0,1],[Box(19.9,-10,-10,20,10,10)])])
# units are inches
floor = Collection([Box(-100,-100,-3,100,100,0)])
floor = Color([.3,.3,.3,0],[floor])
work = Capture()
#tool goes here.. maybe later
tool = Capture()
# "tooltip" for backplot will be the tip of the tool, for now link7
tooltip = Capture()
tool = Collection([tooltip, tool])
# link description
# link2 .. link7 - the 6 moving parts of the robot, numbered form base to end effector
# link7
# link6
# link5: wrist
# link4: arm, origin is in the joint3 location
# link3: shoulder
# link2
# link1: stationary base
try: # Expect files in working directory
link7 = AsciiOBJ(filename= os.path.join(BASEPATH,"r08_j6.obj"))
link6 = AsciiOBJ(filename= os.path.join(BASEPATH,"r08_j5.obj"))
link5 = AsciiOBJ(filename= os.path.join(BASEPATH,"r08_j4.obj"))
link4 = AsciiOBJ(filename= os.path.join(BASEPATH,"r08_j3.obj"))
link3 = AsciiOBJ(filename= os.path.join(BASEPATH,"r08_j2.obj"))
link2 = AsciiOBJ(filename= os.path.join(BASEPATH,"r08_j1.obj"))
link1 = AsciiOBJ(filename= os.path.join(BASEPATH,"r08_base.obj"))
except Exception as detail:
print(detail)
raise SystemExit("r2000ia-200f requires files: r08_j[1-6].obj, r08_base.obj")
#move link7 to 0 pos. so, that tooltip matches
link7 = Color([0.1,0.1,0.1,1],[link7])
link7 = Translate([link7],-71.1417,-77.5590,-.0058)
link7 = Rotate([link7],90,0,1,0)
link7 = Rotate([link7],180,1,0,0)
link7 = Collection([link7, tool])
link7 = Rotate([link7],-180,1,0,0)
link7 = HalRotate([link7],c,"joint6",1,0,0,-1)
link7 = Rotate([link7],-90,0,1,0)
link7 = Translate([link7],10.2362,0,0)
# rotate and translate it so that the joint 6 is in origin
link6 = Color([1,1,0,1],[link6])
link6 = Translate([link6],-62.6772,-77.5590,-.0058) #note: 1.8 + 0.4 = 2.2 - in the drawing distance from join5 to end effector
link6 = Rotate([link6],90,1,0,0)
# mount link7 on it
link6 = Collection([link7, link6])
#translate it back so joint 5 rotation in origin
#link6 = Translate([link6],0,0,1.8)
#apply HAL DOF
#link6 = Rotate([link6],180,0,1,0)
link6 = HalRotate([link6],c,"joint5",1,0,1,0)
link5 = Color([1,1,0,1],[link5])
#translate it so joint 5 rotation in origin
link5 = Translate([link5],-60.9720,-77.5247,-.006)
link5 = Rotate([link5],90,1,0,0)
# assemble
link5 = Collection([link6, link5])
# translate back to joint4 in origin
#link5 = Translate([link5],0,0,2.8)
#apply HAL DOF
link5 = HalRotate([link5],c,"joint4",1,-1,0,0)
link5 = Translate([link5],43.7008,0,8.85827)
# need to rotate it, and translate it so that joint 4 is in origin
#link4 = Rotate([link4],-90,0,1,0)
#link4 = Rotate([link4],90,0,0,1)
link4 = Color([1,1,0,1],[link4])
link4 = Translate([link4],-10.5783,-68.6664, -.006) # note: 14.25 + 2.8 = 17.05 - distance between j3 and j5
link4 = Rotate([link4],90,1,0,0)
#assemble
link4 = Collection([link5, link4])
# move back to joint3 in origin
link4 = Rotate([link4],-2.390,0,1,0)
link4 = HalRotate([link4],c,"joint3",1,0,-1,0)
#link4 = Rotate([link4],-2.390,0,1,0)
link4 = Translate([link4],-1.7052,0,42.2884)
# rotate,translate with joint 3 in origin
link3 = Color([1,1,0,1],[link3])
link3 = Translate([link3],-12.2835,-26.3780,0)
link3 = Rotate([link3],90,1,0,0)
#link3 = Rotate([link3], 180,0,0,1)
#link3 = Rotate([link3], 180,1,0,0)
#assemble
link3 = Collection([link4, link3])
#move back to j2 in Origin
#link3 = Translate([link3],0,0,17)
#and rotate according to kinematics
#link3 = Rotate([link3],90,1,0,0)
link3 = Rotate([link3],90,0,1,0)
#link3 = Rotate([link3],180,0,1,0)
link3 = Rotate([link3],2.309,0,1,0)
link3 = HalRotate([link3],c,"joint2",1,0,-1,0)
#link3 = Rotate([link3],-180,0,1,0)
link3 = Translate([link3],12.2835,0,26.3780)
link2 = Color([1,1,0,1],[link2])
link2 = Rotate([link2], 90,1,0,0)
link2 = Collection([link3, link2])
#link2 = Rotate([link2], 90,0,0,1)
#link2 = Translate([link2], 11.2,0,0) #note: 11.2 = 4 + 7.2 (4 = distance from j1 to link2 side, 7.2 distance from j1 to j2)
#link2 = Translate([link2],-7.2,0,3) # 3 = from j2 to j1 in Z
#rotate so X is in X direction
#link2 = Rotate([link2], -90,0,0,1)
link2 = HalRotate([link2],c,"joint1",1,0,0,1)
#move link2 up
#link2 = Translate([link2], 0,0,23.45) #note: 23.45 = 26.45(drawing) - 3 (from j2 to J1 in Z)
link1 = Color([0.2,0.2,0.2,1],[link1])
link1 = Rotate([link1], 90,1,0,0)
# stationary base
puma = Collection([link2, link1])
# show a title in the HUD
myhud = Hud()
myhud.show("Fanuc R-2000iA 200F")
model = Collection([tooltip, puma, floor, work])
# we want to embed with qtvcp so build a window to display
# the model
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.glWidget = GLWidget()
v = self.glWidget
v.set_latitudelimits(-180, 180)
v.hud = myhud
# HUD needs to know where to draw
v.hud.app = v
world = Capture()
v.model = Collection([model, world])
size = 75
v.distance = size * 3
v.near = size * 0.01
v.far = size * 10.0
v.tool2view = tooltip
v.world2view = world
v.work2view = work
mainLayout = QHBoxLayout()
mainLayout.setContentsMargins(0,0,0,0)
mainLayout.addWidget(self.glWidget)
self.setLayout(mainLayout)
# need to explicitly kill the HAL component
def cleanup(self):
c.exit()
# but it you call this directly it should work too
# It just makes a qtvcp window that is defined in qt_vismach.py
# parameter list:
# final model name must include all parts you want to use
# tooltip (special for tool tip inclusion)
# work (special for work part inclusion)
# size of screen (bigger means more zoomed out to show more of machine)
# hud None if no hud
# last 2 is where view point source is.
if __name__ == '__main__':
main(model, tooltip, work, size=75, hud=myhud, lat=-75, lon=215)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,168 @@
#!/usr/bin/env python3
# Copyright 2007 Chris Radek
# Derived from a work by John Kasunich and Jeff Epler
#
# 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.
# Note: items like pivot_len can be set at invocation, example:
# 5axisgui pivot_len=300
from qtvcp.lib.qt_vismach.qt_vismach import *
import hal
import math
import sys
pivot_len = 250 # to agree with default in 5axiskins.c
za = 50
zb = 100
# give endpoint Z values and radii
# resulting cylinder is on the Z axis
class HalToolCylinder(CylinderZ):
def __init__(self, comp, *args):
CylinderZ.__init__(self, *args)
self.comp = comp
def coords(self):
r = 20 # default if hal pin not set
if (c.tool_diam > 0): r=c.tool_diam/2
return -self.comp.tool_length, r, 0, r
c = hal.component("5axisgui")
c.newpin("jx", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("jy", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("jz", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("jb", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("jc", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("tool_length", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("tool_diam", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("pivot_len", hal.HAL_FLOAT, hal.HAL_OUT)
c["pivot_len"] = pivot_len
c.ready()
tooltip = Capture()
tool = Collection([HalTranslate([tooltip], c, "tool_length", 0,0,-1),
HalToolCylinder(c),
CylinderZ(pivot_len-(zb+za), 100, 0.0, 50),
Box(-100,-100,pivot_len-(zb+za),
100, 100,pivot_len-zb),
Box( -50, 25,pivot_len-zb,
50, 100,pivot_len)
])
tool = Translate([tool], 0, 0, -pivot_len)
tool = Collection([tool,
CylinderY(-100,75, -10,75),
CylinderY(-50,60,50,60),
])
tool = HalRotate([tool],c,"jb",1,0,-1,0)
wrist = Collection([tool,
CylinderY(100,75, 10,75),
Box(-50,-100,0, 50,-25,100),
Box(-100,-100,100, 100,100,150),
CylinderZ(150,75, 200, 75)
])
wrist = HalRotate([wrist],c,"jc",1,0,0,1)
ram = Collection([wrist,
Box(-100,-100,200, 100,100,900),
])
ram = Translate([ram], 0,0,150)
ram = HalTranslate([ram],c,"jz",0,0,1)
ram = Collection([ram,
Box(-100,100,350, 100,200,550)
])
ram = HalTranslate([ram],c,"jx",1,0,0)
ram = Collection([ram,
Box(-800,200,350, 800,400,550),
Box(-1000,200,-900, -800,400,550),
Box(800,200,-900, 1000,400,550)
])
ram = HalTranslate([ram],c,"jy",0,1,0)
ram = Collection([ram,
Box(-1000,1000,-1000, -800, -1000,-900),
Box(800,1000,-1000, 1000,-1000,-900)
])
work = Capture()
table = Collection([
work,
Box(-500,-500,-400, 500,500,-450)
])
model = Collection([ram, table])
# show a title to prove the HUD
myhud = Hud()
myhud.show("5 Axis Gantry")
# we want to embed with qtvcp so build a window to display
# the model
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.glWidget = GLWidget()
v = self.glWidget
v.set_latitudelimits(-180, 180)
v.hud = myhud
# HUD needs to know where to draw
v.hud.app = v
world = Capture()
v.model = Collection([model, world])
size = 600
v.distance = size * 3
v.near = size * 0.01
v.far = size * 10.0
v.tool2view = tooltip
v.world2view = world
v.work2view = work
mainLayout = QHBoxLayout()
mainLayout.setContentsMargins(0,0,0,0)
mainLayout.addWidget(self.glWidget)
self.setLayout(mainLayout)
# need to explicitly kill the HAL component
def cleanup(self):
c.exit()
# but it you call this directly it should work too
# It just makes a qtvcp5 window that is defined in qt_vismach.py
# parameter list:
# final model name must include all parts you want to use
# tooltip (special for tool tip inclusuion)
# work (special for work part inclusion)
# size of screen (bigger means more zoomed out to show more of machine)
# hud None if no hud
# last 2 is where view point source is.
if __name__ == '__main__':
main(model, tooltip, work, hud=myhud, size=1500,lat=-65, lon=45)

View File

@@ -0,0 +1,280 @@
#!/usr/bin/env python3
# Rolf Redford, Nov 2018
# modded for qtvcp Chris Morley 2020
from qtvcp.lib.qt_vismach.qt_vismach import *
from qtvcp.core import Status
STATUS = Status()
#---------------------------------------------------------------------------------------------------------------------------------- # Starting and defining
# model is built in metric
# if using a imperial config need to scale movement
METRIC = 1
IMPERIAL = 25.4
MODEL_SCALING = IMPERIAL
# -----------------------------------------------------------------------------------------------------------
# Concept of machine design
# The model follows logical tree design - picture the tree, with branch and smaller branches off it
# if you move the larger branch, smaller branches will move with it, but if you move smaller branch larger will not.
#
# Machine design follows that conceptal design, so for example if you move X, it can move on its own, but if you move Y,
# it will also move X assembly, as it is attached to Y assembly.
# so for this machine, tree looks like this:
# model
# |
# |---frame
# | |
# | |---base
# | |
# | |---column
# | |
# | |---top
# |
# |
# |---yassembly
# | |
# | |
# | |---xassembly
# | | |
# | | |
# | | |---xbase
# | | |
# | | |---work
# | |
# | |
# | |---ybase
# |
# |
# |---zassembly
# |
# |
# |---zframe
# | |
# | |---zbody
# | |
# | |---spindle
# |
# |
# |---toolassembly
# |
# |---cat30
# |
# |---tool
# |
# |---tooltip
# |
# |---(tool cylinder function)
# As you can see, lowest parts must exist first before it can be grouped with others into assembly.
# So you build upwards from lowest point in tree and assembly them together.
# Same is applicable for any design of machine. Look at machine arm example and you will see that it starts
# with tip and adds to larger part of arm then it finally groups with base.
# -----------------------------------------------------------------------------------------------------------
# Starting with fixed frame
# start creating base itself, floor and column for z. box is centered on 0,0,0
base = BoxCentered(200, 560, 20)
# translate it so top of base is at zero
base = Translate([base], 0, 0, -10)
# column, attached to base on side.
# Box() accepts extents
# ie -100 to 100 is 200 wide, and rightmost is at -100 on coord.
# Box(x rightmost, y futherest, z lowest, x leftmost, y nearest, z highest)
column = Box(-60, -260, 0, 60, -200, 400)
# add block on top
# not really needed, but I like how it looks with it.
# bare column looks little bit strange for some reason.
top = Box(-80, -280, 400, 80, -160, 440)
# now fuse it into "frame"
frame = Collection([base, column, top])
# color it grayish
frame = Color([.8, .8, .8, 1], [frame])
# ----------------------------------------------------------------------------------------------------------------------------------
# Moving parts section
# Start with X, Y then finally Z with tool and spindle.
# X table addition
xbase = BoxCentered(1000, 200, 30)
# let's color it blue
xbase = Color([0, 0, 1, 1], [xbase])
# Move table so top is at zero for now,
# so work (default 0,0,0) is on top of table.
xbase = Translate([xbase], 0, 0, -15)
# now create work which would be defined by Linuxcnc.
# I suspect we would need to define shape but not enough is known.
# for now just create an point that would be bottom center of stock.
work = Capture()
# group work and xbase together so they move together.
xassembly = Collection([xbase, work])
# work is now defined and grouped, and default at 0,0,0, or
# currently on top of x part table.
# so we move table group upwards, taking work with it.
xassembly = Translate([xassembly], 0, 0, 35)
# Must define part motion before it becomes part of collection.
# Must have arguments, object itself, c (defined above), then finally scale from the pin to x y z.
# since this moves solely on X axis, only x is 1, rest is zero.
# you could use fractions for say axis that moves in compound like arm for example
# but this machine is very simple, so all axis will be purely full on axis and zero on other axis.
xassembly = HalTranslate([xassembly], None, "joint.0.pos-fb", MODEL_SCALING, 0, 0)
# Y assembly creation
ybase = BoxCentered(200, 200, 10)
# colorize it green so we can see it separate from frame.
ybase = Color([0, 1, 0, 1], [ybase])
# don't define translation for this one, as y also moves X table.
# translating this would move itself alone. You want it to move X parts also.
# X table is moved by Y base, so we have to make X child of Y.
# now define collection of ybase and xassembly.
yassembly = Collection([ybase, xassembly])
# define its motion first before translate.
yassembly = HalTranslate([yassembly], None, "joint.1.pos-fb", 0, MODEL_SCALING, 0)
# Now that translate is locked with part,
# move it upwards so its on frame base.
yassembly = Translate([yassembly], 0, 0, 5)
# spindle head
# define small cylinder where tool will be attached to.
# It is shallow, basically exposed end of "cat30" toolholder.
# let's pretend machine uses cat30.
cat30 = CylinderZ(0, 30, 20, 40) # cone wider top smaller bottom
# color it red, as in danger, tool!
cat30 = Color([1, 0, 0, 1], [cat30])
# Define tool and grab such model information from linuxcnc
# tooltip is initially in vismach "world" 0,0,0.
# what it does is place where line drawing is in world, so
# you can see where machine think tip of tool is.
# first capture it, so we can use it and move it to where
# defined end of tool is.
tooltip = Capture()
# Now that we have tooltip, let's attach it to cylinder function (see above)
# it creates cylinder then translates tooltip to end of it.
tool = Collection([
Translate([HalTranslate([tooltip], None, "motion.tooloffset.z", 0, 0, -MODEL_SCALING)], 0, 0, 0),
Color([1, .5, .5, .5], [HalToolCylinder()])
])
# Since tool is defined, lets attach it to cat30
# Group cat30 and tooltip
toolassembly = Collection([cat30, tool])
# now that tool is properly attached, we can move it
# and tool will "move" with it now.
# BUT we need to build rest of head in such way that TOP of head is defined as Z zero.
# Move it so it attaches to bottom of spindle body.
toolassembly = Translate([toolassembly], 0, 0, -120)
# Start building Z assembly head, including spindle and support
# top is at zero as I want top to be defined as Z home top.
spindle = CylinderZ(-100, 60, 0, 60) # top is at zero
# define rest of head using Box
zbody = Box(-30, -200, 0, 30, 0, -100)
# fuse into z assembly
zframe = Collection([zbody, spindle])
# color it yellow
zframe = Color([1, 1, 0, 1], [zframe])
# Now that all parts are created, let's group it and finally make Z motion
zassembly = Collection([zframe, toolassembly])
# define Z motion
zassembly = HalTranslate([zassembly], None, "joint.2.pos-fb", 0, 0, MODEL_SCALING)
# Now that motion is defined,
# we can now move it to Z home position.
zassembly = Translate([zassembly], 0, 0, 400)
# show a title and DRO to prove the HUD
myhud = HalHud()
myhud.display_on_right()
myhud.set_background_color(0,.1,.2,0)
myhud.show_top("Mill_XYZ")
myhud.show_top("------------")
myhud.add_pin('axis-x: ',"{:10.4f}","axis.x.pos-cmd")
myhud.add_pin('axis-y: ',"{:10.4f}","axis.y.pos-cmd")
myhud.add_pin('axis-z: ',"{:10.4f}","axis.z.pos-cmd")
myhud.show("-------------")
# ------------------------------------------------------------------------------------
# Getting it all together and finishing model
# Assembly everything into single model.
# xassembly is already included into yassembly so don't need to include it.
model = Collection([frame, yassembly, zassembly])
# build axes origin markers
X = CylinderX(-500,1,500,1)
X = Color([1, 0, 0, 1], [X])
Y = CylinderY(-500,1,500,1)
Y = Color([0, 1, 0, 1], [Y])
Z = CylinderZ(-100,1,100,1)
Z = Color([0, 0, 1, 1], [Z])
origin = Collection([X,Y,Z])
# we want to embed with qtvcp so build a window to display
# the model
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.glWidget = GLWidget()
v = self.glWidget
v.set_latitudelimits(-180, 180)
v.hud = myhud
# HUD needs to know where to draw
v.hud.app = v
world = Capture()
# uncomment and re comment the nect line to se origin markers
#v.model = Collection([origin, model, world])
v.model = Collection([model, world])
size = 600
v.distance = size * 3
v.near = size * 0.01
v.far = size * 10.0
v.tool2view = tooltip
v.world2view = world
v.work2view = work
mainLayout = QHBoxLayout()
mainLayout.setContentsMargins(0,0,0,0)
mainLayout.addWidget(self.glWidget)
self.setLayout(mainLayout)
STATUS.connect('motion-type-changed', lambda w, data: v.choosePlotColor(data))
#v.setColorsAttribute('FEED',(0,1,0))
#print(v.colors)
# but it you call this directly it should work too
# It just makes a qtvcp5 window that is defined in qt_vismach.py
# parameter list:
# final model name must include all parts you want to use
# tooltip (special for tool tip inclusion)
# work (special for work part inclusion)
# size of screen (bigger means more zoomed out to show more of machine)
# hud None if no hud
# last 2 is where view point source is.
if __name__ == '__main__':
main(model, tooltip, work, size=600, hud=myhud, lat=-75, lon=215)

View File

@@ -0,0 +1,293 @@
#!/usr/bin/env python3
# based on earlier work by Rolf Redford, Nov 2018
#import libraries
from qtvcp.lib.qt_vismach.qt_vismach import *
import hal
import math
import sys
#----------------------------------------------------------------------------------------------------------------------------------
# Starting and defining
# Here is where we define pins that linuxcnc will send
# data to, in order to make movements.
# We will need 5 pins, 3 for motion and 2 for tool stats.
# tooldiameter isn't really used but if you are using 2.8 you can make couple changes
# in this file, and uncomment last line in HAL file.
# add joints. Mill has 3.
c = hal.component("millturngui")
# follow ZYX directly
#c.newpin("jointX", hal.HAL_FLOAT, hal.HAL_IN)
#c.newpin("jointY", hal.HAL_FLOAT, hal.HAL_IN)
#c.newpin("jointZ", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("jointA", hal.HAL_FLOAT, hal.HAL_IN)
# kinematics pins
c.newpin("millkins", hal.HAL_BIT, hal.HAL_IN)
# tool length and diameter pins?
c.newpin("toollength", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("tooldiameter", hal.HAL_FLOAT, hal.HAL_IN)
c.newpin("tool-x-offset", hal.HAL_FLOAT, hal.HAL_IN)
# tells loadusr pins is ready
c.ready()
# Used for tool cylinder
# it will be updated in shape and length by function below.
#toolshape = CylinderZ(0)
toolshape = TriangleXZ(0)
toolshape = Color([1, 1, 0, 1],[toolshape])
# updates tool cylinder shape.
class HalToolCylinder(CylinderZ):
def __init__(self, comp, *args):
# get machine access so it can
# change itself as it runs
# specifically tool cylinder in this case.
CylinderZ.__init__(self, *args)
self.comp = c
def coords(self):
#print(self.comp["millkins"])
if self.comp["millkins"] :
rad = ( self.comp["tooldiameter"] )
rad = rad / 2 # change to rad
rad2 = rad
else:
rad = self.comp["tool-x-offset"]
rad2 = 0
# this instantly updates tool model but tooltip doesn't move till -
# tooltip, the drawing point will NOT move till g43h(tool number) is called, however.
# Tool will "crash" if h and tool length does not match.
try:
leng = hal.get_value('motion.tooloffset.z') * self.MODEL_SCALING
except:
leng = 0
# Update tool length when g43h(toolnumber) is called, otherwise stays at 0 or previous size.
# commented out as I prefer machine to show actual tool size right away.
#leng = self.comp["toollength"]
return (-leng, rad, 0, rad2)
#----------------------------------------------------------------------------------------------------------------------------------
# Starting with fixed frame
# start creating base itself, floor and column for z. box is centered on 0,0,0
base = BoxCentered(200, 560, 20)
# translate it so top of base is at zero
base = Translate([base], 0,0,-10)
# column, attached to base on side.
# Box() accepts extents
# ie -100 to 100 is 200 wide, and rightmost is at -100 on coord.
# Box(x rightmost, y futherest, z lowest, x leftmost, y nearest, z highest)
column = Box( -60, -260, 0, 60, -200, 400)
# add block on top
# not really needed, but I like how it looks with it.
# bare column looks little bit strange for some reason.
top = Box(-80,-280,400, 80,-160,440)
# now fuse it into "frame"
frame = Collection([base, column, top])
# color it grayish
frame = Color([.8,.8,.8,1],[frame])
#----------------------------------------------------------------------------------------------------------------------------------
# Moving parts section
# Start with X, Y then finally Z with tool and spindle.
# X table addition
xbase = BoxCentered(1000,200,30)
# let's color it blue
xbase = Color([0,0,1,1], [xbase])
# Move table so top is at zero for now,
# so work (default 0,0,0) is on top of table.
xbase = Translate([xbase], 0,0, -15)
# A-axis/spindle assembly creation
abase = BoxCentered(200, 100, 140)
# colorize it green so we can see it separate from frame.
abase = Color([0,1,0,1], [abase])
# translate the base so it sits on the left side of the table
abase = Translate([abase],400,0,50)
# attach base to table
xspindleassembly1 = Collection([xbase, abase ])
# create chuck
chuck = CylinderX(0,30,-10,30)
# color it red, as in danger!
chuck = Color([1,0,0,1], [chuck])
# create chuck clamp1
chuck_clamp1 = BoxCentered(30, 30, 10)
# translate
chuck_clamp1 = Translate([chuck_clamp1],0,-20,0)
# create chuck clamp2
chuck_clamp2 = BoxCentered(30, 30, 10)
# translate
chuck_clamp2 = Translate([chuck_clamp2],0,-20,0)
chuck_clamp2 = Rotate([chuck_clamp2],120,1,0,0)
# create chuck clamp3
chuck_clamp3 = BoxCentered(30, 30, 10)
# translate
chuck_clamp3 = Translate([chuck_clamp3],0,-20,0)
chuck_clamp3 = Rotate([chuck_clamp3],-120,1,0,0)
# attach chuck clamps to chuck
chuckassembly = Collection([chuck, chuck_clamp1, chuck_clamp2, chuck_clamp3])
chuckassembly = HalRotate([chuckassembly],c,"jointA",1,-1,0,0)
# translate the base so it sits on the left side of the table
chuckassembly = Translate([chuckassembly],300,0,80)
# attach spinle nose to spindle block
xspindleassembly = Collection([xspindleassembly1, chuckassembly])
# now create work which would be defined by Linuxcnc.
# I suspect we would need to define shape but not enough is known.
# for now just create an point that would be bottom center of stock.
work = Capture()
# group work and xbase together so they move together.
xassembly = Collection([xspindleassembly, work])
# work is now defined and grouped, and default at 0,0,0, or
# currently on top of x part table.
# so we move table group upwards, taking work with it.
xassembly = Translate([xassembly], 0,0, 35)
# Must define part motion before it becomes part of collection.
# Must have arguments, object itself, c (defined above), then finally scale from the pin to x y z.
# since this moves solely on X axis, only x is 1, rest is zero.
# you could use fractions for say axis that moves in compound like arm for example
# but this machine is very simple, so all axis will be purely full on axis and zero on other axis.
xassembly = HalTranslate([xassembly], None, "joint.0.pos-fb", 1, 0, 0)
# Y assembly creation
ybase = BoxCentered(200, 200, 10)
# colorize it green so we can see it separate from frame.
ybase = Color([0,1,0,1], [ybase])
# don't define translation for this one, as y also moves X table.
# translating this would move itself alone. You want it to move X parts also.
# X table is moved by Y base, so we have to make X child of Y.
# now define collection of ybase and xassembly.
yassembly = Collection([ybase, xassembly])
# define its motion first before translate.
yassembly = HalTranslate([yassembly], None, "joint.1.pos-fb", 0, 1, 0)
# Now that translate is locked with part,
# move it upwards so its on frame base.
yassembly = Translate([yassembly], 0,0,5)
# spindle head
# define small cylinder where tool will be attached to.
# It is shallow, basically exposed end of "cat30" toolholder.
# let's pretend machine uses cat30.
cat30 = CylinderZ(0, 30, 20, 40) # cone wider top smaller bottom
# color it red, as in danger, tool!
cat30 = Color([1,0,0,1], [cat30])
# Define tool and grab such model information from linuxcnc
# tooltip is initially in vismach "world" 0,0,0.
# what it does is place where line drawing is in world, so
# you can see where machine think tip of tool is.
# first capture it, so we can use it and move it to where
# defined end of tool is.
tooltip = Capture()
# Now that we have tooltip, let's attach it to cylinder function (see above)
# it creates cylinder then translates tooltip to end of it.
tool1 = HalTranslate([tooltip], c, "tool-x-offset", 1, 0, 0)
tool2 = HalTranslate([tool1], c, "toollength", 0, 0, -1)
#tool = Collection([tool2,HalToolCylinder(toolshape)])
tool = Collection([tool2,HalToolTriangle(toolshape)])
# Since tool is defined, lets attach it to cat30
# Group cat30 and tooltip
toolassembly = Collection([cat30, tool])
# now that tool is properly attached, we can move it
# and tool will "move" with it now.
# BUT we need to build rest of head in such way that TOP of head is defined as Z zero.
# Move it so it attaches to bottom of spindle body.
toolassembly = Translate([toolassembly],0,0,-120)
# Start building Z assembly head, including spindle and support
# top is at zero as I want top to be defined as Z home top.
spindle = CylinderZ(-100, 60, 0, 60) # top is at zero
# define rest of head using Box
zbody = Box(-30, -200, 0, 30, 0, -100)
# fuse into z assembly
zframe = Collection([zbody, spindle])
# color it yellow
zframe = Color([1,1,0,1], [zframe])
# Now that all parts are created, let's group it and finally make Z motion
zassembly = Collection([zframe, toolassembly])
# define Z motion
zassembly = HalTranslate([zassembly], None, "joint.2.pos-fb", 0, 0, 1)
# Now that motion is defined,
# we can now move it to Z home position.
zassembly = Translate([zassembly], 0,0, 400)
#----------------------------------------------------------------------------------------------------------------------------------
# Getting it all together and finishing model
# Assembly everything into single model.
# xassembly is already included into yassembly so don't need to include it.
model = Collection([frame, yassembly, zassembly])
# show a title to prove the HUD
myhud = Hud()
myhud.show("Millturn")
# we want to embed with qtvcp so build a window to display
# the model
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.glWidget = GLWidget()
v = self.glWidget
v.set_latitudelimits(-180, 180)
v.hud = myhud
# HUD needs to know where to draw
v.hud.app = v
world = Capture()
v.model = Collection([model, world])
size = 600
v.distance = size * 3
v.near = size * 0.01
v.far = size * 10.0
v.tool2view = tooltip
v.world2view = world
v.work2view = work
mainLayout = QHBoxLayout()
mainLayout.setContentsMargins(0,0,0,0)
mainLayout.addWidget(self.glWidget)
self.setLayout(mainLayout)
# need to explicitly kill the HAL component
def cleanup(self):
c.exit()
# but it you call this directly it should work too
# It just makes a qtvcp5 window that is defined in qt_vismach.py
# parameter list:
# final model name must include all parts you want to use
# tooltip (special for tool tip inclusuion)
# work (special for work part inclusion)
# size of screen (bigger means more zoomed out to show more of machine)
# hud None if no hud
# last 2 is where view point source is.
if __name__ == '__main__':
main(model, tooltip, work, size=600,hud=myhud, lat=-75, lon=170)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,472 @@
#!/usr/bin/env python3
import sys
from qtpy.QtCore import Signal, QPoint, QSize, Qt, QTimer
from qtpy.QtGui import QColor
from qtpy.QtWidgets import (QApplication, QHBoxLayout, QOpenGLWidget, QSlider,
QWidget)
import OpenGL.GL as GL
from OpenGL import GLU
from qtvcp.lib.qt_vismach.primitives import *
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.glWidget = GLWidget()
self.xSlider = self.createSlider()
self.ySlider = self.createSlider()
self.zSlider = self.createSlider()
self.zoomSlider = self.createSlider()
self.zoomSlider.setRange(1000, 5600)
self.zoomSlider.setPageStep(10)
self.zoomSlider.setTickInterval(1)
self.xSlider.valueChanged.connect(self.glWidget.setXRotation)
self.glWidget.xRotationChanged.connect(self.xSlider.setValue)
self.ySlider.valueChanged.connect(self.glWidget.setYRotation)
self.glWidget.yRotationChanged.connect(self.ySlider.setValue)
self.zSlider.valueChanged.connect(self.glWidget.setZRotation)
self.glWidget.zRotationChanged.connect(self.zSlider.setValue)
self.zoomSlider.valueChanged.connect(self.glWidget.setZoom)
self.glWidget.zoomChanged.connect(self.zoomSlider.setValue)
mainLayout = QHBoxLayout()
mainLayout.addWidget(self.glWidget)
mainLayout.addWidget(self.xSlider)
mainLayout.addWidget(self.ySlider)
mainLayout.addWidget(self.zSlider)
mainLayout.addWidget(self.zoomSlider)
self.setLayout(mainLayout)
self.xSlider.setValue(112 * 16)
self.ySlider.setValue(180 * 16)
self.zSlider.setValue(0 * 16)
self.zoomSlider.setValue(10)
self.setWindowTitle("Qt Vismach")
def createSlider(self):
slider = QSlider(Qt.Vertical)
slider.setRange(0, 360 * 16)
slider.setSingleStep(16)
slider.setPageStep(15 * 16)
slider.setTickInterval(15 * 16)
slider.setTickPosition(QSlider.TicksRight)
return slider
def setZoomRange(self, small, big):
self.zoomSlider.setRange(small, big)
class GLWidget(QOpenGLWidget):
xRotationChanged = Signal(int)
yRotationChanged = Signal(int)
zRotationChanged = Signal(int)
zoomChanged = Signal(int)
def __init__(self, parent=None):
super(GLWidget, self).__init__(parent)
self.model = None
self.xRot = 1700
self.yRot = 2850
self.zRot = 0
self.viewX = 0
self.viewY = 0
self.lastPos = QPoint()
self.r_back = self.g_back = self.b_back = 0
self.colors = {
'DEFAULT': (1.0, 1.0, 0.0),
'TRAVERSE': (0.30, 0.50, 0.50),
'FEED': (1.00, 1.00, 1.00),
'ARC': (1.00, 1.00, 1.00),
'TOOLCHANGE': (1.00, 1.00, 1.00),
'PROBE': (1.00, 1.00, 1.00),
'ROTARYINDEX': (1.00, 1.00, 1.00),
}
self.plotdata = []
self.plotColor = [1.0, 0.5, 0.5]
self.plotlen = 64000
# Where we are centering.
self.xcenter = 0.0
self.ycenter = 0.0
self.zcenter = 0.0
# Where the eye is
self.distance = 10.0
# Field of view in y direction
self.fovy = 30.0
# Position of clipping planes.
self.near = 0.1
self.far = 1000.0
# View settings
self.perspective = 0
self.lat = 0
self.minlat = -90
self.maxlat = 90
# does not show HUD by default
self.hud = Hud()
# self.hud.show("stuff")
# add a 100ms timer to poll linuxcnc stats
self.timer = QTimer()
self.timer.timeout.connect(self.update)
self.timer.start(50)
def choosePlotColor(self, data):
# by name
if isinstance(data, str):
if not data.upper() in self.colors:
return
color = self.colors[data.upper()]
self.plotColor = color
return
# by integer 0-6
elif isinstance(data, int):
for n,i in enumerate(self.colors):
if n == data:
color = self.colors[i]
self.plotColor = color
return
def setColorsAttribute(self,attr, color):
# by string
if isinstance(attr.upper(), str):
if not attr.upper() in self.colors:
return
self.colors[attr.upper()] = color
return
# by integer 0-6
elif isinstance(attr, int):
for n,i in enumerate(self.colors):
if n == attr:
self.colors[i] = color
return
def getOpenglInfo(self):
info = """
Vendor: {0}
Renderer: {1}
OpenGL Version: {2}
Shader Version: {3}
""".format(
GL.glGetString(GL.GL_VENDOR),
GL.glGetString(GL.GL_RENDERER),
GL.glGetString(GL.GL_VERSION),
GL.glGetString(GL.GL_SHADING_LANGUAGE_VERSION)
)
return info
def minimumSizeHint(self):
return QSize(50, 50)
def sizeHint(self):
return QSize(400, 400)
def winfo_width(self):
return self.geometry().width()
def winfo_height(self):
return self.geometry().height()
def setXRotation(self, angle):
angle = self.normalizeAngle(angle)
if angle != self.xRot:
self.xRot = angle
self.xRotationChanged.emit(angle)
self.update()
def setYRotation(self, angle):
angle = self.normalizeAngle(angle)
if angle != self.yRot:
self.yRot = angle
self.yRotationChanged.emit(angle)
self.update()
def setZRotation(self, angle):
angle = self.normalizeAngle(angle)
if angle != self.zRot:
self.zRot = angle
self.zRotationChanged.emit(angle)
self.update()
def setZoom(self, depth):
self.distance = depth
self.update()
def zoomin(self):
self.distance = self.distance / 1.2 - 20
if self.distance < self.near:
self.distance = self.near
self.update()
def zoomout(self):
self.distance = self.distance * 1.2 + 20
if self.distance > self.far:
self.distance = self.far
self.update()
def set_latitudelimits(self, minlat, maxlat):
"""Set the new "latitude" limits for rotations."""
if maxlat > 180:
return
if minlat < -180:
return
if maxlat <= minlat:
return
self.maxlat = maxlat
self.minlat = minlat
def initializeGL(self):
# basic_lighting
GL.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, (1, -1, .5, 0))
GL.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, (.2, .2, .2, 0))
GL.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, (.6, .6, .4, 0))
GL.glLightfv(GL.GL_LIGHT0 + 1, GL.GL_POSITION, (-1, -1, .5, 0))
GL.glLightfv(GL.GL_LIGHT0 + 1, GL.GL_AMBIENT, (.0, .0, .0, 0))
GL.glLightfv(GL.GL_LIGHT0 + 1, GL.GL_DIFFUSE, (.0, .0, .4, 0))
GL.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE, (1, 1, 1, 0))
GL.glDisable(GL.GL_CULL_FACE)
GL.glEnable(GL.GL_LIGHTING)
GL.glEnable(GL.GL_LIGHT0)
GL.glEnable(GL.GL_LIGHT0 + 1)
GL.glDepthFunc(GL.GL_LESS)
GL.glEnable(GL.GL_DEPTH_TEST)
GL.glMatrixMode(GL.GL_MODELVIEW)
GL.glLoadIdentity()
def paintGL(self):
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
GL.glLoadIdentity()
GL.glTranslated(0.0, 0.0, -10.0)
GL.glRotated(self.xRot / 16.0, 1.0, 0.0, 0.0)
GL.glRotated(self.yRot / 16.0, 0.0, 1.0, 0.0)
GL.glRotated(self.zRot / 16.0, 0.0, 0.0, 1.0)
# draw Objects
GL.glPushMatrix() # Protect our matrix
# set view size
w = self.winfo_width()
h = self.winfo_height()
GL.glViewport(0, 0, w, h)
# Clear the background and depth buffer.
GL.glClearColor(self.r_back, self.g_back, self.b_back, 0.)
GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glLoadIdentity()
GLU.gluPerspective(self.fovy, float(w) / float(h), self.near, self.far)
if 1:
# Now translate the scene origin away from the world origin
GL.glMatrixMode(GL.GL_MODELVIEW)
mat = GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX)
GL.glLoadIdentity()
GL.glTranslatef(-(self.xcenter + self.viewX), -(self.ycenter + self.viewY),
-(self.zcenter + self.distance))
GL.glMultMatrixd(mat)
else:
GLU.gluLookAt(self.xcenter, self.ycenter, self.zcenter + self.distance,
self.xcenter, self.ycenter, self.zcenter,
0., 1., 0.)
GL.glMatrixMode(GL.GL_MODELVIEW)
# Call objects redraw method.
self.drawObjects()
GL.glFlush() # Tidy up
GL.glPopMatrix() # Restore the matrix
def drawObjects(self, *args):
if self.winfo_width() == 1: return
if self.model is None: return
self.model.traverse()
# current coords: world
# the matrices tool2view, work2view, and world2view
# transform from tool/work/world coords to viewport coords
# if we want to draw in tool coords, we need to do
# "tool -> view -> world" (since the current frame is world)
# and if we want to draw in work coords, we need
# "work -> view -> world". For both, we need to invert
# the world2view matrix to do the second step
view2world = invert(self.world2view.t)
# likewise, for backplot, we want to transform the tooltip
# position from tool coords (where it is [0,0,0]) to work
# coords, so we need tool -> view -> work
# so lets also invert the work2view matrix
view2work = invert(self.work2view.t)
# since backplot lines only need vertices, not orientation,
# and the tooltip is at the origin, getting the tool coords
# is easy
tx, ty, tz = self.tool2view.t[3][:3]
# now we have to transform them to the work frame
wx = tx * view2work[0][0] + ty * view2work[1][0] + tz * view2work[2][0] + view2work[3][0]
wy = tx * view2work[0][1] + ty * view2work[1][1] + tz * view2work[2][1] + view2work[3][1]
wz = tx * view2work[0][2] + ty * view2work[1][2] + tz * view2work[2][2] + view2work[3][2]
# wx, wy, wz are the values to use for backplot
# so we save them in a buffer
if len(self.plotdata) == self.plotlen:
del self.plotdata[:self.plotlen // 10]
point = [wx, wy, wz]
# if tool position is different from last time, record plot position
if not self.plotdata or point != self.plotdata[-1][0]:
self.plotdata.append([point,self.plotColor])
# now lets draw something in the tool coordinate system
# GL.glPushMatrix()
# matrixes take effect in reverse order, so the next
# two lines do "tool -> view -> world"
# GL.glMultMatrixd(view2world)
# GL.glMultMatrixd(self.tool2view.t)
# do drawing here
# cylinder normally goes to +Z, we want it down
# GL.glTranslatef(0,0,-60)
# GLU.gluCylinder(self.q1, 20, 20, 60, 32, 16)
# back to world coords
# GL.glPopMatrix()
# we can also draw in the work coord system
GL.glPushMatrix()
# "work -> view -> world"
GL.glMultMatrixd(view2world)
GL.glMultMatrixd(self.work2view.t)
# now we can draw in work coords, and whatever we draw
# will move with the work, (if the work is attached to
# a table or indexer or something that moves with
# respect to the world
# just a test object, sitting on the table
# GLU.gluCylinder(self.q2, 40, 20, 60, 32, 16)
# draw head up display
if (hasattr(self.hud, "draw")):
self.hud.draw()
# draw backplot
GL.glDisable(GL.GL_LIGHTING)
GL.glLineWidth(2)
GL.glBegin(GL.GL_LINE_STRIP)
for p,c in self.plotdata:
GL.glColor3f(*c)
GL.glVertex3f(*p)
GL.glEnd()
GL.glEnable(GL.GL_LIGHTING)
GL.glColor3f(1, 1, 1)
GL.glLineWidth(1)
GL.glDisable(GL.GL_BLEND)
GL.glDepthFunc(GL.GL_LESS)
# back to world again
GL.glPopMatrix()
def plotclear(self):
del self.plotdata[:self.plotlen]
def resizeGL(self, width, height):
side = min(width, height)
if side < 0:
return
GL.glViewport((width - side) // 2, (height - side) // 2, side,
side)
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glLoadIdentity()
GL.glOrtho(-0.5, +0.5, +0.5, -0.5, 4.0, 15.0)
GL.glMatrixMode(GL.GL_MODELVIEW)
def mousePressEvent(self, event):
self.lastPos = event.pos()
def mouseMoveEvent(self, event):
dx = event.x() - self.lastPos.x()
dy = event.y() - self.lastPos.y()
if event.buttons() & Qt.LeftButton:
scale = max(0.2, (self.distance ** 0.7) * 0.01)
self.viewX -= dx * scale
self.viewY += dy * scale
elif event.buttons() & Qt.RightButton:
self.setXRotation(self.xRot + 8 * dy)
self.setZRotation(self.zRot + 8 * dx)
else:
self.setXRotation(self.xRot + 8 * dy)
self.setYRotation(self.yRot - 8 * dx)
self.lastPos = event.pos()
def mouseDoubleClickEvent(self, event):
if event.button() & Qt.RightButton:
self.plotclear()
def wheelEvent(self, event):
# Use the mouse wheel to zoom in/out
a = event.angleDelta().y() / 200
if a < 0:
self.zoomout()
else:
self.zoomin()
event.accept()
def normalizeAngle(self, angle):
while angle < 0:
angle += 360 * 16
while angle > 360 * 16:
angle -= 360 * 16
return angle
def main(model, tool, work, size=10, hud=None, rotation_vectors=None, lat=0, lon=0):
app = QApplication(sys.argv)
window = Window()
t = window.glWidget
t.set_latitudelimits(-180, 180)
if not hud is None:
t.hud = hud
t.hud.app = t #HUD needs to know where to draw
world = Capture()
t.model = Collection([model, world])
t.distance = size * 3
t.near = size * 0.01
t.far = size * 10.0
t.tool2view = tool
t.world2view = world
t.work2view = work
window.setZoomRange(int(t.near),int(t.far))
window.show()
sys.exit(app.exec())
if __name__ == '__main__':
print('This is a library file - it needs to be imported')

View File

@@ -0,0 +1,224 @@
#!/usr/bin/env python3
# Copyright 2007 John Kasunich and Jeff Epler
#
# 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.
from qtvcp.lib.qt_vismach.qt_vismach import *
import hal
import math
# no component made here - reads the pins directly
comp = None
# set measurement system
METRIC = 1
IMPERIAL = 25.4
MODEL_SCALING = METRIC
# parameters that define the geometry see scarakins.c for definitions these
# numbers match the defaults there, and will need to be changed or specified on
# the commandline if you are not using the defaults.
#setp scarakins.D1 400.0
#setp scarakins.D2 350.0
#setp scarakins.D3 -75.0
#setp scarakins.D4 350.0
##setp scarakins.D5 200.0
#setp scarakins.D6 0.0
d1 = 490.0
d2 = 340.0
d3 = 50.0
d4 = 250.0
d5 = 50.0
d6 = 50.0
j3min = 40.0
j3max = 270.0
# calculate a bunch of other dimensions that are used
# to scale the model of the machine
# most of these scale factors are arbitrary, to give
# a nicely proportioned machine. If you know specifics
# for the machine you are modeling, feel free to change
# these numbers
tool_len = math.sqrt(d5*d5+d6*d6) # don't change
tool_dia = tool_len / 6.0
# diameters of the arms
l1_dia = d2 / 5.0
l2_dia = d4 / 5.0
l3_dia = l2_dia * 0.8
# diameters of the "lumps" at the joints
j0_dia = l1_dia * 1.5
j1_dia = max(l1_dia * 1.25, l2_dia * 1.5)
j2_dia = l2_dia * 1.25
# other dims
j0_hi = l1_dia * 1.2
j1_hi1 = l1_dia * 1.1
j1_hi2 = l2_dia * 1.2
j2_hi = l2_dia * 1.3
# don't change these
tool_angle = math.degrees(math.atan2(d6,d5))
tool_radius = tool_dia / 2.0
l1_rad = l1_dia / 2.0
l2_rad = l2_dia / 2.0
l3_len = j3max + j2_hi * 0.7
l3_rad = l3_dia / 2.0
j0_hi = j0_hi / 2.0
j0_rad = j0_dia / 2.0
j1_hi1 = j1_hi1 / 2.0
j1_hi2 = j1_hi2 / 2.0
j1_rad = j1_dia / 2.0
j2_hi = j2_hi / 2.0
j2_rad = j2_dia / 2.0
size = max(d1+d3+l3_len,d2+d4+d6)
# tool - cylinder with a point, and a ball to hide the blunt back end
# the origin starts out at the tool tip, and we want to capture this
# "tooltip" coordinate system
tooltip = Capture()
tool = Collection([
tooltip,
Sphere(0.0, 0.0, tool_len, tool_dia),
CylinderZ(tool_len, tool_radius, tool_dia, tool_radius),
CylinderZ(tool_dia, tool_radius, 0.0, 0.0)])
# translate so origin is at base of tool, not the tip
tool = Translate([tool],0.0,0.0,-tool_len)
# the tool might not be pointing straight down
tool = Rotate([tool],tool_angle,0.0,-1.0,0.0)
# make joint 3 rotate
tool = HalRotate([tool],comp,"joint.3.pos-fb", 1, 0, 0, 1)
link3 = CylinderZ(0.0, l3_rad, l3_len, l3_rad)
# attach tool to end
link3 = Collection([tool,link3])
# make joint 2 go up and down
link3 = HalTranslate([link3], comp, "joint.2.pos-fb", 0, 0, -MODEL_SCALING)
# outer arm
# start with link3 and the cylinder it slides in
link2 = Collection([
link3,
CylinderZ(-j2_hi, j2_rad, j2_hi, j2_rad)])
# move to end of arm
link2 = Translate([link2], d4, 0.0, 0.0)
# add the arm itself
link2 = Collection([
link2,
CylinderX(d4, l2_rad, 1.5*j1_rad, l2_rad)])
# the joint gets interesting, because link2 can be above or below link1
if d3 > 0:
flip = 1
else:
flip = -1
# add the joint
link2 = Collection([
link2,
Box(1.5*j1_rad, -0.9*j1_rad, -j1_hi2, 1.15*j1_rad, 0.9*j1_rad, j1_hi2),
Box(1.15*j1_rad, -0.9*j1_rad, -0.4*d3, 0.0, 0.9*j1_rad, flip*j1_hi2),
CylinderZ(-0.4*d3, j1_rad, flip*1.2*j1_hi2, j1_rad)])
# make the joint work
link2 = HalRotate([link2],comp,"joint.1.pos-fb", 1, 0, 0, 1)
# inner arm
# the outer arm and the joint
link1 = Collection([
Translate([link2],0.0,0.0,d3),
Box(-1.5*j1_rad, -0.9*j1_rad, -j1_hi1, -1.15*j1_rad, 0.9*j1_rad, j1_hi1),
Box(-1.15*j1_rad, -0.9*j1_rad, 0.4*d3, 0.0, 0.9*j1_rad, -flip*j1_hi1),
CylinderZ(0.4*d3, j1_rad, flip*-1.2*j1_hi1, j1_rad),
CylinderZ(0.6*d3, 0.8*j1_rad, 0.4*d3, 0.8*j1_rad)])
# move to end of arm
link1 = Translate([link1], d2, 0.0, 0.0)
# add the arm itself, and the inner joint
link1 = Collection([
link1,
CylinderX(d2-1.5*j1_rad, l1_rad, 1.5*j0_rad, l1_rad),
Box(1.5*j0_rad, -0.9*j0_rad, -j0_hi, 0.0, 0.9*j0_rad, j0_hi),
CylinderZ(-1.2*j0_hi, j0_rad, 1.2*j0_hi, j0_rad)])
# make the joint work
link1 = HalRotate([link1],comp,"joint.0.pos-fb", 1, 0, 0, 1)
link1 = Color([1, .5, .5, .5],[link1])
#stationary base
link0 = Collection([
CylinderZ(d1-j0_hi, 0.8*j0_rad, d1-1.5*j0_hi, 0.8*j0_rad),
CylinderZ(d1-1.5*j0_hi, 0.8*j0_rad, 0.07*d1, 1.3*j0_rad),
CylinderZ(0.07*d1, 2.0*j0_rad, 0.0, 2.0*j0_rad)])
# slap the arm on top
link0 = Collection([
link0,
Translate([link1],0,0,d1)])
# add a floor
floor = Box(-0.5*size,-0.5*size,-0.02*size,0.5*size,0.5*size,0.0)
# and a table for the workpiece - define in workpiece coords
reach = d2+d4-d6
table_height = d1+d3-j3max-d5
work = Capture()
table = Collection([
work,
Box(-0.35*reach,-0.5*reach, -0.1*d1, 0.35*reach, 0.5*reach, 0.0)])
# make the table moveable (tilting)
table = HalRotate([table],comp,"joint.4.pos-fb", 1, 0, 1, 0)
table = HalRotate([table],comp,"joint.5.pos-fb", 1, 1, 0, 0)
# put the table into its proper place
table = Translate([table],0.5*reach,0.0,table_height)
model = Collection([link0, floor, table])
# show a title to prove the HUD
myhud = Hud()
myhud.show("Scara")
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.glWidget = GLWidget()
v = self.glWidget
v.set_latitudelimits(-360, 360)
size = max(d1+d3+l3_len,d2+d4+d6)
v.hud = myhud
v.hud.app = v #HUD needs to know where to draw
world = Capture()
v.model = Collection([model, world])
v.distance = size * 3
v.near = size * 0.01
v.far = size * 10.0
v.tool2view = tooltip
v.world2view = world
v.work2view = work
mainLayout = QHBoxLayout()
mainLayout.setContentsMargins(0,0,0,0)
mainLayout.addWidget(self.glWidget)
self.setLayout(mainLayout)
# but it you call this directly it should work too
if __name__ == '__main__':
main(model, tooltip, work, size=600, hud=myhud, lat=-75, lon=215)

View File

@@ -0,0 +1,199 @@
'''
conv_block.py
Copyright (C) 2020 - 2025 Phillip A Carter
Copyright (C) 2020 - 2024 Gregory D Carl
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.
'''
from qtpy.QtCore import Qt, QCoreApplication
from qtpy.QtWidgets import QLabel, QMessageBox
from qtvcp.core import Status
from importlib import reload
from plasmac import block as BLOCK
_translate = QCoreApplication.translate
STATUS = Status()
def preview(P, W, Conv, doMirror=False, doFlip=False):
if P.dialogError or not W.preview.isEnabled():
return
error = BLOCK.preview(Conv, P.fNgc, P.isConvBlock, W.conv_preview, W.cnEntry.text(), W.rnEntry.text(),
W.csEntry.text(), W.rsEntry.text(), W.oxEntry.text(), W.oyEntry.text(),
W.aEntry.text(), W.scEntry.text(), W.rtEntry.text(), doMirror, doFlip)
if error:
P.dialogError = True
P.dialog_show_ok(QMessageBox.Warning, _translate('Conversational', 'Block Error'), error)
else:
W.conv_preview.load(P.fNgc)
W.conv_preview.set_current_view()
W.add.setEnabled(True)
W.undo.setEnabled(True)
Conv.conv_preview_button(P, W, True)
W.add.setEnabled(True)
if not P.isConvBlock:
P.isConvBlock = 'created'
def get_parameters(P, W):
if P.isConvBlock:
with open(P.fNgc, 'r') as inCode:
line = inCode.readline()
inputs = None
for line in inCode:
if ';CONV_BLOCK INPUTS' in line:
inputs = [line]
elif inputs:
inputs = line.strip().strip(';').split(',')
W.csEntry.setText(inputs[0])
W.rsEntry.setText(inputs[1])
W.cnEntry.setText(inputs[2])
W.rnEntry.setText(inputs[3])
W.oxEntry.setText(inputs[4])
W.oyEntry.setText(inputs[5])
W.aEntry.setText(inputs[6])
W.scEntry.setText(inputs[7])
W.rtEntry.setText(inputs[8])
P.convMirror = int(inputs[9])
P.convFlip = int(inputs[10])
break
def widgets(P, W, Conv):
if P.developmentPin.get():
reload(BLOCK)
W.shLabel.setText(_translate('Conversational', 'SHAPE'))
W.lDesc.setText(_translate('Conversational', 'CREATE ARRAY OF SHAPES'))
# alignment and size
rightAlign = ['cnLabel', 'cnEntry', 'csEntry',
'rnLabel', 'rnEntry', 'rsEntry',
'oxLabel', 'oxEntry', 'oyEntry',
'scLabel', 'aEntry', 'scEntry',
'rtEntry']
leftAlign = ['csLabel', 'rsLabel', 'oyLabel', 'aLabel', 'rtLabel']
centerAlign = ['lDesc', 'ccLabel', 'rrLabel', 'oLabel', 'shLabel', 'ptLabel']
pButton = ['preview', 'add', 'undo', 'mirror', 'flip']
for widget in rightAlign:
W[widget].setAlignment(Qt.AlignRight | Qt.AlignVCenter)
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in leftAlign:
W[widget].setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in centerAlign:
W[widget].setAlignment(Qt.AlignCenter | Qt.AlignVCenter)
if widget == 'lDesc':
W[widget].setFixedWidth(240)
else:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in pButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
# starting parameters
W.add.setEnabled(False)
# connections
W.preview.pressed.connect(lambda: preview(P, W, Conv))
W.add.pressed.connect(lambda: Conv.conv_accept(P, W))
W.undo.pressed.connect(lambda: Conv.conv_undo_shape(P, W))
W.mirror.clicked.connect(lambda: preview(P, W, Conv, doMirror=True))
W.flip.clicked.connect(lambda: preview(P, W, Conv, doFlip=True))
entries = ['cnEntry', 'csEntry', 'rnEntry', 'rsEntry', 'oxEntry',
'oyEntry', 'scEntry', 'aEntry', 'rtEntry']
for entry in entries:
W[entry].textChanged.connect(lambda: Conv.conv_entry_changed(P, W, W.sender()))
W[entry].returnPressed.connect(lambda: preview(P, W, Conv))
# add to layout
if P.landscape:
W.s0 = QLabel('')
W.s0.setFixedHeight(51)
W.entries.addWidget(W.s0, 0, 0)
W.entries.addWidget(W.ccLabel, 1, 2)
W.entries.addWidget(W.cnLabel, 1, 0)
W.entries.addWidget(W.cnEntry, 1, 1)
W.entries.addWidget(W.csEntry, 1, 3)
W.entries.addWidget(W.csLabel, 1, 4)
W.entries.addWidget(W.rrLabel, 3, 2)
W.entries.addWidget(W.rnLabel, 3, 0)
W.entries.addWidget(W.rnEntry, 3, 1)
W.entries.addWidget(W.rsEntry, 3, 3)
W.entries.addWidget(W.rsLabel, 3, 4)
W.entries.addWidget(W.oLabel, 5, 2)
W.entries.addWidget(W.oxLabel, 5, 0)
W.entries.addWidget(W.oxEntry, 5, 1)
W.entries.addWidget(W.oyEntry, 5, 3)
W.entries.addWidget(W.oyLabel, 5, 4)
W.entries.addWidget(W.ptLabel, 7, 2)
W.entries.addWidget(W.aEntry, 7, 3)
W.entries.addWidget(W.aLabel, 7, 4)
W.entries.addWidget(W.scLabel, 9, 0)
W.entries.addWidget(W.scEntry, 9, 1)
W.entries.addWidget(W.shLabel, 9, 2)
W.entries.addWidget(W.rtEntry, 9, 3)
W.entries.addWidget(W.rtLabel, 9, 4)
W.entries.addWidget(W.mirror, 11, 1)
W.entries.addWidget(W.flip, 11, 3)
for r in [2, 4, 6, 8, 10]:
W[f'{r}'] = QLabel('')
W[f'{r}'].setFixedHeight(24)
W.entries.addWidget(W[f'{r}'], r, 0)
W.entries.addWidget(W.preview, 12, 0)
W.entries.addWidget(W.add, 12, 2)
W.entries.addWidget(W.undo, 12, 4)
W.entries.addWidget(W.lDesc, 13, 1, 1, 3)
else:
W.entries.addWidget(W.ccLabel, 0, 2)
W.entries.addWidget(W.cnLabel, 0, 0)
W.entries.addWidget(W.cnEntry, 0, 1)
W.entries.addWidget(W.csEntry, 0, 3)
W.entries.addWidget(W.csLabel, 0, 4)
W.entries.addWidget(W.rrLabel, 2, 2)
W.entries.addWidget(W.rnLabel, 2, 0)
W.entries.addWidget(W.rnEntry, 2, 1)
W.entries.addWidget(W.rsEntry, 2, 3)
W.entries.addWidget(W.rsLabel, 2, 4)
W.entries.addWidget(W.oLabel, 4, 2)
W.entries.addWidget(W.oxLabel, 4, 0)
W.entries.addWidget(W.oxEntry, 4, 1)
W.entries.addWidget(W.oyEntry, 4, 3)
W.entries.addWidget(W.oyLabel, 4, 4)
W.entries.addWidget(W.ptLabel, 6, 2)
W.entries.addWidget(W.aEntry, 6, 3)
W.entries.addWidget(W.aLabel, 6, 4)
W.entries.addWidget(W.scLabel, 8, 0)
W.entries.addWidget(W.scEntry, 8, 1)
W.entries.addWidget(W.shLabel, 8, 2)
W.entries.addWidget(W.rtEntry, 8, 3)
W.entries.addWidget(W.rtLabel, 8, 4)
W.entries.addWidget(W.mirror, 9, 1)
W.entries.addWidget(W.flip, 9, 3)
for r in [1, 3, 5, 7]:
W[f'{r}'] = QLabel('')
W[f'{r}'].setFixedHeight(24)
W.entries.addWidget(W[f'{r}'], r, 0)
W.entries.addWidget(W.preview, 10, 0)
W.entries.addWidget(W.add, 10, 2)
W.entries.addWidget(W.undo, 10, 4)
W.cnEntry.setFocus()
P.convSettingsChanged = False
get_parameters(P, W)
if not float(W.csEntry.text()):
W.csEntry.setText(f"{round(float(W.conv_preview.gcode_properties['x'].split()[4]) + (float(W.liEntry.text()) * 2), 2)}")
if not float(W.rsEntry.text()):
W.rsEntry.setText(f"{round(float(W.conv_preview.gcode_properties['y'].split()[4]) + (float(W.liEntry.text()) * 2), 2)}")

View File

@@ -0,0 +1,184 @@
'''
conv_bolt.py
Copyright (C) 2020 - 2024 Phillip A Carter
Copyright (C) 2020 - 2024 Gregory D Carl
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.
'''
from qtpy.QtCore import Qt, QCoreApplication
from qtpy.QtWidgets import QLabel, QMessageBox
from importlib import reload
from plasmac import bolt_circle as BOLT
_translate = QCoreApplication.translate
def preview(P, W, Conv):
if P.dialogError:
return
origin = W.centLeft.text() == 'CENTER'
error = BOLT.preview(Conv, P.fTmp, P.fNgc, P.fNgcBkp,
int(W.conv_material.currentText().split(':')[0]),
W.conv_material.currentText().split(':')[1].strip(),
P.preAmble, P.postAmble,
W.liEntry.text(), W.loEntry.text(), W.aEntry.text(),
origin, W.xsEntry.text(), W.ysEntry.text(),
W.kerf_width.value(),
W.overcut.isChecked(), W.ocEntry.text(),
P.holeDiameter, P.holeSpeed, W.dEntry.text(), W.hdEntry.text(),
W.hEntry.text(), W.caEntry.text(), P.invalidLeads)
if error:
P.dialogError = True
P.dialog_show_ok(QMessageBox.Warning, _translate('Conversational', 'Bolt-Circle Error'), error)
else:
W.conv_preview.load(P.fNgc)
W.conv_preview.set_current_view()
W.add.setEnabled(True)
W.undo.setEnabled(True)
Conv.conv_preview_button(P, W, True)
def auto_preview(P, W, Conv, button=False):
if button == 'center':
if not W.centLeft.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
if W.main_tab_widget.currentIndex() == 1 and \
W.dEntry.text() and W.hdEntry.text() and W.hEntry.text():
preview(P, W, Conv)
def entry_changed(P, W, Conv, widget):
Conv.conv_entry_changed(P, W, widget, 'bolt')
def widgets(P, W, Conv):
if P.developmentPin.get():
reload(BOLT)
W.dLabel.setText(_translate('Conversational', 'DIAMETER'))
W.hLabel.setText(_translate('Conversational', '# OF HOLES'))
W.loEntry.setText('0.0')
W.hEntry.setObjectName('intEntry')
W.lDesc.setText(_translate('Conversational', 'CREATING BOLT CIRCLE'))
W.iLabel.setPixmap(P.conv_bolt_l)
# alignment and size
rightAlign = ['spLabel', 'xsLabel', 'xsEntry', 'ysLabel', 'ysEntry',
'liLabel', 'liEntry', 'loLabel', 'loEntry', 'dLabel', 'dEntry',
'hdLabel', 'hdEntry', 'hLabel', 'hEntry',
'aLabel', 'aEntry', 'caLabel', 'caEntry', 'ocEntry']
centerAlign = ['lDesc']
leftAlign = ['ocLabel']
rButton = ['centLeft']
pButton = ['preview', 'add', 'undo', 'overcut']
for widget in rightAlign:
W[widget].setAlignment(Qt.AlignRight | Qt.AlignVCenter)
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in centerAlign:
W[widget].setAlignment(Qt.AlignCenter | Qt.AlignBottom)
W[widget].setFixedWidth(240)
W[widget].setFixedHeight(24)
for widget in leftAlign:
W[widget].setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in rButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in pButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
# connections
W.conv_material.currentTextChanged.connect(lambda: auto_preview(P, W, Conv))
W.centLeft.toggled.connect(lambda: auto_preview(P, W, Conv, 'center'))
W.overcut.toggled.connect(lambda: auto_preview(P, W, Conv))
W.preview.pressed.connect(lambda: preview(P, W, Conv))
W.add.pressed.connect(lambda: Conv.conv_add_shape_to_file(P, W))
W.undo.pressed.connect(lambda: Conv.conv_undo_shape(P, W))
entries = ['ocEntry', 'xsEntry', 'ysEntry', 'liEntry', 'loEntry',
'dEntry', 'hdEntry', 'hEntry', 'aEntry', 'caEntry']
for entry in entries:
W[entry].textChanged.connect(lambda: entry_changed(P, W, Conv, W.sender()))
W[entry].returnPressed.connect(lambda: preview(P, W, Conv))
# add to layout
if P.landscape:
W.entries.addWidget(W.spLabel, 0, 0)
W.entries.addWidget(W.centLeft, 0, 1)
W.entries.addWidget(W.xsLabel, 1, 0)
W.entries.addWidget(W.xsEntry, 1, 1)
W.entries.addWidget(W.ysLabel, 2, 0)
W.entries.addWidget(W.ysEntry, 2, 1)
W.entries.addWidget(W.liLabel, 3, 0)
W.entries.addWidget(W.liEntry, 3, 1)
W.entries.addWidget(W.loLabel, 4, 0)
W.entries.addWidget(W.loEntry, 4, 1)
W.entries.addWidget(W.dLabel, 5, 0)
W.entries.addWidget(W.dEntry, 5, 1)
W.entries.addWidget(W.hdLabel, 6, 0)
W.entries.addWidget(W.hdEntry, 6, 1)
W.entries.addWidget(W.hLabel, 7, 0)
W.entries.addWidget(W.hEntry, 7, 1)
W.entries.addWidget(W.aLabel, 8, 0)
W.entries.addWidget(W.aEntry, 8, 1)
W.entries.addWidget(W.caLabel, 9, 0)
W.entries.addWidget(W.caEntry, 9, 1)
W.entries.addWidget(W.overcut, 10, 0)
W.entries.addWidget(W.ocEntry, 10, 1)
W.entries.addWidget(W.ocLabel, 10, 2)
W.s11 = QLabel('')
W.s11.setFixedHeight(24)
W.entries.addWidget(W.s11, 11, 0)
W.entries.addWidget(W.preview, 12, 0)
W.entries.addWidget(W.add, 12, 2)
W.entries.addWidget(W.undo, 12, 4)
W.entries.addWidget(W.lDesc, 13, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 2, 7, 3)
else:
W.entries.addWidget(W.conv_material, 0, 0, 1, 5)
W.entries.addWidget(W.overcut, 1, 0)
W.entries.addWidget(W.ocLabel, 1, 1)
W.entries.addWidget(W.ocEntry, 1, 2)
W.entries.addWidget(W.spLabel, 2, 0)
W.entries.addWidget(W.centLeft, 2, 1)
W.entries.addWidget(W.xsLabel, 3, 0)
W.entries.addWidget(W.xsEntry, 3, 1)
W.entries.addWidget(W.ysLabel, 3, 2)
W.entries.addWidget(W.ysEntry, 3, 3)
W.entries.addWidget(W.liLabel, 4, 0)
W.entries.addWidget(W.liEntry, 4, 1)
W.entries.addWidget(W.loLabel, 4, 2)
W.entries.addWidget(W.loEntry, 4, 3)
W.entries.addWidget(W.dLabel, 5, 0)
W.entries.addWidget(W.dEntry, 5, 1)
W.entries.addWidget(W.hdLabel, 6, 0)
W.entries.addWidget(W.hdEntry, 6, 1)
W.entries.addWidget(W.hLabel, 6, 2)
W.entries.addWidget(W.hEntry, 6, 3)
W.entries.addWidget(W.aLabel, 7, 0)
W.entries.addWidget(W.aEntry, 7, 1)
W.entries.addWidget(W.caLabel, 7, 2)
W.entries.addWidget(W.caEntry, 7, 3)
W.s8 = QLabel('')
W.s8.setFixedHeight(24)
W.entries.addWidget(W.s8, 8, 0)
W.entries.addWidget(W.preview, 9, 0)
W.entries.addWidget(W.add, 9, 2)
W.entries.addWidget(W.undo, 9, 4)
W.entries.addWidget(W.lDesc, 10, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 5, 7, 3)
W.dEntry.setFocus()
P.convSettingsChanged = False

View File

@@ -0,0 +1,198 @@
'''
conv_circle.py
Copyright (C) 2020 - 2024 Phillip A Carter
Copyright (C) 2020 - 2024 Gregory D Carl
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.
'''
from qtpy.QtCore import Qt, QCoreApplication
from qtpy.QtWidgets import QLabel, QMessageBox
from importlib import reload
from plasmac import circle as CIRCLE
_translate = QCoreApplication.translate
def preview(P, W, Conv):
if P.dialogError:
return
origin = W.centLeft.text() == 'CENTER'
error = CIRCLE.preview(Conv, P.fTmp, P.fNgc, P.fNgcBkp,
int(W.conv_material.currentText().split(':')[0]),
W.conv_material.currentText().split(':')[1].strip(),
P.preAmble, P.postAmble,
W.liEntry.text(), W.loEntry.text(),
origin, W.xsEntry.text(), W.ysEntry.text(),
W.kerf_width.value(), P.intExt,
W.overcut.isChecked(), W.ocEntry.text(),
P.holeDiameter, P.holeSpeed,
W.dEntry.text(), P.invalidLeads)
if error:
P.dialogError = True
P.dialog_show_ok(QMessageBox.Warning, _translate('Conversational', 'Circle Error'), error)
else:
W.conv_preview.load(P.fNgc)
W.conv_preview.set_current_view()
W.add.setEnabled(True)
W.undo.setEnabled(True)
Conv.conv_preview_button(P, W, True)
def auto_preview(P, W, Conv, button=False):
if button == 'intext':
if not W.intExt.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
Conv.conv_entry_changed(P, W, None, 'circle')
elif button == 'center':
if not W.centLeft.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
if W.main_tab_widget.currentIndex() == 1 and W.dEntry.text():
preview(P, W, Conv)
def entry_changed(P, W, Conv, widget):
Conv.conv_entry_changed(P, W, widget, 'circle')
def overcut_toggled(P, W, Conv):
if W.overcut.isChecked():
try:
lolen = float(W.loEntry.text())
except:
lolen = 0
try:
dia = float(W.dEntry.text())
except:
dia = 0
if (P.intExt and lolen) or not dia or dia > P.holeDiameter:
W.overcut.setChecked(False)
auto_preview(P, W, Conv)
def cut_type_toggled(P, W):
try:
dia = float(W.dEntry.text())
except:
dia = 0
if dia >= P.holeDiameter or dia == 0 or P.intExt:
W.overcut.setChecked(False)
W.overcut.setEnabled(False)
W.ocEntry.setEnabled(False)
else:
W.overcut.setEnabled(True)
W.ocEntry.setEnabled(True)
def widgets(P, W, Conv):
if P.developmentPin.get():
reload(CIRCLE)
W.dLabel.setText(_translate('Conversational', 'DIAMETER'))
W.lDesc.setText(_translate('Conversational', 'CREATING CIRCLE'))
W.iLabel.setPixmap(P.conv_circle_l)
# alignment and size
rightAlign = ['ctLabel', 'spLabel', 'xsLabel', 'xsEntry', 'ysLabel',
'ysEntry', 'liLabel', 'liEntry', 'loLabel', 'loEntry',
'dLabel', 'dEntry', 'ocLabel', 'ocEntry']
centerAlign = ['lDesc']
rButton = ['intExt', 'centLeft']
pButton = ['preview', 'add', 'undo', 'overcut']
for widget in rightAlign:
W[widget].setAlignment(Qt.AlignRight | Qt.AlignVCenter)
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in centerAlign:
W[widget].setAlignment(Qt.AlignCenter | Qt.AlignBottom)
W[widget].setFixedWidth(240)
W[widget].setFixedHeight(24)
for widget in rButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in pButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
# connections
W.conv_material.currentTextChanged.connect(lambda: auto_preview(P, W, Conv))
W.intExt.toggled.connect(lambda: auto_preview(P, W, Conv, 'intext'))
W.centLeft.toggled.connect(lambda: auto_preview(P, W, Conv, 'center'))
W.overcut.toggled.connect(lambda: overcut_toggled(P, W, Conv))
W.preview.pressed.connect(lambda: preview(P, W, Conv))
W.add.pressed.connect(lambda: Conv.conv_add_shape_to_file(P, W))
W.undo.pressed.connect(lambda: Conv.conv_undo_shape(P, W))
entries = ['xsEntry', 'ysEntry', 'liEntry', 'loEntry', 'dEntry', 'ocEntry']
for entry in entries:
W[entry].textChanged.connect(lambda: entry_changed(P, W, Conv, W.sender()))
W[entry].returnPressed.connect(lambda: preview(P, W, Conv))
# add to layout
if P.landscape:
W.entries.addWidget(W.ctLabel, 0, 0)
W.entries.addWidget(W.intExt, 0, 1)
W.entries.addWidget(W.spLabel, 1, 0)
W.entries.addWidget(W.centLeft, 1, 1)
W.entries.addWidget(W.xsLabel, 2, 0)
W.entries.addWidget(W.xsEntry, 2, 1)
W.entries.addWidget(W.ysLabel, 3, 0)
W.entries.addWidget(W.ysEntry, 3, 1)
W.entries.addWidget(W.liLabel, 4, 0)
W.entries.addWidget(W.liEntry, 4, 1)
W.entries.addWidget(W.loLabel, 5, 0)
W.entries.addWidget(W.loEntry, 5, 1)
W.entries.addWidget(W.dLabel, 6, 0)
W.entries.addWidget(W.dEntry, 6, 1)
W.entries.addWidget(W.overcut, 7, 1)
W.entries.addWidget(W.ocLabel, 8, 0)
W.entries.addWidget(W.ocEntry, 8, 1)
for r in [9, 10, 11]:
W[f's{r}'] = QLabel('')
W[f's{r}'].setFixedHeight(24)
W.entries.addWidget(W[f's{r}'], r, 0)
W.entries.addWidget(W.preview, 12, 0)
W.entries.addWidget(W.add, 12, 2)
W.entries.addWidget(W.undo, 12, 4)
W.entries.addWidget(W.lDesc, 13, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 2, 7, 3)
else:
W.entries.addWidget(W.conv_material, 0, 0, 1, 5)
W.entries.addWidget(W.ctLabel, 1, 0)
W.entries.addWidget(W.intExt, 1, 1)
W.entries.addWidget(W.spLabel, 2, 0)
W.entries.addWidget(W.centLeft, 2, 1)
W.entries.addWidget(W.xsLabel, 3, 0)
W.entries.addWidget(W.xsEntry, 3, 1)
W.entries.addWidget(W.ysLabel, 3, 2)
W.entries.addWidget(W.ysEntry, 3, 3)
W.entries.addWidget(W.liLabel, 4, 0)
W.entries.addWidget(W.liEntry, 4, 1)
W.entries.addWidget(W.loLabel, 4, 2)
W.entries.addWidget(W.loEntry, 4, 3)
W.entries.addWidget(W.dLabel, 5, 0)
W.entries.addWidget(W.dEntry, 5, 1)
W.entries.addWidget(W.overcut, 6, 1)
W.entries.addWidget(W.ocLabel, 6, 2)
W.entries.addWidget(W.ocEntry, 6, 3)
for r in [7, 8]:
W[f's{r}'] = QLabel('')
W[f's{r}'].setFixedHeight(24)
W.entries.addWidget(W[f's{r}'], r, 0)
W.entries.addWidget(W.preview, 9, 0)
W.entries.addWidget(W.add, 9, 2)
W.entries.addWidget(W.undo, 9, 4)
W.entries.addWidget(W.lDesc, 10, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 5, 7, 3)
W.dEntry.setFocus()
P.convSettingsChanged = False

View File

@@ -0,0 +1,168 @@
'''
conv_ellipse.py
Copyright (C) 2021 - 2024 Phillip A Carter
Copyright (C) 2021 - 2024 Gregory D Carl
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.
'''
from qtpy.QtCore import Qt, QCoreApplication
from qtpy.QtWidgets import QLabel, QMessageBox
from importlib import reload
from plasmac import ellipse as ELLIPSE
_translate = QCoreApplication.translate
def preview(P, W, Conv):
if P.dialogError:
return
origin = W.centLeft.text() == 'CENTER'
error = ELLIPSE.preview(Conv, P.fTmp, P.fNgc, P.fNgcBkp,
int(W.conv_material.currentText().split(':')[0]),
W.conv_material.currentText().split(':')[1].strip(),
P.preAmble, P.postAmble,
W.liEntry.text(), W.loEntry.text(),
origin, W.xsEntry.text(), W.ysEntry.text(),
W.kerf_width.value(), P.intExt,
W.wEntry.text(), W.hEntry.text(), W.aEntry.text(), P.unitsPerMm)
if error:
P.dialogError = True
P.dialog_show_ok(QMessageBox.Warning, _translate('Conversational', 'Ellipse Error'), error)
else:
W.conv_preview.load(P.fNgc)
W.conv_preview.set_current_view()
W.add.setEnabled(True)
W.undo.setEnabled(True)
Conv.conv_preview_button(P, W, True)
def entry_changed(P, W, Conv, widget):
Conv.conv_entry_changed(P, W, widget)
def auto_preview(P, W, Conv, button=False):
if button == 'intext':
if not W.intExt.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
elif button == 'center':
if not W.centLeft.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
if W.main_tab_widget.currentIndex() == 1 and W.wEntry.text() and W.hEntry.text():
preview(P, W, Conv)
def widgets(P, W, Conv):
if P.developmentPin.get():
reload(ELLIPSE)
W.hLabel.setText(_translate('Conversational', 'HEIGHT'))
W.hEntry.setObjectName('')
W.lDesc.setText(_translate('Conversational', 'CREATING ELLIPSE'))
W.iLabel.setPixmap(P.conv_ellipse_l)
# alignment and size
rightAlign = ['ctLabel', 'spLabel', 'xsLabel', 'xsEntry', 'ysLabel',
'ysEntry', 'liLabel', 'liEntry', 'loLabel', 'loEntry',
'wLabel', 'wEntry', 'hLabel', 'hEntry', 'aLabel', 'aEntry']
centerAlign = ['lDesc']
rButton = ['intExt', 'centLeft']
pButton = ['preview', 'add', 'undo']
for widget in rightAlign:
W[widget].setAlignment(Qt.AlignRight | Qt.AlignVCenter)
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in centerAlign:
W[widget].setAlignment(Qt.AlignCenter | Qt.AlignBottom)
W[widget].setFixedWidth(240)
W[widget].setFixedHeight(24)
for widget in rButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in pButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
# connections
W.conv_material.currentTextChanged.connect(lambda: auto_preview(P, W, Conv))
W.intExt.toggled.connect(lambda: auto_preview(P, W, Conv, 'intext'))
W.centLeft.toggled.connect(lambda: auto_preview(P, W, Conv, 'center'))
W.preview.pressed.connect(lambda: preview(P, W, Conv))
W.add.pressed.connect(lambda: Conv.conv_add_shape_to_file(P, W))
W.undo.pressed.connect(lambda: Conv.conv_undo_shape(P, W))
entries = ['xsEntry', 'ysEntry', 'liEntry', 'loEntry', 'wEntry', 'hEntry', 'aEntry']
for entry in entries:
W[entry].textChanged.connect(lambda: entry_changed(P, W, Conv, W.sender()))
W[entry].returnPressed.connect(lambda: preview(P, W, Conv))
# add to layout
if P.landscape:
W.entries.addWidget(W.ctLabel, 0, 0)
W.entries.addWidget(W.intExt, 0, 1)
W.entries.addWidget(W.spLabel, 1, 0)
W.entries.addWidget(W.centLeft, 1, 1)
W.entries.addWidget(W.xsLabel, 2, 0)
W.entries.addWidget(W.xsEntry, 2, 1)
W.entries.addWidget(W.ysLabel, 3, 0)
W.entries.addWidget(W.ysEntry, 3, 1)
W.entries.addWidget(W.liLabel, 4, 0)
W.entries.addWidget(W.liEntry, 4, 1)
W.entries.addWidget(W.loLabel, 5, 0)
W.entries.addWidget(W.loEntry, 5, 1)
W.entries.addWidget(W.wLabel, 6, 0)
W.entries.addWidget(W.wEntry, 6, 1)
W.entries.addWidget(W.hLabel, 7, 0)
W.entries.addWidget(W.hEntry, 7, 1)
W.entries.addWidget(W.aLabel, 8, 0)
W.entries.addWidget(W.aEntry, 8, 1)
for r in [9, 10, 11]:
W[f's{r}'] = QLabel('')
W[f's{r}'].setFixedHeight(24)
W.entries.addWidget(W[f's{r}'], r, 0)
W.entries.addWidget(W.preview, 12, 0)
W.entries.addWidget(W.add, 12, 2)
W.entries.addWidget(W.undo, 12, 4)
W.entries.addWidget(W.lDesc, 13, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 2, 7, 3)
else:
W.entries.addWidget(W.conv_material, 0, 0, 1, 5)
W.entries.addWidget(W.ctLabel, 1, 0)
W.entries.addWidget(W.intExt, 1, 1)
W.entries.addWidget(W.spLabel, 2, 0)
W.entries.addWidget(W.centLeft, 2, 1)
W.entries.addWidget(W.xsLabel, 3, 0)
W.entries.addWidget(W.xsEntry, 3, 1)
W.entries.addWidget(W.ysLabel, 3, 2)
W.entries.addWidget(W.ysEntry, 3, 3)
W.entries.addWidget(W.liLabel, 4, 0)
W.entries.addWidget(W.liEntry, 4, 1)
W.entries.addWidget(W.loLabel, 4, 2)
W.entries.addWidget(W.loEntry, 4, 3)
W.entries.addWidget(W.wLabel, 5, 0)
W.entries.addWidget(W.wEntry, 5, 1)
W.entries.addWidget(W.hLabel, 5, 2)
W.entries.addWidget(W.hEntry, 5, 3)
W.entries.addWidget(W.aLabel, 6, 0)
W.entries.addWidget(W.aEntry, 6, 1)
for r in [7, 8]:
W[f's{r}'] = QLabel('')
W[f's{r}'].setFixedHeight(24)
W.entries.addWidget(W[f's{r}'], r, 0)
W.entries.addWidget(W.preview, 9, 0)
W.entries.addWidget(W.add, 9, 2)
W.entries.addWidget(W.undo, 9, 4)
W.entries.addWidget(W.lDesc, 10, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 5, 7, 3)
W.wEntry.setFocus()
P.convSettingsChanged = False

View File

@@ -0,0 +1,185 @@
'''
conv_gusset.py
Copyright (C) 2020 - 2024 Phillip A Carter
Copyright (C) 2020 - 2024 Gregory D Carl
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.
'''
from qtpy.QtCore import Qt, QCoreApplication
from qtpy.QtWidgets import QLabel, QMessageBox
from importlib import reload
from plasmac import gusset as GUSSET
_translate = QCoreApplication.translate
def preview(P, W, Conv):
if P.dialogError:
return
error = GUSSET.preview(Conv, P.fTmp, P.fNgc, P.fNgcBkp,
int(W.conv_material.currentText().split(':')[0]),
W.conv_material.currentText().split(':')[1].strip(),
P.preAmble, P.postAmble,
W.liEntry.text(), W.loEntry.text(),
W.xsEntry.text(), W.ysEntry.text(),
W.kerf_width.value(), P.intExt,
W.wEntry.text(), W.hEntry.text(), W.aEntry.text(),
W.rEntry.text(), W.rButton.text())
if error:
P.dialogError = True
P.dialog_show_ok(QMessageBox.Warning, _translate('Conversational', 'Gusset Error'), error)
else:
W.conv_preview.load(P.fNgc)
W.conv_preview.set_current_view()
W.add.setEnabled(True)
W.undo.setEnabled(True)
Conv.conv_preview_button(P, W, True)
def auto_preview(P, W, Conv, button=False):
if button == 'intext':
if not W.intExt.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
elif button == 'center':
if not W.centLeft.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
if W.main_tab_widget.currentIndex() == 1 and \
W.wEntry.text() and W.hEntry.text():
preview(P, W, Conv)
def entry_changed(P, W, Conv, widget):
Conv.conv_entry_changed(P, W, widget)
def rad_button_pressed(P, W, Conv, widget):
if widget.text() == _translate('Conversational', 'RADIUS'):
widget.setText(_translate('Conversational', 'CHAMFER'))
else:
widget.setText(_translate('Conversational', 'RADIUS'))
auto_preview(P, W, Conv)
def widgets(P, W, Conv):
if P.developmentPin.get():
reload(GUSSET)
W.rEntry.setText('0.0')
W.hLabel.setText(_translate('Conversational', 'HEIGHT'))
W.hEntry.setObjectName('')
W.lDesc.setText(_translate('Conversational', 'CREATING GUSSET'))
W.iLabel.setPixmap(P.conv_gusset_l)
# alignment and size
rightAlign = ['ctLabel', 'xsLabel', 'xsEntry', 'ysLabel', 'ysEntry',
'liLabel', 'liEntry', 'loLabel', 'loEntry', 'wLabel',
'wEntry', 'hLabel', 'hEntry', 'rEntry', 'aLabel', 'aEntry']
centerAlign = ['lDesc']
rButton = ['intExt']
pButton = ['preview', 'add', 'undo', 'rButton']
for widget in rightAlign:
W[widget].setAlignment(Qt.AlignRight | Qt.AlignVCenter)
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in centerAlign:
W[widget].setAlignment(Qt.AlignCenter | Qt.AlignBottom)
W[widget].setFixedWidth(240)
W[widget].setFixedHeight(24)
for widget in rButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in pButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
# connections
# we need an exception handler here as there is no signal connected if it is the first instance
try:
W.preview.pressed.disconnect()
W.undo.pressed.disconnect()
except:
pass
W.conv_material.currentTextChanged.connect(lambda: auto_preview(P, W, Conv))
W.intExt.toggled.connect(lambda: auto_preview(P, W, Conv, 'intext'))
W.rButton.pressed.connect(lambda: rad_button_pressed(P, W, Conv, W.sender()))
W.preview.pressed.connect(lambda: preview(P, W, Conv))
W.add.pressed.connect(lambda: Conv.conv_add_shape_to_file(P, W))
W.undo.pressed.connect(lambda: Conv.conv_undo_shape(P, W))
entries = ['xsEntry', 'ysEntry', 'liEntry', 'loEntry', 'wEntry', 'hEntry', 'rEntry', 'aEntry']
for entry in entries:
W[entry].textChanged.connect(lambda: entry_changed(P, W, Conv, W.sender()))
W[entry].returnPressed.connect(lambda: preview(P, W, Conv))
# add to layout
if P.landscape:
W.entries.addWidget(W.ctLabel, 0, 0)
W.entries.addWidget(W.intExt, 0, 1)
W.entries.addWidget(W.xsLabel, 1, 0)
W.entries.addWidget(W.xsEntry, 1, 1)
W.entries.addWidget(W.ysLabel, 2, 0)
W.entries.addWidget(W.ysEntry, 2, 1)
W.entries.addWidget(W.liLabel, 3, 0)
W.entries.addWidget(W.liEntry, 3, 1)
W.entries.addWidget(W.loLabel, 4, 0)
W.entries.addWidget(W.loEntry, 4, 1)
W.entries.addWidget(W.wLabel, 5, 0)
W.entries.addWidget(W.wEntry, 5, 1)
W.entries.addWidget(W.hLabel, 6, 0)
W.entries.addWidget(W.hEntry, 6, 1)
W.entries.addWidget(W.rButton, 7, 0)
W.entries.addWidget(W.rEntry, 7, 1)
W.entries.addWidget(W.aLabel, 8, 0)
W.entries.addWidget(W.aEntry, 8, 1)
for r in [9, 10, 11]:
W[f's{r}'] = QLabel('')
W[f's{r}'].setFixedHeight(24)
W.entries.addWidget(W[f's{r}'], r, 0)
W.entries.addWidget(W.preview, 12, 0)
W.entries.addWidget(W.add, 12, 2)
W.entries.addWidget(W.undo, 12, 4)
W.entries.addWidget(W.lDesc, 13, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 2, 7, 3)
else:
W.entries.addWidget(W.conv_material, 0, 0, 1, 5)
W.entries.addWidget(W.ctLabel, 1, 0)
W.entries.addWidget(W.intExt, 1, 1)
W.entries.addWidget(W.xsLabel, 2, 0)
W.entries.addWidget(W.xsEntry, 2, 1)
W.entries.addWidget(W.ysLabel, 2, 2)
W.entries.addWidget(W.ysEntry, 2, 3)
W.entries.addWidget(W.liLabel, 3, 0)
W.entries.addWidget(W.liEntry, 3, 1)
W.entries.addWidget(W.loLabel, 3, 2)
W.entries.addWidget(W.loEntry, 3, 3)
W.entries.addWidget(W.wLabel, 4, 0)
W.entries.addWidget(W.wEntry, 4, 1)
W.entries.addWidget(W.hLabel, 5, 0)
W.entries.addWidget(W.hEntry, 5, 1)
W.entries.addWidget(W.rButton, 6, 0)
W.entries.addWidget(W.rEntry, 6, 1)
W.entries.addWidget(W.aLabel, 7, 0)
W.entries.addWidget(W.aEntry, 7, 1)
W.s8 = QLabel('')
W.s8.setFixedHeight(24)
W.entries.addWidget(W.s8, 8, 0)
W.entries.addWidget(W.preview, 9, 0)
W.entries.addWidget(W.add, 9, 2)
W.entries.addWidget(W.undo, 9, 4)
W.entries.addWidget(W.lDesc, 10, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 5, 7, 3)
if W.aEntry.text() == '0.0':
W.aEntry.setText('90.0')
W.wEntry.setFocus()
P.convSettingsChanged = False

View File

@@ -0,0 +1,371 @@
'''
conv_line.py
Copyright (C) 2020 - 2024 Phillip A Carter
Copyright (C) 2020 - 2024 Gregory D Carl
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.
'''
from qtpy.QtCore import Qt, QCoreApplication
from qtpy.QtWidgets import QLabel, QMessageBox
from importlib import reload
from plasmac import line as LINE
_translate = QCoreApplication.translate
def preview(P, W, Conv):
if P.xLineEnd != Conv.conv_is_float(W.entry1.text())[1] or \
P.yLineEnd != Conv.conv_is_float(W.entry2.text())[1]:
P.convAddSegment = 0
if W.lType.currentText() == _translate('Conversational', 'LINE POINT ~ POINT'):
reply = LINE.do_line_point_to_point(Conv, W.entry1.text(), W.entry2.text(), W.entry3.text(),
W.entry4.text())
if not reply[0]:
P.xLineEnd = reply[1]
P.yLineEnd = reply[2]
P.conv_gcodeLine = reply[3]
else:
error_set(P, f'{reply[1]}\n')
return
elif W.lType.currentText() == _translate('Conversational', 'LINE BY ANGLE'):
reply = LINE.do_line_by_angle(Conv, W.entry1.text(), W.entry2.text(), W.entry3.text(),
W.entry4.text())
if not reply[0]:
P.xLineEnd = reply[1]
P.yLineEnd = reply[2]
P.conv_gcodeLine = reply[3]
else:
error_set(P, f'{reply[1]}\n')
return
elif W.lType.currentText() == _translate('Conversational', 'ARC 3P'):
reply = LINE.do_arc_3_points(Conv, W.entry1.text(), W.entry2.text(), W.entry3.text(),
W.entry4.text(), W.entry5.text(), W.entry6.text())
if not reply[0]:
P.xLineEnd = reply[1]
P.yLineEnd = reply[2]
P.conv_gcodeLine = reply[3]
else:
error_set(P, f'{reply[1]}\n')
return
elif W.lType.currentText() == _translate('Conversational', 'ARC 2P +RADIUS'):
arcType = '3' if 'CCW' in W.g23Arc.text() else '2'
reply = LINE.do_arc_2_points_radius(Conv, W.entry1.text(), W.entry2.text(), W.entry3.text(),
W.entry4.text(), W.entry5.text(), arcType)
if not reply[0]:
P.xLineEnd = reply[1]
P.yLineEnd = reply[2]
P.conv_gcodeLine = reply[3]
else:
error_set(P, f'{reply[1]}\n')
return
elif W.lType.currentText() == _translate('Conversational', 'ARC ANGLE +RADIUS'):
arcType = '3' if 'CCW' in W.g23Arc.text() else '2'
reply = LINE.do_arc_by_angle_radius(Conv, W.entry1.text(), W.entry2.text(), W.entry3.text(),
W.entry4.text(), W.entry5.text(), arcType)
if not reply[0]:
P.xLineEnd = reply[1]
P.yLineEnd = reply[2]
P.conv_gcodeLine = reply[3]
else:
error_set(P, f'{reply[1]}\n')
return
if P.convAddSegment == 1:
LINE.next_segment(P.fTmp, P.fNgc)
else:
valid, P.xLineStart = Conv.conv_is_float(W.entry1.text())
valid, P.yLineStart = Conv.conv_is_float(W.entry2.text())
# variable is not currently used
del valid
LINE.first_segment(P.fTmp, P.fNgc, P.fNgcBkp, P.preAmble,
P.xLineStart, P.yLineStart,
int(W.conv_material.currentText().split(':')[0]),
W.conv_material.currentText().split(':')[1].strip())
LINE.last_segment(P.fTmp, P.fNgc, P.conv_gcodeLine, P.postAmble)
Conv.conv_preview_button(P, W, True)
W.conv_preview.load(P.fNgc)
W.conv_preview.set_current_view()
W.add.setEnabled(True)
W.undo.setEnabled(True)
if P.convAddSegment == 1:
P.convAddSegment = 2
P.previewActive = True
def auto_preview(P, W, Conv):
# only act if checked as we uncheck it here
if W.g23Arc.isChecked():
text = 'CW - G2' if 'CCW' in W.g23Arc.text() else 'CCW - G3'
W.g23Arc.setChecked(False)
W.g23Arc.setText(text)
if W.main_tab_widget.currentIndex() == 1 and \
W.entry1.text() and W.entry2.text() and W.entry3.text() and W.entry4.text():
if W.lType.currentText() == _translate('Conversational', 'LINE POINT ~ POINT') or \
W.lType.currentText() == _translate('Conversational', 'LINE BY ANGLE') or \
(W.lType.currentText() == _translate('Conversational', 'ARC 3P') and W.entry5.text() and W.entry6.text()) or \
(W.lType.currentText() == _translate('Conversational', 'ARC 2P +RADIUS') and W.entry5.text()) or \
(W.lType.currentText() == _translate('Conversational', 'ARC ANGLE +RADIUS') and W.entry5.text()):
preview(P, W, Conv)
def line_type_changed(P, W, refresh):
if W.lType.currentText() == _translate('Conversational', 'LINE POINT ~ POINT'):
if not refresh:
set_line_point_to_point(P, W)
elif W.lType.currentText() == _translate('Conversational', 'LINE BY ANGLE'):
if not refresh:
set_line_by_angle(P, W)
elif W.lType.currentText() == _translate('Conversational', 'ARC 3P'):
if not refresh:
set_arc_3_points(P, W)
elif W.lType.currentText() == _translate('Conversational', 'ARC 2P +RADIUS'):
if not refresh:
set_arc_2_points_radius(P, W)
elif W.lType.currentText() == _translate('Conversational', 'ARC ANGLE +RADIUS'):
if not refresh:
set_arc_by_angle_radius(P, W)
W.entry3.setFocus()
def add_shape_to_file(P, W, Conv):
P.conv_gcodeSave = P.conv_gcodeLine
Conv.conv_add_shape_to_file(P, W)
P.xLineStart = P.xLineEnd
P.yLineStart = P.yLineEnd
W.entry1.setText(f'{P.xLineEnd:0.3f}')
W.entry2.setText(f'{P.yLineEnd:0.3f}')
P.convAddSegment = 1
line_type_changed(P, W, True)
W.add.setEnabled(False)
P.previewActive = False
def undo_shape(P, W, Conv):
cancel = Conv.conv_undo_shape(P, W)
if cancel:
return
if P.previewActive:
if P.convAddSegment > 1:
P.convAddSegment = 1
line_type_changed(P, W, True) # undo
else:
P.convAddSegment = 0
P.xLineStart = 0.000
P.yLineStart = 0.000
line_type_changed(P, W, False)
P.xLineEnd = P.xLineStart
P.yLineEnd = P.yLineStart
if len(P.conv_gcodeSave):
P.conv_gcodeLine = P.conv_gcodeSave
P.previewActive = False
def clear_widgets(P, W, image):
set_start_point(P, W, image)
for n in '3456':
W[f'entry{n}'].hide()
W[f'label{n}'].setText('')
W.g23Arc.hide()
def set_start_point(P, W, image):
W.iLabel.setPixmap(image)
text = _translate('Conversational', 'START')
W.label1.setText(_translate('Conversational', f'X {text}'))
W.entry1.setText(f'{P.xLineStart:0.3f}')
W.label2.setText(_translate('Conversational', f'Y {text}'))
W.entry2.setText(f'{P.yLineStart:0.3f}')
def set_line_point_to_point(P, W):
clear_widgets(P, W, P.conv_line_point)
W.label3.setText(_translate('Conversational', 'X END'))
W.label4.setText(_translate('Conversational', 'Y END'))
for n in '34':
W[f'entry{n}'].setText('')
W[f'entry{n}'].show()
W.entry3.setObjectName('neg')
def set_line_by_angle(P, W):
clear_widgets(P, W, P.conv_line_angle)
W.label3.setText(_translate('Conversational', 'LENGTH'))
W.label4.setText(_translate('Conversational', 'ANGLE'))
W.entry4.setText('0.000')
for n in '34':
W[f'entry{n}'].setText('')
W[f'entry{n}'].show()
W.entry3.setObjectName(None)
def set_arc_3_points(P, W):
clear_widgets(P, W, P.conv_line_3p)
W.label3.setText(_translate('Conversational', 'X NEXT'))
W.label4.setText(_translate('Conversational', 'Y NEXT'))
W.label5.setText(_translate('Conversational', 'X END'))
W.label6.setText(_translate('Conversational', 'Y END'))
for n in '3456':
W[f'entry{n}'].setText('')
W[f'entry{n}'].show()
W[f'entry{n}'].setObjectName('neg')
def set_arc_2_points_radius(P, W):
clear_widgets(P, W, P.conv_line_2pr)
set_arc_widgets(P, W)
W.label3.setText(_translate('Conversational', 'X END'))
W.label4.setText(_translate('Conversational', 'Y END'))
W.label5.setText(_translate('Conversational', 'RADIUS'))
W.entry5.setText('0.000')
W.label6.setText(_translate('Conversational', 'DIRECTION'))
for n in '345':
W[f'entry{n}'].setText('')
W[f'entry{n}'].show()
W.entry3.setObjectName('neg')
W.entry5.setObjectName(None)
def set_arc_by_angle_radius(P, W):
clear_widgets(P, W, P.conv_arc_angle)
set_arc_widgets(P, W)
W.label3.setText(_translate('Conversational', 'LENGTH'))
W.label4.setText(_translate('Conversational', 'ANGLE'))
W.entry4.setText('0.000')
W.label5.setText(_translate('Conversational', 'RADIUS'))
W.label6.setText(_translate('Conversational', 'DIRECTION'))
for n in '345':
W[f'entry{n}'].setText('')
W[f'entry{n}'].show()
W.entry3.setObjectName(None)
W.entry5.setObjectName(None)
def set_arc_widgets(P, W):
W.entries.removeWidget(W.g23Arc)
if P.landscape:
W.entries.addWidget(W.g23Arc, 8, 1)
else:
W.entries.addWidget(W.g23Arc, 6, 3)
W.label6.setText(_translate('Conversational', 'DIRECTION'))
W.label6.show()
W.g23Arc.show()
def error_set(P, error):
P.dialog_show_ok(QMessageBox.Warning, _translate('Conversational', 'Line Error'), error)
def widgets(P, W, Conv):
if P.developmentPin.get():
reload(LINE)
P.previewActive = False
W.lDesc.setText(_translate('Conversational', 'CREATING LINE OR ARC'))
# alignment and size
rightAlign = ['label1', 'entry1', 'label2', 'entry2', 'label3', 'entry3',
'label4', 'entry4', 'label5', 'entry5', 'label6', 'entry6']
centerAlign = ['lDesc']
rButton = ['g23Arc']
pButton = ['preview', 'add', 'undo']
for widget in rightAlign:
W[widget].setAlignment(Qt.AlignRight | Qt.AlignVCenter)
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in centerAlign:
W[widget].setAlignment(Qt.AlignCenter | Qt.AlignBottom)
W[widget].setFixedWidth(240)
W[widget].setFixedHeight(24)
for widget in rButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in pButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
# starting parameters
W.add.setEnabled(False)
P.convAddSegment = 0
P.conv_gcodeLine = ''
P.conv_gcodeSave = ''
P.xLineStart = 0.000
P.yLineStart = 0.000
P.xLineEnd = 0.000
P.yLineEnd = 0.000
# connections
W.conv_material.currentTextChanged.connect(lambda: auto_preview(P, W, Conv))
W.preview.pressed.connect(lambda: preview(P, W, Conv))
W.add.pressed.connect(lambda: add_shape_to_file(P, W, Conv))
W.undo.pressed.connect(lambda: undo_shape(P, W, Conv))
W.lType.currentTextChanged.connect(lambda: line_type_changed(P, W, False))
W.g23Arc.toggled.connect(lambda: auto_preview(P, W, Conv))
entries = ['entry1', 'entry2', 'entry3', 'entry4', 'entry5', 'entry6']
for entry in entries:
W[entry].textChanged.connect(lambda w: Conv.conv_entry_changed(P, W, W.sender()))
W[entry].returnPressed.connect(lambda: preview(P, W, Conv))
# add to layout
if P.landscape:
for row in range(14):
W.entries.setRowMinimumHeight(row, 24)
W.entries.addWidget(W.lType, 0, 0, 1, 2)
W.lType.setFixedHeight(24)
W.entries.addWidget(W.label1, 1, 0)
W.entries.addWidget(W.entry1, 1, 1)
W.entries.addWidget(W.label2, 2, 0)
W.entries.addWidget(W.entry2, 2, 1)
W.entries.addWidget(W.label3, 4, 0)
W.entries.addWidget(W.entry3, 4, 1)
W.entries.addWidget(W.label4, 5, 0)
W.entries.addWidget(W.entry4, 5, 1)
W.entries.addWidget(W.label5, 7, 0)
W.entries.addWidget(W.entry5, 7, 1)
W.entries.addWidget(W.label6, 8, 0)
W.entries.addWidget(W.entry6, 8, 1)
for r in [3, 6, 9, 10, 11]:
W[f's{r}'] = QLabel('')
W[f's{r}'].setFixedHeight(24)
W.entries.addWidget(W[f's{r}'], r, 0)
W.entries.addWidget(W.preview, 12, 0)
W.entries.addWidget(W.add, 12, 2)
W.entries.addWidget(W.undo, 12, 4)
W.entries.addWidget(W.lDesc, 13, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 2, 7, 3)
else:
for row in range(11):
W.entries.setRowMinimumHeight(row, 24)
W.entries.addWidget(W.conv_material, 0, 0, 1, 5)
W.entries.addWidget(W.lType, 1, 0, 1, 2)
W.entries.addWidget(W.label1, 2, 0)
W.entries.addWidget(W.entry1, 2, 1)
W.entries.addWidget(W.label2, 2, 2)
W.entries.addWidget(W.entry2, 2, 3)
W.entries.addWidget(W.label3, 4, 0)
W.entries.addWidget(W.entry3, 4, 1)
W.entries.addWidget(W.label4, 4, 2)
W.entries.addWidget(W.entry4, 4, 3)
W.entries.addWidget(W.label5, 6, 0)
W.entries.addWidget(W.entry5, 6, 1)
W.entries.addWidget(W.label6, 6, 2)
W.entries.addWidget(W.entry6, 6, 3)
for r in [3, 5, 7, 8]:
W[f's{r}'] = QLabel('')
W[f's{r}'].setFixedHeight(24)
W.entries.addWidget(W[f's{r}'], r, 0)
W.entries.addWidget(W.preview, 9, 0)
W.entries.addWidget(W.add, 9, 2)
W.entries.addWidget(W.undo, 9, 4)
W.entries.addWidget(W.lDesc, 10, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 5, 7, 3)
if not P.convSettingsChanged:
line_type_changed(P, W, False)
P.convSettingsChanged = False

View File

@@ -0,0 +1,181 @@
'''
conv_polygon.py
Copyright (C) 2020 - 2024 Phillip A Carter
Copyright (C) 2020 - 2024 Gregory D Carl
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.
'''
from qtpy.QtCore import Qt, QCoreApplication
from qtpy.QtWidgets import QLabel, QMessageBox
from importlib import reload
from plasmac import polygon as POLYGON
_translate = QCoreApplication.translate
def preview(P, W, Conv):
if P.dialogError:
return
origin = W.centLeft.text() == 'CENTER'
error = POLYGON.preview(Conv, P.fTmp, P.fNgc, P.fNgcBkp,
int(W.conv_material.currentText().split(':')[0]),
W.conv_material.currentText().split(':')[1].strip(),
P.preAmble, P.postAmble,
W.liEntry.text(), W.loEntry.text(),
origin, W.xsEntry.text(), W.ysEntry.text(),
W.kerf_width.value(), P.intExt,
W.sEntry.text(), W.dEntry.text(), W.aEntry.text(),
W.mCombo.currentIndex(), W.dLabel.text())
if error:
P.dialogError = True
P.dialog_show_ok(QMessageBox.Warning, _translate('Conversational', 'Polygon Error'), error)
else:
W.conv_preview.load(P.fNgc)
W.conv_preview.set_current_view()
W.add.setEnabled(True)
W.undo.setEnabled(True)
Conv.conv_preview_button(P, W, True)
def auto_preview(P, W, Conv, button=False):
if button == 'intext':
if not W.intExt.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
elif button == 'center':
if not W.centLeft.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
if W.main_tab_widget.currentIndex() == 1 and \
W.sEntry.text() and W.dEntry.text():
preview(P, W, Conv)
def entry_changed(P, W, Conv, widget):
Conv.conv_entry_changed(P, W, widget)
def mode_changed(P, W, Conv):
if W.mCombo.currentIndex() == 2:
W.dLabel.setText(_translate('Conversational', 'LENGTH'))
else:
W.dLabel.setText(_translate('Conversational', 'DIAMETER'))
auto_preview(P, W, Conv)
def widgets(P, W, Conv):
if P.developmentPin.get():
reload(POLYGON)
if W.mCombo.currentText() == _translate('Conversational', 'SIDE LENGTH'):
W.dLabel.setText(_translate('Conversational', 'LENGTH'))
else:
W.dLabel.setText(_translate('Conversational', 'DIAMETER'))
W.sLabel.setText(_translate('Conversational', 'SIDES'))
W.lDesc.setText(_translate('Conversational', 'CREATING POLYGON'))
W.iLabel.setPixmap(P.conv_polygon_l)
# alignment and size
rightAlign = ['ctLabel', 'spLabel', 'xsLabel', 'xsEntry', 'ysLabel',
'ysEntry', 'liLabel', 'liEntry', 'loLabel', 'loEntry',
'sLabel', 'sEntry', 'dLabel', 'dEntry', 'aLabel', 'aEntry']
centerAlign = ['lDesc']
rButton = ['intExt', 'centLeft']
pButton = ['preview', 'add', 'undo']
for widget in rightAlign:
W[widget].setAlignment(Qt.AlignRight | Qt.AlignVCenter)
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in centerAlign:
W[widget].setAlignment(Qt.AlignCenter | Qt.AlignBottom)
W[widget].setFixedWidth(240)
W[widget].setFixedHeight(24)
for widget in rButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in pButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
# connections
W.conv_material.currentTextChanged.connect(lambda: auto_preview(P, W, Conv))
W.intExt.toggled.connect(lambda: auto_preview(P, W, Conv, 'intext'))
W.centLeft.toggled.connect(lambda: auto_preview(P, W, Conv, 'center'))
W.mCombo.currentIndexChanged.connect(lambda: mode_changed(P, W, Conv))
W.preview.pressed.connect(lambda: preview(P, W, Conv))
W.add.pressed.connect(lambda: Conv.conv_add_shape_to_file(P, W))
W.undo.pressed.connect(lambda: Conv.conv_undo_shape(P, W))
entries = ['xsEntry', 'ysEntry', 'liEntry', 'loEntry',
'sEntry', 'dEntry', 'aEntry']
for entry in entries:
W[entry].textChanged.connect(lambda: entry_changed(P, W, Conv, W.sender()))
W[entry].returnPressed.connect(lambda: preview(P, W, Conv))
# add to layout
if P.landscape:
W.entries.addWidget(W.ctLabel, 0, 0)
W.entries.addWidget(W.intExt, 0, 1)
W.entries.addWidget(W.spLabel, 1, 0)
W.entries.addWidget(W.centLeft, 1, 1)
W.entries.addWidget(W.xsLabel, 2, 0)
W.entries.addWidget(W.xsEntry, 2, 1)
W.entries.addWidget(W.ysLabel, 3, 0)
W.entries.addWidget(W.ysEntry, 3, 1)
W.entries.addWidget(W.liLabel, 4, 0)
W.entries.addWidget(W.liEntry, 4, 1)
W.entries.addWidget(W.loLabel, 5, 0)
W.entries.addWidget(W.loEntry, 5, 1)
W.entries.addWidget(W.mCombo, 6, 0, 1, 2)
W.entries.addWidget(W.sLabel, 7, 0)
W.entries.addWidget(W.sEntry, 7, 1)
W.entries.addWidget(W.dLabel, 8, 0)
W.entries.addWidget(W.dEntry, 8, 1)
W.entries.addWidget(W.aLabel, 9, 0)
W.entries.addWidget(W.aEntry, 9, 1)
for r in [10, 11]:
W[f's{r}'] = QLabel('')
W[f's{r}'].setFixedHeight(24)
W.entries.addWidget(W[f's{r}'], r, 0)
W.entries.addWidget(W.preview, 12, 0)
W.entries.addWidget(W.add, 12, 2)
W.entries.addWidget(W.undo, 12, 4)
W.entries.addWidget(W.lDesc, 13, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 2, 7, 3)
else:
W.entries.addWidget(W.conv_material, 0, 0, 1, 5)
W.entries.addWidget(W.ctLabel, 1, 0)
W.entries.addWidget(W.intExt, 1, 1)
W.entries.addWidget(W.spLabel, 2, 0)
W.entries.addWidget(W.centLeft, 2, 1)
W.entries.addWidget(W.xsLabel, 3, 0)
W.entries.addWidget(W.xsEntry, 3, 1)
W.entries.addWidget(W.ysLabel, 3, 2)
W.entries.addWidget(W.ysEntry, 3, 3)
W.entries.addWidget(W.liLabel, 4, 0)
W.entries.addWidget(W.liEntry, 4, 1)
W.entries.addWidget(W.loLabel, 4, 2)
W.entries.addWidget(W.loEntry, 4, 3)
W.entries.addWidget(W.mCombo, 5, 0, 1, 2)
W.entries.addWidget(W.sLabel, 6, 0)
W.entries.addWidget(W.sEntry, 6, 1)
W.entries.addWidget(W.dLabel, 7, 0)
W.entries.addWidget(W.dEntry, 7, 1)
W.entries.addWidget(W.aLabel, 8, 0)
W.entries.addWidget(W.aEntry, 8, 1)
W.entries.addWidget(W.preview, 9, 0)
W.entries.addWidget(W.add, 9, 2)
W.entries.addWidget(W.undo, 9, 4)
W.entries.addWidget(W.lDesc, 10, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 5, 7, 3)
W.sEntry.setFocus()
P.convSettingsChanged = False

View File

@@ -0,0 +1,210 @@
'''
conv_rectangle.py
Copyright (C) 2020 - 2024 Phillip A Carter
Copyright (C) 2020 - 2024 Gregory D Carl
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.
'''
from qtpy.QtCore import Qt, QCoreApplication
from qtpy.QtWidgets import QLabel, QMessageBox
from importlib import reload
from plasmac import rectangle as RECTANGLE
_translate = QCoreApplication.translate
def preview(P, W, Conv):
if P.dialogError:
return
origin = W.centLeft.text() == 'CENTER'
styles = [None, 'extRadius', 'extRadius', 'extRadius', 'extRadius']
for n in range(1, 5):
if W[f'r{n}Button'].text().startswith(_translate('Conversational', 'CHAMFER')):
styles[n] = 'chamfer'
elif W[f'r{n}Button'].text().startswith(_translate('Conversational', 'iRADIUS')):
styles[n] = 'intRadius'
error = RECTANGLE.preview(Conv, P.fTmp, P.fNgc, P.fNgcBkp,
int(W.conv_material.currentText().split(':')[0]),
W.conv_material.currentText().split(':')[1].strip(),
P.preAmble, P.postAmble,
W.liEntry.text(), W.loEntry.text(),
origin, W.xsEntry.text(), W.ysEntry.text(),
W.kerf_width.value(), P.intExt,
W.wEntry.text(), W.hEntry.text(), W.aEntry.text(),
styles[1], styles[2], styles[3], styles[4],
W.r1Entry.text(), W.r2Entry.text(), W.r3Entry.text(), W.r4Entry.text(),
W.r1Button.text(), W.r2Button.text(), W.r3Button.text(), W.r4Button.text())
if error:
P.dialogError = True
P.dialog_show_ok(QMessageBox.Warning, _translate('Conversational', 'Rectangle Error'), error)
else:
W.conv_preview.load(P.fNgc)
W.conv_preview.set_current_view()
W.add.setEnabled(True)
W.undo.setEnabled(True)
Conv.conv_preview_button(P, W, True)
def auto_preview(P, W, Conv, button=False):
if button == 'intext':
if not W.intExt.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
elif button == 'center':
if not W.centLeft.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
# if W.main_tab_widget.currentIndex() == 1 and \
# W.wEntry.text() and W.hEntry.text():
if W.main_tab_widget.currentIndex() == 1:
preview(P, W, Conv)
def entry_changed(P, W, Conv, widget):
Conv.conv_entry_changed(P, W, widget)
def rad_button_pressed(P, W, Conv, button, value):
if button.text().split()[0] == _translate('Conversational', 'RADIUS'):
text = _translate('Conversational', 'CHAMFER')
button.setText(f'{text} {value}')
elif button.text().split()[0] == _translate('Conversational', 'CHAMFER'):
text = _translate('Conversational', 'iRADIUS')
button.setText(f'{text} {value}')
else:
text = _translate('Conversational', 'RADIUS')
button.setText(f'{text} {value}')
auto_preview(P, W, Conv)
def widgets(P, W, Conv):
if P.developmentPin.get():
reload(RECTANGLE)
W.hLabel.setText(_translate('Conversational', 'HEIGHT'))
W.hEntry.setObjectName('')
W.lDesc.setText(_translate('Conversational', 'CREATING RECTANGLE'))
W.iLabel.setPixmap(P.conv_rectangle_l)
# alignment and size
rightAlign = ['ctLabel', 'spLabel', 'xsLabel', 'xsEntry', 'ysLabel',
'ysEntry', 'liLabel', 'liEntry', 'loLabel', 'loEntry',
'wLabel', 'wEntry', 'hLabel', 'hEntry', 'aLabel',
'aEntry', 'r1Entry', 'r2Entry', 'r3Entry', 'r4Entry']
centerAlign = ['lDesc']
rButton = ['intExt', 'centLeft']
pButton = ['preview', 'add', 'undo',
'r1Button', 'r2Button', 'r3Button', 'r4Button']
for widget in rightAlign:
W[widget].setAlignment(Qt.AlignRight | Qt.AlignVCenter)
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in centerAlign:
W[widget].setAlignment(Qt.AlignCenter | Qt.AlignBottom)
W[widget].setFixedWidth(240)
W[widget].setFixedHeight(24)
for widget in rButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in pButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
# connections
W.conv_material.currentTextChanged.connect(lambda: auto_preview(P, W, Conv))
W.intExt.toggled.connect(lambda: auto_preview(P, W, Conv, 'intext'))
W.centLeft.toggled.connect(lambda: auto_preview(P, W, Conv, 'center'))
W.preview.pressed.connect(lambda: preview(P, W, Conv))
W.add.pressed.connect(lambda: Conv.conv_add_shape_to_file(P, W))
W.undo.pressed.connect(lambda: Conv.conv_undo_shape(P, W))
entries = ['xsEntry', 'ysEntry', 'liEntry', 'loEntry', 'wEntry', 'hEntry',
'aEntry', 'r1Entry', 'r2Entry', 'r3Entry', 'r4Entry', ]
for entry in entries:
W[entry].textChanged.connect(lambda: entry_changed(P, W, Conv, W.sender()))
W[entry].returnPressed.connect(lambda: preview(P, W, Conv))
W.r1Button.pressed.connect(lambda: rad_button_pressed(P, W, Conv, W.sender(), '1'))
W.r2Button.pressed.connect(lambda: rad_button_pressed(P, W, Conv, W.sender(), '2'))
W.r3Button.pressed.connect(lambda: rad_button_pressed(P, W, Conv, W.sender(), '3'))
W.r4Button.pressed.connect(lambda: rad_button_pressed(P, W, Conv, W.sender(), '4'))
# add to layout
if P.landscape:
W.entries.addWidget(W.ctLabel, 0, 0)
W.entries.addWidget(W.intExt, 0, 1)
W.entries.addWidget(W.spLabel, 1, 0)
W.entries.addWidget(W.centLeft, 1, 1)
W.entries.addWidget(W.xsLabel, 2, 0)
W.entries.addWidget(W.xsEntry, 2, 1)
W.entries.addWidget(W.ysLabel, 3, 0)
W.entries.addWidget(W.ysEntry, 3, 1)
W.entries.addWidget(W.liLabel, 4, 0)
W.entries.addWidget(W.liEntry, 4, 1)
W.entries.addWidget(W.loLabel, 5, 0)
W.entries.addWidget(W.loEntry, 5, 1)
W.entries.addWidget(W.wLabel, 6, 0)
W.entries.addWidget(W.wEntry, 6, 1)
W.entries.addWidget(W.hLabel, 7, 0)
W.entries.addWidget(W.hEntry, 7, 1)
W.entries.addWidget(W.aLabel, 8, 0)
W.entries.addWidget(W.aEntry, 8, 1)
W.entries.addWidget(W.r1Button, 9, 0)
W.entries.addWidget(W.r1Entry, 9, 1)
W.entries.addWidget(W.r2Button, 9, 2)
W.entries.addWidget(W.r2Entry, 9, 3)
W.entries.addWidget(W.r3Button, 10, 0)
W.entries.addWidget(W.r3Entry, 10, 1)
W.entries.addWidget(W.r4Button, 10, 2)
W.entries.addWidget(W.r4Entry, 10, 3)
W.s11 = QLabel('')
W.s11.setFixedHeight(24)
W.entries.addWidget(W.s11, 11, 0)
W.entries.addWidget(W.preview, 12, 0)
W.entries.addWidget(W.add, 12, 2)
W.entries.addWidget(W.undo, 12, 4)
W.entries.addWidget(W.lDesc, 13, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 2, 7, 3)
else:
W.entries.addWidget(W.conv_material, 0, 0, 1, 5)
W.entries.addWidget(W.ctLabel, 1, 0)
W.entries.addWidget(W.intExt, 1, 1)
W.entries.addWidget(W.spLabel, 2, 0)
W.entries.addWidget(W.centLeft, 2, 1)
W.entries.addWidget(W.xsLabel, 3, 0)
W.entries.addWidget(W.xsEntry, 3, 1)
W.entries.addWidget(W.ysLabel, 3, 2)
W.entries.addWidget(W.ysEntry, 3, 3)
W.entries.addWidget(W.liLabel, 4, 0)
W.entries.addWidget(W.liEntry, 4, 1)
W.entries.addWidget(W.loLabel, 4, 2)
W.entries.addWidget(W.loEntry, 4, 3)
W.entries.addWidget(W.wLabel, 5, 0)
W.entries.addWidget(W.wEntry, 5, 1)
W.entries.addWidget(W.hLabel, 5, 2)
W.entries.addWidget(W.hEntry, 5, 3)
W.entries.addWidget(W.aLabel, 6, 0)
W.entries.addWidget(W.aEntry, 6, 1)
W.entries.addWidget(W.r1Button, 7, 0)
W.entries.addWidget(W.r1Entry, 7, 1)
W.entries.addWidget(W.r2Button, 7, 2)
W.entries.addWidget(W.r2Entry, 7, 3)
W.entries.addWidget(W.r3Button, 8, 0)
W.entries.addWidget(W.r3Entry, 8, 1)
W.entries.addWidget(W.r4Button, 8, 2)
W.entries.addWidget(W.r4Entry, 8, 3)
W.entries.addWidget(W.preview, 9, 0)
W.entries.addWidget(W.add, 9, 2)
W.entries.addWidget(W.undo, 9, 4)
W.entries.addWidget(W.lDesc, 10, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 5, 7, 3)
W.wEntry.setFocus()
P.convSettingsChanged = False

View File

@@ -0,0 +1,161 @@
'''
conv_sector.py
Copyright (C) 2020 - 2024 Phillip A Carter
Copyright (C) 2020 - 2024 Gregory D Carl
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.
'''
from qtpy.QtCore import Qt, QCoreApplication
from qtpy.QtWidgets import QLabel, QMessageBox
from importlib import reload
from plasmac import sector as SECTOR
_translate = QCoreApplication.translate
def preview(P, W, Conv):
if P.dialogError:
return
error = SECTOR.preview(Conv, P.fTmp, P.fNgc, P.fNgcBkp,
int(W.conv_material.currentText().split(':')[0]),
W.conv_material.currentText().split(':')[1].strip(),
P.preAmble, P.postAmble,
W.liEntry.text(), W.loEntry.text(),
W.xsEntry.text(), W.ysEntry.text(),
W.kerf_width.value(), P.intExt,
W.rEntry.text(), W.sEntry.text(), W.aEntry.text())
if error:
P.dialogError = True
P.dialog_show_ok(QMessageBox.Warning, _translate('Conversational', 'Sector Error'), error)
else:
W.conv_preview.load(P.fNgc)
W.conv_preview.set_current_view()
W.add.setEnabled(True)
W.undo.setEnabled(True)
Conv.conv_preview_button(P, W, True)
def auto_preview(P, W, Conv, button=False):
if button == 'intext':
if not W.intExt.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
elif button == 'center':
if not W.centLeft.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
if W.main_tab_widget.currentIndex() == 1 and \
W.rEntry.text() and W.sEntry.text():
preview(P, W, Conv)
def entry_changed(P, W, Conv, widget):
Conv.conv_entry_changed(P, W, widget)
def widgets(P, W, Conv):
if P.developmentPin.get():
reload(SECTOR)
W.sLabel.setText(_translate('Conversational', 'SEC ANGLE'))
W.lDesc.setText(_translate('Conversational', 'CREATING SECTOR'))
W.iLabel.setPixmap(P.conv_sector_l)
# alignment and size
rightAlign = ['ctLabel', 'xsLabel', 'xsEntry', 'ysLabel', 'ysEntry',
'liLabel', 'liEntry', 'loLabel', 'loEntry', 'rLabel',
'rEntry', 'sLabel', 'sEntry', 'aLabel', 'aEntry']
centerAlign = ['lDesc']
rButton = ['intExt']
pButton = ['preview', 'add', 'undo']
for widget in rightAlign:
W[widget].setAlignment(Qt.AlignRight | Qt.AlignVCenter)
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in centerAlign:
W[widget].setAlignment(Qt.AlignCenter | Qt.AlignBottom)
W[widget].setFixedWidth(240)
W[widget].setFixedHeight(24)
for widget in rButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in pButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
# connections
W.conv_material.currentTextChanged.connect(lambda: auto_preview(P, W, Conv))
W.intExt.toggled.connect(lambda: auto_preview(P, W, Conv, 'intext'))
W.preview.pressed.connect(lambda: preview(P, W, Conv))
W.add.pressed.connect(lambda: Conv.conv_add_shape_to_file(P, W))
W.undo.pressed.connect(lambda: Conv.conv_undo_shape(P, W))
entries = ['xsEntry', 'ysEntry', 'liEntry', 'loEntry', 'rEntry', 'sEntry', 'aEntry']
for entry in entries:
W[entry].textChanged.connect(lambda: entry_changed(P, W, Conv, W.sender()))
W[entry].returnPressed.connect(lambda: preview(P, W, Conv))
# add to layout
if P.landscape:
W.entries.addWidget(W.ctLabel, 0, 0)
W.entries.addWidget(W.intExt, 0, 1)
W.entries.addWidget(W.xsLabel, 1, 0)
W.entries.addWidget(W.xsEntry, 1, 1)
W.entries.addWidget(W.ysLabel, 2, 0)
W.entries.addWidget(W.ysEntry, 2, 1)
W.entries.addWidget(W.liLabel, 3, 0)
W.entries.addWidget(W.liEntry, 3, 1)
W.entries.addWidget(W.loLabel, 4, 0)
W.entries.addWidget(W.loEntry, 4, 1)
W.entries.addWidget(W.rLabel, 5, 0)
W.entries.addWidget(W.rEntry, 5, 1)
W.entries.addWidget(W.sLabel, 6, 0)
W.entries.addWidget(W.sEntry, 6, 1)
W.entries.addWidget(W.aLabel, 7, 0)
W.entries.addWidget(W.aEntry, 7, 1)
for r in [8, 9, 10, 11]:
W[f's{r}'] = QLabel('')
W[f's{r}'].setFixedHeight(24)
W.entries.addWidget(W[f's{r}'], r, 0)
W.entries.addWidget(W.preview, 12, 0)
W.entries.addWidget(W.add, 12, 2)
W.entries.addWidget(W.undo, 12, 4)
W.entries.addWidget(W.lDesc, 13, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 2, 7, 3)
else:
W.entries.addWidget(W.conv_material, 0, 0, 1, 5)
W.entries.addWidget(W.ctLabel, 1, 0)
W.entries.addWidget(W.intExt, 1, 1)
W.entries.addWidget(W.xsLabel, 2, 0)
W.entries.addWidget(W.xsEntry, 2, 1)
W.entries.addWidget(W.ysLabel, 3, 2)
W.entries.addWidget(W.ysEntry, 3, 3)
W.entries.addWidget(W.liLabel, 4, 0)
W.entries.addWidget(W.liEntry, 4, 1)
W.entries.addWidget(W.loLabel, 4, 2)
W.entries.addWidget(W.loEntry, 4, 3)
W.entries.addWidget(W.rLabel, 5, 0)
W.entries.addWidget(W.rEntry, 5, 1)
W.entries.addWidget(W.sLabel, 6, 0)
W.entries.addWidget(W.sEntry, 6, 1)
W.entries.addWidget(W.aLabel, 7, 0)
W.entries.addWidget(W.aEntry, 7, 1)
W.s8 = QLabel('')
W.s8.setFixedHeight(24)
W.entries.addWidget(W.s8, 8, 0)
W.entries.addWidget(W.preview, 9, 0)
W.entries.addWidget(W.add, 9, 2)
W.entries.addWidget(W.undo, 9, 4)
W.entries.addWidget(W.lDesc, 10, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 5, 7, 3)
W.rEntry.setFocus()
P.convSettingsChanged = False

View File

@@ -0,0 +1,194 @@
'''
conv_settings.py
Copyright (C) 2020 - 2024 Phillip A Carter
Copyright (C) 2020 - 2024 Gregory D Carl
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.
'''
from qtpy.QtCore import Qt, QCoreApplication
from qtpy.QtWidgets import QLabel, QMessageBox
_translate = QCoreApplication.translate
def save(P, W, Conv):
if P.dialogError:
return
msg = []
P.preAmble = W.preEntry.text()
P.postAmble = W.pstEntry.text()
P.origin = W.centLeft.text() == 'CENTER'
error = ''
valid, P.leadIn = Conv.conv_is_float(W.liEntry.text())
if not valid:
msg = _translate('Conversational', 'Invalid LEAD IN entry detected')
error += f'{msg}\n\n'
valid, P.leadOut = Conv.conv_is_float(W.loEntry.text())
if not valid:
msg = _translate('Conversational', 'Invalid LEAD OUT entry detected')
error += f'{msg}\n\n'
valid, P.holeDiameter = Conv.conv_is_float(W.shEntry.text())
if not valid:
msg = _translate('Conversational', 'Invalid DIAMETER entry detected')
error += f'{msg}\n\n'
valid, P.holeSpeed = Conv.conv_is_float(W.hsEntry.text())
if not valid:
msg = _translate('Conversational', 'Invalid SPEED % entry detected')
error += f'{msg}\n\n'
valid, P.gridSize = Conv.conv_is_float(W.gsEntry.text())
if not valid:
msg = _translate('Conversational', 'Invalid GRID SIZE entry detected')
error += f'{msg}\n\n'
if error:
P.dialogError = True
P.dialog_show_ok(QMessageBox.Warning, _translate('Conversational', 'Settings Error'), error)
return
P.PREFS.putpref('Preamble', P.preAmble, str, 'CONVERSATIONAL')
P.PREFS.putpref('Postamble', P.postAmble, str, 'CONVERSATIONAL')
P.PREFS.putpref('Origin', P.origin, int, 'CONVERSATIONAL')
P.PREFS.putpref('Leadin', P.leadIn, float, 'CONVERSATIONAL')
P.PREFS.putpref('Leadout', P.leadOut, float, 'CONVERSATIONAL')
P.PREFS.putpref('Hole diameter', P.holeDiameter, float, 'CONVERSATIONAL')
P.PREFS.putpref('Hole speed', P.holeSpeed, int, 'CONVERSATIONAL')
P.PREFS.putpref('Grid Size', P.gridSize, float, 'CONVERSATIONAL')
# grid size is in inches
W.conv_preview.grid_size = P.gridSize / P.unitsPerMm / 25.4
W.conv_preview.set_current_view()
P.convSettingsChanged = 1
def reload(P, W, Conv):
load(P, W)
show(P, W)
if not P.convSettingsChanged:
P.convSettingsChanged = 2
def exit(P, W, Conv):
if P.convSettingsChanged != 1:
W.centLeft.setText(P.savedSettings['origin'])
W.intExt.setText(P.savedSettings['intext'])
W.liEntry.setText(P.savedSettings['in'])
W.loEntry.setText(P.savedSettings['out'])
Conv.conv_restore_buttons(P, W)
if not P.convSettingsChanged:
P.convSettingsChanged = 3
W[P.oldConvButton].click()
def load(P, W):
P.preAmble = P.PREFS.getpref('Preamble', P.ambles, str, 'CONVERSATIONAL')
P.postAmble = P.PREFS.getpref('Postamble', P.ambles, str, 'CONVERSATIONAL')
P.origin = P.PREFS.getpref('Origin', 0, int, 'CONVERSATIONAL')
P.leadIn = P.PREFS.getpref('Leadin', 0, float, 'CONVERSATIONAL')
P.leadOut = P.PREFS.getpref('Leadout', 0, float, 'CONVERSATIONAL')
P.holeDiameter = P.PREFS.getpref('Hole diameter', P.unitCode[2], float, 'CONVERSATIONAL')
P.holeSpeed = P.PREFS.getpref('Hole speed', 60, int, 'CONVERSATIONAL')
P.gridSize = P.PREFS.getpref('Grid Size', 0, float, 'CONVERSATIONAL')
def show(P, W):
W.preEntry.setText(P.preAmble)
W.pstEntry.setText(P.postAmble)
W.liEntry.setText(f'{P.leadIn}')
W.loEntry.setText(f'{P.leadOut}')
W.shEntry.setText(f'{P.holeDiameter}')
W.hsEntry.setText(f'{P.holeSpeed}')
W.gsEntry.setText(f'{P.gridSize}')
if P.origin:
W.centLeft.setText('CENTER')
else:
W.centLeft.setText('BTM LEFT')
# grid size is in inches
W.conv_preview.grid_size = P.gridSize / P.unitsPerMm / 25.4
W.conv_preview.set_current_view()
def centLeft_toggled(P, W, Conv):
if not W.centLeft.isChecked():
return
text = 'CENTER' if W.centLeft.text() == 'BTM LEFT' else 'BTM LEFT'
W.centLeft.setText(text)
W.centLeft.setChecked(False)
def widgets(P, W, Conv):
W.shLabel.setText(_translate('Conversational', 'SMALL HOLES'))
W.hLabel.setText(_translate('Conversational', 'DIAMETER'))
# alignment and size
ra = ['preLabel', 'pstLabel', 'liLabel', 'liEntry', 'loEntry',
'hLabel', 'shEntry', 'hsEntry', 'gsLabel', 'gsEntry']
la = ['loLabel', 'hsLabel']
ca = ['oLabel', 'llLabel', 'shLabel', 'pvLabel']
rb = ['centLeft']
bt = ['save', 'reload', 'cExit']
for w in ra:
W[w].setAlignment(Qt.AlignRight | Qt.AlignVCenter)
W[w].setFixedWidth(80)
W[w].setFixedHeight(24)
for w in la:
W[w].setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
W[w].setFixedWidth(80)
W[w].setFixedHeight(24)
for w in ca:
W[w].setAlignment(Qt.AlignCenter | Qt.AlignBottom)
W[w].setFixedWidth(240)
W[w].setFixedHeight(24)
for w in rb:
W[w].setFixedWidth(80)
W[w].setFixedHeight(24)
for w in bt:
W[w].setFixedWidth(80)
W[w].setFixedHeight(24)
# connections
W.centLeft.toggled.connect(lambda: centLeft_toggled(P, W, Conv))
W.liEntry.textChanged.connect(lambda: Conv.conv_entry_changed(P, W, W.sender()))
W.loEntry.textChanged.connect(lambda: Conv.conv_entry_changed(P, W, W.sender()))
W.shEntry.textChanged.connect(lambda: Conv.conv_entry_changed(P, W, W.sender()))
W.hsEntry.textChanged.connect(lambda: Conv.conv_entry_changed(P, W, W.sender()))
W.gsEntry.textChanged.connect(lambda: Conv.conv_entry_changed(P, W, W.sender()))
W.save.pressed.connect(lambda: save(P, W, Conv))
W.reload.pressed.connect(lambda: reload(P, W, Conv))
W.cExit.pressed.connect(lambda: exit(P, W, Conv))
# add to layout
W.entries.addWidget(W.preLabel, 0, 0)
W.entries.addWidget(W.preEntry, 0, 1, 1, 4)
W.entries.addWidget(W.pstLabel, 1, 0)
W.entries.addWidget(W.pstEntry, 1, 1, 1, 4)
W.entries.addWidget(W.oLabel, 2, 1, 1, 3)
W.entries.addWidget(W.centLeft, 3, 2)
W.entries.addWidget(W.llLabel, 4, 1, 1, 3)
W.entries.addWidget(W.liLabel, 5, 0)
W.entries.addWidget(W.liEntry, 5, 1)
W.entries.addWidget(W.loEntry, 5, 3)
W.entries.addWidget(W.loLabel, 5, 4)
W.entries.addWidget(W.shLabel, 6, 1, 1, 3)
W.entries.addWidget(W.hLabel, 7, 0)
W.entries.addWidget(W.shEntry, 7, 1)
W.entries.addWidget(W.hsEntry, 7, 3)
W.entries.addWidget(W.hsLabel, 7, 4)
W.entries.addWidget(W.pvLabel, 8, 1, 1, 3)
W.entries.addWidget(W.gsLabel, 9, 0)
W.entries.addWidget(W.gsEntry, 9, 1)
for r in (10, 11):
W[f's{r}'] = QLabel('')
W[f's{r}'].setFixedHeight(24)
W.entries.addWidget(W[f's{r}'], r, 0)
W.entries.addWidget(W.save, 12, 0)
W.entries.addWidget(W.reload, 12, 2)
W.entries.addWidget(W.cExit, 12, 4)
W.preEntry.setFocus()

View File

@@ -0,0 +1,167 @@
'''
conv_slot.py
Copyright (C) 2020 - 2024 Phillip A Carter
Copyright (C) 2020 - 2024 Gregory D Carl
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.
'''
from qtpy.QtCore import Qt, QCoreApplication
from qtpy.QtWidgets import QLabel, QMessageBox
from importlib import reload
from plasmac import slot as SLOT
_translate = QCoreApplication.translate
def preview(P, W, Conv):
if P.dialogError:
return
origin = W.centLeft.text() == 'CENTER'
error = SLOT.preview(Conv, P.fTmp, P.fNgc, P.fNgcBkp,
int(W.conv_material.currentText().split(':')[0]),
W.conv_material.currentText().split(':')[1].strip(),
P.preAmble, P.postAmble,
W.liEntry.text(), W.loEntry.text(),
origin, W.xsEntry.text(), W.ysEntry.text(),
W.kerf_width.value(), P.intExt,
W.lEntry.text(), W.wEntry.text(), W.aEntry.text())
if error:
P.dialogError = True
P.dialog_show_ok(QMessageBox.Warning, _translate('Conversational', 'Slot Error'), error)
else:
W.conv_preview.load(P.fNgc)
W.conv_preview.set_current_view()
W.add.setEnabled(True)
W.undo.setEnabled(True)
Conv.conv_preview_button(P, W, True)
def auto_preview(P, W, Conv, button=False):
if button == 'intext':
if not W.intExt.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
elif button == 'center':
if not W.centLeft.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
if W.main_tab_widget.currentIndex() == 1 and \
W.lEntry.text() and W.wEntry.text():
preview(P, W, Conv)
def entry_changed(P, W, Conv, widget):
Conv.conv_entry_changed(P, W, widget)
def widgets(P, W, Conv):
if P.developmentPin.get():
reload(SLOT)
W.lDesc.setText(_translate('Conversational', 'CREATING SLOT'))
W.iLabel.setPixmap(P.conv_slot_l)
# alignment and size
rightAlign = ['ctLabel', 'spLabel', 'xsLabel', 'xsEntry', 'ysLabel',
'ysEntry', 'liLabel', 'liEntry', 'loLabel', 'loEntry',
'lLabel', 'lEntry', 'wLabel', 'wEntry', 'aLabel', 'aEntry']
centerAlign = ['lDesc']
rButton = ['intExt', 'centLeft']
pButton = ['preview', 'add', 'undo']
for widget in rightAlign:
W[widget].setAlignment(Qt.AlignRight | Qt.AlignVCenter)
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in centerAlign:
W[widget].setAlignment(Qt.AlignCenter | Qt.AlignBottom)
W[widget].setFixedWidth(240)
W[widget].setFixedHeight(24)
for widget in rButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in pButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
# connections
W.conv_material.currentTextChanged.connect(lambda: auto_preview(P, W, Conv))
W.intExt.toggled.connect(lambda: auto_preview(P, W, Conv, 'intext'))
W.centLeft.toggled.connect(lambda: auto_preview(P, W, Conv, 'center'))
W.preview.pressed.connect(lambda: preview(P, W, Conv))
W.add.pressed.connect(lambda: Conv.conv_add_shape_to_file(P, W))
W.undo.pressed.connect(lambda: Conv.conv_undo_shape(P, W))
entries = ['xsEntry', 'ysEntry', 'liEntry', 'loEntry',
'lEntry', 'wEntry', 'aEntry']
for entry in entries:
W[entry].textChanged.connect(lambda: entry_changed(P, W, Conv, W.sender()))
W[entry].returnPressed.connect(lambda: preview(P, W, Conv))
# add to layout
if P.landscape:
W.entries.addWidget(W.ctLabel, 0, 0)
W.entries.addWidget(W.intExt, 0, 1)
W.entries.addWidget(W.spLabel, 1, 0)
W.entries.addWidget(W.centLeft, 1, 1)
W.entries.addWidget(W.xsLabel, 2, 0)
W.entries.addWidget(W.xsEntry, 2, 1)
W.entries.addWidget(W.ysLabel, 3, 0)
W.entries.addWidget(W.ysEntry, 3, 1)
W.entries.addWidget(W.liLabel, 4, 0)
W.entries.addWidget(W.liEntry, 4, 1)
W.entries.addWidget(W.loLabel, 5, 0)
W.entries.addWidget(W.loEntry, 5, 1)
W.entries.addWidget(W.lLabel, 6, 0)
W.entries.addWidget(W.lEntry, 6, 1)
W.entries.addWidget(W.wLabel, 7, 0)
W.entries.addWidget(W.wEntry, 7, 1)
W.entries.addWidget(W.aLabel, 8, 0)
W.entries.addWidget(W.aEntry, 8, 1)
for r in [9, 10, 11]:
W[f's{r}'] = QLabel('')
W[f's{r}'].setFixedHeight(24)
W.entries.addWidget(W[f's{r}'], r, 0)
W.entries.addWidget(W.preview, 12, 0)
W.entries.addWidget(W.add, 12, 2)
W.entries.addWidget(W.undo, 12, 4)
W.entries.addWidget(W.lDesc, 13, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 2, 7, 3)
else:
W.entries.addWidget(W.conv_material, 0, 0, 1, 5)
W.entries.addWidget(W.ctLabel, 1, 0)
W.entries.addWidget(W.intExt, 1, 1)
W.entries.addWidget(W.spLabel, 2, 0)
W.entries.addWidget(W.centLeft, 2, 1)
W.entries.addWidget(W.xsLabel, 3, 0)
W.entries.addWidget(W.xsEntry, 3, 1)
W.entries.addWidget(W.ysLabel, 3, 2)
W.entries.addWidget(W.ysEntry, 3, 3)
W.entries.addWidget(W.liLabel, 4, 0)
W.entries.addWidget(W.liEntry, 4, 1)
W.entries.addWidget(W.loLabel, 4, 2)
W.entries.addWidget(W.loEntry, 4, 3)
W.entries.addWidget(W.lLabel, 5, 0)
W.entries.addWidget(W.lEntry, 5, 1)
W.entries.addWidget(W.wLabel, 6, 0)
W.entries.addWidget(W.wEntry, 6, 1)
W.entries.addWidget(W.aLabel, 7, 0)
W.entries.addWidget(W.aEntry, 7, 1)
W.s8 = QLabel('')
W.s8.setFixedHeight(24)
W.entries.addWidget(W.s8, 8, 0)
W.entries.addWidget(W.preview, 9, 0)
W.entries.addWidget(W.add, 9, 2)
W.entries.addWidget(W.undo, 9, 4)
W.entries.addWidget(W.lDesc, 10, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 5, 7, 3)
W.lEntry.setFocus()
P.convSettingsChanged = False

View File

@@ -0,0 +1,172 @@
'''
conv_star.py
Copyright (C) 2020 - 2024 Phillip A Carter
Copyright (C) 2020 - 2024 Gregory D Carl
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.
'''
from qtpy.QtCore import Qt, QCoreApplication
from qtpy.QtWidgets import QLabel, QMessageBox
from importlib import reload
from plasmac import star as STAR
_translate = QCoreApplication.translate
def preview(P, W, Conv):
if P.dialogError:
return
origin = W.centLeft.text() == 'CENTER'
error = STAR.preview(Conv, P.fTmp, P.fNgc, P.fNgcBkp,
int(W.conv_material.currentText().split(':')[0]),
W.conv_material.currentText().split(':')[1].strip(),
P.preAmble, P.postAmble,
W.liEntry.text(), W.loEntry.text(),
origin, W.xsEntry.text(), W.ysEntry.text(),
W.kerf_width.value(), P.intExt,
W.pEntry.text(), W.odEntry.text(), W.idEntry.text(), W.aEntry.text())
if error:
P.dialogError = True
P.dialog_show_ok(QMessageBox.Warning, _translate('Conversational', 'Star Error'), error)
else:
W.conv_preview.load(P.fNgc)
W.conv_preview.set_current_view()
W.add.setEnabled(True)
W.undo.setEnabled(True)
Conv.conv_preview_button(P, W, True)
def auto_preview(P, W, Conv, button=False):
if button == 'intext':
if not W.intExt.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
elif button == 'center':
if not W.centLeft.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
if W.main_tab_widget.currentIndex() == 1 and \
W.pEntry.text() and W.odEntry.text() and W.idEntry.text():
preview(P, W, Conv)
def entry_changed(P, W, Conv, widget):
Conv.conv_entry_changed(P, W, widget)
def widgets(P, W, Conv):
if P.developmentPin.get():
reload(STAR)
W.lDesc.setText(_translate('Conversational', 'CREATING STAR'))
W.iLabel.setPixmap(P.conv_star_l)
# alignment and size
rightAlign = ['ctLabel', 'spLabel', 'xsLabel', 'xsEntry', 'ysLabel',
'ysEntry', 'liLabel', 'liEntry', 'loLabel', 'loEntry',
'pLabel', 'pEntry', 'odLabel', 'odEntry', 'idLabel',
'idEntry', 'aLabel', 'aEntry']
centerAlign = ['lDesc']
rButton = ['intExt', 'centLeft']
pButton = ['preview', 'add', 'undo']
for widget in rightAlign:
W[widget].setAlignment(Qt.AlignRight | Qt.AlignVCenter)
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in centerAlign:
W[widget].setAlignment(Qt.AlignCenter | Qt.AlignBottom)
W[widget].setFixedWidth(240)
W[widget].setFixedHeight(24)
for widget in rButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in pButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
# connections
W.conv_material.currentTextChanged.connect(lambda: auto_preview(P, W, Conv))
W.intExt.toggled.connect(lambda: auto_preview(P, W, Conv, 'intext'))
W.centLeft.toggled.connect(lambda: auto_preview(P, W, Conv, 'center'))
W.preview.pressed.connect(lambda: preview(P, W, Conv))
W.add.pressed.connect(lambda: Conv.conv_add_shape_to_file(P, W))
W.undo.pressed.connect(lambda: Conv.conv_undo_shape(P, W))
entries = ['xsEntry', 'ysEntry', 'liEntry', 'loEntry',
'pEntry', 'odEntry', 'idEntry', 'aEntry']
for entry in entries:
W[entry].textChanged.connect(lambda: entry_changed(P, W, Conv, W.sender()))
W[entry].returnPressed.connect(lambda: preview(P, W, Conv))
# add to layout
if P.landscape:
W.entries.addWidget(W.ctLabel, 0, 0)
W.entries.addWidget(W.intExt, 0, 1)
W.entries.addWidget(W.spLabel, 1, 0)
W.entries.addWidget(W.centLeft, 1, 1)
W.entries.addWidget(W.xsLabel, 2, 0)
W.entries.addWidget(W.xsEntry, 2, 1)
W.entries.addWidget(W.ysLabel, 3, 0)
W.entries.addWidget(W.ysEntry, 3, 1)
W.entries.addWidget(W.liLabel, 4, 0)
W.entries.addWidget(W.liEntry, 4, 1)
W.entries.addWidget(W.loLabel, 5, 0)
W.entries.addWidget(W.loEntry, 5, 1)
W.entries.addWidget(W.pLabel, 6, 0)
W.entries.addWidget(W.pEntry, 6, 1)
W.entries.addWidget(W.odLabel, 7, 0)
W.entries.addWidget(W.odEntry, 7, 1)
W.entries.addWidget(W.idLabel, 8, 0)
W.entries.addWidget(W.idEntry, 8, 1)
W.entries.addWidget(W.aLabel, 9, 0)
W.entries.addWidget(W.aEntry, 9, 1)
for r in [10, 11]:
W[f's{r}'] = QLabel('')
W[f's{r}'].setFixedHeight(24)
W.entries.addWidget(W[f's{r}'], r, 0)
W.entries.addWidget(W.preview, 12, 0)
W.entries.addWidget(W.add, 12, 2)
W.entries.addWidget(W.undo, 12, 4)
W.entries.addWidget(W.lDesc, 13, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 2, 7, 3)
else:
W.entries.addWidget(W.conv_material, 0, 0, 1, 5)
W.entries.addWidget(W.ctLabel, 1, 0)
W.entries.addWidget(W.intExt, 1, 1)
W.entries.addWidget(W.spLabel, 2, 0)
W.entries.addWidget(W.centLeft, 2, 1)
W.entries.addWidget(W.xsLabel, 3, 0)
W.entries.addWidget(W.xsEntry, 3, 1)
W.entries.addWidget(W.ysLabel, 3, 2)
W.entries.addWidget(W.ysEntry, 3, 3)
W.entries.addWidget(W.liLabel, 4, 0)
W.entries.addWidget(W.liEntry, 4, 1)
W.entries.addWidget(W.loLabel, 4, 2)
W.entries.addWidget(W.loEntry, 4, 3)
W.entries.addWidget(W.pLabel, 5, 0)
W.entries.addWidget(W.pEntry, 5, 1)
W.entries.addWidget(W.odLabel, 6, 0)
W.entries.addWidget(W.odEntry, 6, 1)
W.entries.addWidget(W.idLabel, 6, 2)
W.entries.addWidget(W.idEntry, 6, 3)
W.entries.addWidget(W.aLabel, 7, 0)
W.entries.addWidget(W.aEntry, 7, 1)
W.s8 = QLabel('')
W.s8.setFixedHeight(24)
W.entries.addWidget(W.s8, 8, 0)
W.entries.addWidget(W.preview, 9, 0)
W.entries.addWidget(W.add, 9, 2)
W.entries.addWidget(W.undo, 9, 4)
W.entries.addWidget(W.lDesc, 10, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 5, 7, 3)
W.pEntry.setFocus()
P.convSettingsChanged = False

View File

@@ -0,0 +1,179 @@
'''
conv_triangle.py
Copyright (C) 2020 - 2024 Phillip A Carter
Copyright (C) 2020 - 2024 Gregory D Carl
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.
'''
from qtpy.QtCore import Qt, QCoreApplication
from qtpy.QtWidgets import QMessageBox
from importlib import reload
from plasmac import triangle as TRIANGLE
_translate = QCoreApplication.translate
def preview(P, W, Conv):
if P.dialogError:
return
error = TRIANGLE.preview(Conv, P.fTmp, P.fNgc, P.fNgcBkp,
int(W.conv_material.currentText().split(':')[0]),
W.conv_material.currentText().split(':')[1].strip(),
P.preAmble, P.postAmble,
W.liEntry.text(), W.loEntry.text(),
W.xsEntry.text(), W.ysEntry.text(),
W.kerf_width.value(), P.intExt,
W.AaEntry.text(), W.BaEntry.text(), W.CaEntry.text(),
W.AlEntry.text(), W.BlEntry.text(), W.ClEntry.text(),
W.aEntry.text())
if error:
P.dialogError = True
P.dialog_show_ok(QMessageBox.Warning, _translate('Conversational', 'Triangle Error'), error)
else:
W.conv_preview.load(P.fNgc)
W.conv_preview.set_current_view()
W.add.setEnabled(True)
W.undo.setEnabled(True)
Conv.conv_preview_button(P, W, True)
def auto_preview(P, W, Conv, button=False):
if button == 'intext':
if not W.intExt.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
elif button == 'center':
if not W.centLeft.isChecked():
return
Conv.conv_auto_preview_button(P, W, button)
if W.main_tab_widget.currentIndex() == 1 and \
((W.AaEntry.text() and W.BaEntry.text() and W.CaEntry.text() and
(W.AlEntry.text() or W.BlEntry.text() or W.ClEntry.text())) or
(W.AaEntry.text() and W.BlEntry.text() and W.ClEntry.text()) or
(W.AlEntry.text() and W.BaEntry.text() and W.ClEntry.text()) or
(W.AlEntry.text() and W.BlEntry.text() and W.CaEntry.text()) or
(W.AlEntry.text() and W.BlEntry.text() and W.ClEntry.text())):
preview(P, W, Conv)
def entry_changed(P, W, Conv, widget):
Conv.conv_entry_changed(P, W, widget)
def widgets(P, W, Conv):
if P.developmentPin.get():
reload(TRIANGLE)
W.lDesc.setText(_translate('Conversational', 'CREATING TRIANGLE'))
W.iLabel.setPixmap(P.conv_triangle_l)
# alignment and size
rightAlign = ['ctLabel', 'xsLabel', 'xsEntry', 'ysLabel', 'ysEntry',
'liLabel', 'liEntry', 'loLabel', 'loEntry', 'AaLabel',
'AaEntry', 'BaLabel', 'BaEntry', 'CaLabel', 'CaEntry',
'AlLabel', 'AlEntry', 'BlLabel', 'BlEntry', 'ClLabel',
'ClEntry', 'aLabel', 'aEntry']
centerAlign = ['lDesc']
rButton = ['intExt']
pButton = ['preview', 'add', 'undo']
for widget in rightAlign:
W[widget].setAlignment(Qt.AlignRight | Qt.AlignVCenter)
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in centerAlign:
W[widget].setAlignment(Qt.AlignCenter | Qt.AlignBottom)
W[widget].setFixedWidth(240)
W[widget].setFixedHeight(24)
for widget in rButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
for widget in pButton:
W[widget].setFixedWidth(80)
W[widget].setFixedHeight(24)
# connections
W.conv_material.currentTextChanged.connect(lambda: auto_preview(P, W, Conv))
W.intExt.toggled.connect(lambda: auto_preview(P, W, Conv, 'intext'))
W.preview.pressed.connect(lambda: preview(P, W, Conv))
W.add.pressed.connect(lambda: Conv.conv_add_shape_to_file(P, W))
W.undo.pressed.connect(lambda: Conv.conv_undo_shape(P, W))
entries = ['xsEntry', 'ysEntry', 'liEntry', 'loEntry', 'AaEntry', 'BaEntry',
'CaEntry', 'AlEntry', 'BlEntry', 'ClEntry', 'aEntry']
for entry in entries:
W[entry].textChanged.connect(lambda: entry_changed(P, W, Conv, W.sender()))
W[entry].returnPressed.connect(lambda: preview(P, W, Conv))
# add to layout
if P.landscape:
W.entries.addWidget(W.ctLabel, 0, 0)
W.entries.addWidget(W.intExt, 0, 1)
W.entries.addWidget(W.xsLabel, 1, 0)
W.entries.addWidget(W.xsEntry, 1, 1)
W.entries.addWidget(W.ysLabel, 2, 0)
W.entries.addWidget(W.ysEntry, 2, 1)
W.entries.addWidget(W.liLabel, 3, 0)
W.entries.addWidget(W.liEntry, 3, 1)
W.entries.addWidget(W.loLabel, 4, 0)
W.entries.addWidget(W.loEntry, 4, 1)
W.entries.addWidget(W.AaLabel, 5, 0)
W.entries.addWidget(W.AaEntry, 5, 1)
W.entries.addWidget(W.BaLabel, 6, 0)
W.entries.addWidget(W.BaEntry, 6, 1)
W.entries.addWidget(W.CaLabel, 7, 0)
W.entries.addWidget(W.CaEntry, 7, 1)
W.entries.addWidget(W.AlLabel, 8, 0)
W.entries.addWidget(W.AlEntry, 8, 1)
W.entries.addWidget(W.BlLabel, 9, 0)
W.entries.addWidget(W.BlEntry, 9, 1)
W.entries.addWidget(W.ClLabel, 10, 0)
W.entries.addWidget(W.ClEntry, 10, 1)
W.entries.addWidget(W.aLabel, 11, 0)
W.entries.addWidget(W.aEntry, 11, 1)
W.entries.addWidget(W.preview, 12, 0)
W.entries.addWidget(W.add, 12, 2)
W.entries.addWidget(W.undo, 12, 4)
W.entries.addWidget(W.lDesc, 13, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 2, 7, 3)
else:
W.entries.addWidget(W.conv_material, 0, 0, 1, 5)
W.entries.addWidget(W.ctLabel, 1, 0)
W.entries.addWidget(W.intExt, 1, 1)
W.entries.addWidget(W.xsLabel, 2, 0)
W.entries.addWidget(W.xsEntry, 2, 1)
W.entries.addWidget(W.ysLabel, 2, 2)
W.entries.addWidget(W.ysEntry, 2, 3)
W.entries.addWidget(W.liLabel, 3, 0)
W.entries.addWidget(W.liEntry, 3, 1)
W.entries.addWidget(W.loLabel, 3, 2)
W.entries.addWidget(W.loEntry, 3, 3)
W.entries.addWidget(W.AaLabel, 4, 0)
W.entries.addWidget(W.AaEntry, 4, 1)
W.entries.addWidget(W.BaLabel, 4, 2)
W.entries.addWidget(W.BaEntry, 4, 3)
W.entries.addWidget(W.CaLabel, 5, 0)
W.entries.addWidget(W.CaEntry, 5, 1)
W.entries.addWidget(W.AlLabel, 6, 0)
W.entries.addWidget(W.AlEntry, 6, 1)
W.entries.addWidget(W.BlLabel, 6, 2)
W.entries.addWidget(W.BlEntry, 6, 3)
W.entries.addWidget(W.ClLabel, 7, 0)
W.entries.addWidget(W.ClEntry, 7, 1)
W.entries.addWidget(W.aLabel, 8, 0)
W.entries.addWidget(W.aEntry, 8, 1)
W.entries.addWidget(W.preview, 9, 0)
W.entries.addWidget(W.add, 9, 2)
W.entries.addWidget(W.undo, 9, 4)
W.entries.addWidget(W.lDesc, 10, 1, 1, 3)
W.entries.addWidget(W.iLabel, 0, 5, 7, 3)
W.AaEntry.setFocus()
P.convSettingsChanged = False

View File

@@ -0,0 +1,828 @@
'''
conversational.py
Copyright (C) 2019 - 2025 Phillip A Carter
Copyright (C) 2020 - 2025 Gregory D Carl
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.
'''
import os
import re
from shutil import copy as COPY
from importlib import reload
from qtpy.QtCore import Qt, QCoreApplication
from qtpy.QtWidgets import QFileDialog, QMessageBox, QPushButton, QLabel, QLineEdit
from qtpy.QtWidgets import QComboBox
from qtvcp.core import Status, Action
from qtvcp.lib.qtplasmac import conv_settings as CONVSET
from qtvcp.lib.qtplasmac import conv_line as CONVLINE
from qtvcp.lib.qtplasmac import conv_circle as CONVCIRC
from qtvcp.lib.qtplasmac import conv_ellipse as CONVELLI
from qtvcp.lib.qtplasmac import conv_triangle as CONVTRIA
from qtvcp.lib.qtplasmac import conv_rectangle as CONVRECT
from qtvcp.lib.qtplasmac import conv_polygon as CONVPOLY
from qtvcp.lib.qtplasmac import conv_bolt as CONVBOLT
from qtvcp.lib.qtplasmac import conv_slot as CONVSLOT
from qtvcp.lib.qtplasmac import conv_star as CONVSTAR
from qtvcp.lib.qtplasmac import conv_gusset as CONVGUST
from qtvcp.lib.qtplasmac import conv_sector as CONVSECT
from qtvcp.lib.qtplasmac import conv_block as CONVBLCK
from rs274.glcanon import GlCanonDraw as DRAW
STATUS = Status()
ACTION = Action()
_translate = QCoreApplication.translate
gcodePattern = re.compile(
r"(;row(?P<OP>.[^X]+) *)?"
r"([Gg](?P<G1> *\d{1,2}) *)?"
r"([Gg](?P<G2> *\d{1,2}) *)?"
r"([Xx](?P<X> *-*\d+\.?\d*) *)?"
r"([Yy](?P<Y> *-*\d+\.?\d*) *)?"
r"([Zz](?P<Z>( *-*\d+\.?\d*)|([^;^(]*)) *)?"
r"([Ii](?P<I> *-*\d+\.?\d*) *)?"
r"([Jj](?P<J> *-*\d+\.?\d*) *)?"
r"([Mm](?P<M> *\d{1,3}) *)?"
r"([Pp](?P<P> *-*\d+\.?\d*) *)?"
r"([Qq](?P<Q> *-*\d+\.?\d*) *)?"
r"((?P<C>[;(].+) *)?"
)
def conv_setup(P, W):
P.convSettingsChanged = False
P.validShape = False
P.savedSettings = {'origin': None, 'intext': None, 'in': None, 'out': None}
P.invalidLeads = 0
P.isConvBlock = None
if not P.convWidgetsLoaded or P.developmentPin.get():
conv_widgets(P, W)
if not ACTION.prefilter_path:
W.undo.setEnabled(False)
conv_preview_button(P, W, False)
P.convButtonState = {}
P.convCommonButtons = ['new', 'save', 'send', 'settings']
for w in P.convCommonButtons:
P.convButtonState[w] = False
if P.unitsPerMm == 1:
P.unitCode = ['21', '0.25', 32]
W.conv_preview.setmetric(True)
else:
P.unitCode = ['20', '0.004', 1.26]
W.conv_preview.setmetric(False)
P.ambles = f'G{P.unitCode[0]}\nG64P{P.unitCode[1]}\nG40\nG49\nM52P1\nG80\nG90\nG92.1\nG94\nG97'
CONVSET.load(P, W)
# grid size is in inches
W.conv_preview.grid_size = P.gridSize / P.unitsPerMm / 25.4
W.conv_preview.set_current_view()
W.conv_new.setEnabled(True)
W.conv_save.setEnabled(False)
W.conv_send.setEnabled(False)
W.conv_settings.setEnabled(True)
if ACTION.prefilter_path and P.fileOpened:
W.conv_preview.load(P.filteredBkp)
machine = W.conv_preview.gcode_properties['machine_unit_sys']
gcode = W.conv_preview.gcode_properties['gcode_units']
if machine == 'Metric' and gcode == 'in':
gcode_convert_units(P.filteredBkp, P.fNgcBkp, W.conv_preview, P.unitsPerMm, '20', '21', 25.4, 25.4)
elif machine == 'Imperial' and gcode == 'mm':
gcode_convert_units(P.filteredBkp, P.fNgcBkp, W.conv_preview, P.unitsPerMm, '21', '20', 1, 1/25.4)
with open(P.filteredBkp, 'r') as blockCheck:
line = blockCheck.readline()
if line.startswith(';conversational block V2'):
P.isConvBlock = 'loaded'
W.conv_preview.set_current_view()
conv_enable_tabs(P, W)
COPY(P.filteredBkp, P.fNgc)
COPY(P.filteredBkp, P.fNgcBkp)
else:
with open(P.filteredBkp, 'w') as outNgc:
outNgc.write('(new conversational file)\nM2\n')
conv_new_pressed(P, W, None)
P.xOrigin = STATUS.get_position()[1][0]
P.yOrigin = STATUS.get_position()[1][1]
P.xSaved = '0.000'
P.ySaved = '0.000'
if P.isConvBlock:
conv_shape_request(P, W, 'conv_block')
elif P.oldConvButton and not P.oldConvButton == 'conv_block':
conv_shape_request(P, W, P.oldConvButton)
else:
conv_shape_request(P, W, 'conv_line')
def gcode_convert_units(file, bkp, window, unitsPerMm, oldG, newG, eMult, uMult):
COPY(file, bkp)
template = ''
inputs = False
with open(bkp, 'r') as inFile:
with open(file, 'w') as outFile:
for line in inFile:
line = line.strip()
if line and line[0] != '(':
if line[0] == ';':
if ';conversational block V2' in line:
template = ';'
elif ';CONV_BLOCK TEMPLATE END' in line:
template = ''
# if it is a conversational block
elif inputs:
values = line.lstrip(';').split(', ')
cSpacing = float(values[0]) * uMult
rSpacing = float(values[1]) * uMult
columns = int(values[2])
rows = int(values[3])
# set the converted values
values[0] = f"{cSpacing:0.4f}"
values[1] = f"{rSpacing:0.4f}"
values[4] = f"{float(values[4]) * uMult:0.4f}"
values[5] = f"{float(values[5]) * uMult:0.4f}"
if not float(values[11]) and not float(values[12]):
# get the overall extents
xMid = DRAW.extents_info(window)[0][0] * eMult - STATUS.stat.g5x_offset[0]
yMid = DRAW.extents_info(window)[0][1] * eMult - STATUS.stat.g5x_offset[1]
# get the midpoints of the first shape only
if columns > 1:
xMid -= (columns - 1) * cSpacing / 2
if rows > 1:
yMid -= (rows - 1) * rSpacing / 2
values[11] = f"{xMid:0.4f}"
values[12] = f"{yMid:0.4f}"
else:
values[11] = f"{float(values[11]) * uMult:0.4f}"
values[12] = f"{float(values[12]) * uMult:0.4f}"
line = f";{', '.join(values)}"
inputs = False
elif ';CONV_BLOCK INPUTS' in line:
inputs = True
line = line[1:] if template else line
code = gcodePattern.match(line).groupdict()
comment = code['C'].strip() if code['C'] else ''
originPoint = f";row{code['OP'].strip()}" if code['OP'] else ''
if originPoint:
line = f"{originPoint} X{float(code['X']) * uMult:0.4f} Y{float(code['Y']) * uMult:0.4f}"
if 'F[#<_hal[plasmac.cut-feed-rate]>' in line:
line = f"F#<_hal[plasmac.cut-feed-rate]> {comment}"
if code['G1'] == oldG:
line = line.replace(code['G1'], newG)
elif code['G1'] == '53' and '#<_ini[axis_z]max_limit>' in line:
line = f"G53 G00 Z[#<_ini[axis_z]max_limit> - {5.00 * unitsPerMm:0.4f}] {comment}"
elif code['G1'] == '64':
Q = float(code['Q']) if code['Q'] else 0.0
line = f"G{code['G1']} P{float(code['P']) * uMult:0.4f} Q{Q * uMult:0.4f} {comment}"
if code['X']:
line = line.replace(f"X{code['X']}", f"X{float(code['X']) * uMult:0.4f}")
if code['Y']:
line = line.replace(f"Y{code['Y']}", f"Y{float(code['Y']) * uMult:0.4f}")
if code['I']:
line = line.replace(f"I{code['I']}", f"I{float(code['I']) * uMult:0.4f}")
if code['J']:
line = line.replace(f"J{code['J']}", f"J{float(code['J']) * uMult:0.4f}")
line = template + line
outFile.write(f"{line}\n")
window.load(file)
def conv_new_pressed(P, W, button):
if button and (W.conv_save.isEnabled() or W.conv_send.isEnabled() or P.convPreviewActive or P.oldConvButton == 'conv_block'):
head = _translate('HandlerClass', 'Unsaved Shape')
btn1 = _translate('HandlerClass', 'CONTINUE')
btn2 = _translate('HandlerClass', 'CANCEL')
if P.oldConvButton == 'conv_block':
msg0 = _translate('HandlerClass', 'A loaded file from the MAIN tab is being previewed')
msg1 = _translate('HandlerClass', 'If you continue it will be removed from the Conversational preview')
else:
msg0 = _translate('HandlerClass', 'You have an unsaved, unsent, or active previewed shape')
msg1 = _translate('HandlerClass', 'If you continue it will be deleted')
if not P.dialog_show_yesno(QMessageBox.Warning, f'{head}', f'{msg0}\n\n{msg1}\n', f'{btn1}', f'{btn2}'):
return
if P.oldConvButton == 'conv_line' and button:
if W.lType.currentText() == _translate('Conversational', 'LINE POINT ~ POINT'):
CONVLINE.set_line_point_to_point(P, W)
elif W.lType.currentText() == _translate('Conversational', 'LINE BY ANGLE'):
CONVLINE.set_line_by_angle(P, W)
elif W.lType.currentText() == _translate('Conversational', 'ARC 3P'):
CONVLINE.set_arc_3_points(P, W)
elif W.lType.currentText() == _translate('Conversational', 'ARC 2P +RADIUS'):
CONVLINE.set_arc_2_points_radius(P, W)
elif W.lType.currentText() == _translate('Conversational', 'ARC ANGLE +RADIUS'):
CONVLINE.set_arc_by_angle_radius(P, W)
W.entry1.setText('0.000')
W.entry2.setText('0.000')
with open(P.fNgc, 'w') as outNgc:
outNgc.write('(new conversational file)\nM2\n')
COPY(P.fNgc, P.fTmp)
COPY(P.fNgc, P.fNgcBkp)
W.conv_preview.load(P.fNgc)
W.conv_save.setEnabled(False)
W.conv_send.setEnabled(False)
P.validShape = False
conv_preview_button(P, W, False)
conv_enable_tabs(P, W)
if P.oldConvButton == 'conv_block':
conv_shape_request(P, W, 'conv_line')
P.isConvBlock = None
def conv_save_pressed(P, W):
head = _translate('HandlerClass', 'Save Error')
with open(P.fNgc, 'r') as inFile:
for line in inFile:
if '(new conversational file)' in line:
msg0 = _translate('HandlerClass', 'An empty file cannot be saved')
P.dialog_show_ok(QMessageBox.Warning, f'{head}', f'{msg0}\n')
return
P.vkb_show()
dlg = QFileDialog(W)
dlg.setOptions(QFileDialog.DontUseNativeDialog)
dlg.setAcceptMode(QFileDialog.AcceptSave)
dlg.setNameFilters(['G-Code Files (*.ngc *.nc *.tap)', 'All Files (*)'])
dlg.setDefaultSuffix('ngc')
dlg.setDirectory(P.programPrefix)
name = ''
if dlg.exec():
name = dlg.selectedFiles()[0]
if name:
COPY(P.fNgc, name)
W.conv_save.setEnabled(False)
conv_enable_tabs(P, W)
P.vkb_show(True)
def conv_settings_pressed(P, W):
W.conv_material.hide()
P.color_item(P.oldConvButton, P.foreColor, 'button')
W[P.oldConvButton].setStyleSheet(f'QPushButton {{ background: {P.backColor} }} \
QPushButton:pressed {{ background: {P.backColor} }}')
for w in P.convCommonButtons:
P.convButtonState[w] = W[f'conv_{w}'].isEnabled()
W[f'conv_{w}'].setEnabled(False)
conv_clear_widgets(P, W, True)
if P.developmentPin.get():
reload(CONVSET)
CONVSET.widgets(P, W, P.CONV)
CONVSET.show(P, W)
def conv_send_pressed(P, W):
COPY(P.fNgcBkp, P.fNgcSent)
W.conv_send.setEnabled(False)
W.conv_save.setEnabled(False)
conv_enable_tabs(P, W)
P.vkb_hide()
ACTION.OPEN_PROGRAM(P.fNgcSent)
def conv_block_pressed(P, W):
if not P.convSettingsChanged:
if P.convPreviewActive and not conv_active_shape(P, W):
return
head = _translate('HandlerClass', 'Array Error')
with open(P.fNgc) as inFile:
for line in inFile:
if '(new conversational file)' in line:
msg0 = _translate('HandlerClass', 'An empty file cannot be arrayed, rotated, or scaled')
P.dialog_show_ok(QMessageBox.Warning, f'{head}', f'{msg0}\n')
return
# see if we can do something about NURBS blocks down the track
# elif 'g5.2' in line.lower() or 'g5.3' in line.lower():
# head = _translate('HandlerClass', 'Scale Error')
# msg0 = _translate('HandlerClass', 'Cannot scale a GCode NURBS block')
# P.dialog_show_ok(QMessageBox.Warning, f'{head}', f'{msg0}\n\n{line}')
# return
elif 'M3' in line.upper() or 'M03' in line.upper():
break
conv_shape_request(P, W, W.sender().objectName())
def conv_shape_request(P, W, shape):
if shape == 'conv_line':
module = CONVLINE
elif shape == 'conv_circle':
module = CONVCIRC
elif shape == 'conv_ellipse':
module = CONVELLI
elif shape == 'conv_triangle':
module = CONVTRIA
elif shape == 'conv_rectangle':
module = CONVRECT
elif shape == 'conv_polygon':
module = CONVPOLY
elif shape == 'conv_bolt':
module = CONVBOLT
elif shape == 'conv_slot':
module = CONVSLOT
elif shape == 'conv_star':
module = CONVSTAR
elif shape == 'conv_gusset':
module = CONVGUST
elif shape == 'conv_sector':
module = CONVSECT
elif shape == 'conv_block':
module = CONVBLCK
else:
return
if P.developmentPin.get():
reload(module)
if not P.convSettingsChanged:
if P.convPreviewActive and not conv_active_shape(P, W):
return
conv_preview_button(P, W, False)
if shape == 'conv_block':
W.conv_material.hide()
if P.isConvBlock:
conv_shape_buttons(W, False)
else:
conv_shape_buttons(W, True)
else:
W.conv_material.show()
conv_shape_buttons(W, True)
# we use exception handlers here as there may be no signals connected
try:
W.conv_material.currentTextChanged.disconnect()
except:
pass
try:
W.preview.pressed.disconnect()
except:
pass
try:
W.undo.pressed.disconnect()
except:
pass
conv_button_color(P, W, shape)
W.conv_settings.setEnabled(True)
W.preview.setEnabled(True)
W.loLabel.setEnabled(True)
W.loEntry.setEnabled(True)
if P.validShape:
W.undo.setEnabled(True)
W.add.setEnabled(False)
conv_clear_widgets(P, W)
# common starting parameters
if P.convSettingsChanged == 0:
W.intExt.setText('EXTERNAL')
P.intExt = True
if P.convSettingsChanged <= 1:
if P.origin:
W.centLeft.setText('CENTER')
else:
W.centLeft.setText('BTM LEFT')
W.liEntry.setText(f'{P.leadIn}')
W.loEntry.setText(f'{P.leadOut}')
# call the shape
module.widgets(P, W, P.CONV)
P.convSettingsChanged = False
def conv_preview_button(P, W, state):
if state and P.oldConvButton == 'conv_block':
conv_shape_buttons(W, False)
P.convPreviewActive = state
conv_enable_tabs(P, W)
if state:
W.preview.setStyleSheet(f'QPushButton {{ color: {P.estopColor} }} \
QPushButton:disabled {{ color: {P.disabledColor} }}')
W.conv_save.setEnabled(False)
W.conv_send.setEnabled(False)
W.undo.setText(_translate('HandlerClass', 'UNDO'))
else:
W.preview.setStyleSheet(f'QPushButton {{ color: {P.foreColor} }} \
QPushButton:disabled {{ color: {P.disabledColor} }}')
if P.validShape:
W.conv_save.setEnabled(True)
W.conv_send.setEnabled(True)
W.undo.setText(_translate('HandlerClass', 'RELOAD'))
if P.convWidgetsLoaded:
W.add.setEnabled(False)
def conv_shape_buttons(W, state):
buttons = ['line', 'circle', 'ellipse', 'triangle', 'rectangle', 'polygon', 'bolt', 'slot', 'star', 'gusset', 'sector']
for button in buttons:
W[f'conv_{button}'].setEnabled(state)
def conv_active_shape(P, W):
btn1 = _translate('HandlerClass', 'CONTINUE')
btn2 = _translate('HandlerClass', 'CANCEL')
head = _translate('HandlerClass', 'Active Preview')
msg0 = _translate('HandlerClass', 'You have an active previewed shape')
msg1 = _translate('HandlerClass', 'If you continue it will be deleted')
response = P.dialog_show_yesno(QMessageBox.Warning, f'{head}', f'{msg0}\n\n{msg1}\n', f'{btn1}', f'{btn2}')
if response:
conv_undo_shape(P, W)
conv_preview_button(P, W, False)
return response
def conv_button_color(P, W, button):
if P.oldConvButton:
P.color_item(P.oldConvButton, P.foreColor, 'button')
W[P.oldConvButton].setStyleSheet(f'QPushButton {{ background: {P.backColor} }} \
QPushButton:pressed {{ background: {P.backColor} }}')
P.oldConvButton = button
P.color_item(button, P.backColor, 'button')
W[button].setStyleSheet(f'QPushButton {{ background: {P.foreColor} }} \
QPushButton:pressed {{ background: {P.foreColor} }}')
def conv_restore_buttons(P, W):
for button in P.convCommonButtons:
W[f'conv_{button}'].setEnabled(P.convButtonState[button])
def conv_enable_tabs(P, W):
if W.conv_save.isEnabled() or P.convPreviewActive:
for n in range(W.main_tab_widget.count()):
if n != 1:
W.main_tab_widget.setTabEnabled(n, False)
else:
for n in range(W.main_tab_widget.count()):
W.main_tab_widget.setTabEnabled(n, True)
# enabling tabs causes issues with the gcode widgets margin styles
# so we refresh the style here as a workaround
W.gcode_editor.setStyleSheet(f'EditorBase{{ qproperty-styleColorMarginText: {P.foreColor} }}')
W.gcode_display.setStyleSheet(f'EditorBase{{ qproperty-styleColorMarginText: {P.foreColor} }}')
def conv_entry_changed(P, W, widget, circleType=False):
if widget:
name = widget.objectName()
value = widget.text()
else:
name = value = None
# circle specific code
if circleType:
P.invalidLeads = 0
dia = W.hdEntry.text() if circleType == 'bolt' else W.dEntry.text()
try:
dia = float(dia)
except:
dia = 0
# cannot do overcut if large hole, no hole, or external circle
if dia >= P.holeDiameter or dia == 0 or (P.intExt and circleType != 'bolt'):
W.overcut.setChecked(False)
W.overcut.setEnabled(False)
W.ocEntry.setEnabled(False)
else:
W.overcut.setEnabled(True)
W.ocEntry.setEnabled(True)
# cannot do leadout if small hole
if not P.intExt or circleType == 'bolt':
if dia < P.holeDiameter:
W.loLabel.setEnabled(False)
W.loEntry.setEnabled(False)
P.invalidLeads = 2
else:
# test for large leadin or leadout
try:
lIn = float(W.liEntry.text())
except:
lIn = 0
try:
lOut = float(W.loEntry.text())
except:
lOut = 0
if lIn and lIn > dia / 4:
W.loLabel.setEnabled(False)
W.loEntry.setEnabled(False)
P.invalidLeads = 2
elif lOut and lOut > dia / 4:
W.loLabel.setEnabled(False)
P.invalidLeads = 1
else:
W.loLabel.setEnabled(True)
W.loEntry.setEnabled(True)
P.invalidLeads = 0
else:
W.loLabel.setEnabled(True)
W.loEntry.setEnabled(True)
P.invalidLeads = 0
if value:
cursor_position = widget.cursorPosition()
if name in ['intEntry', 'hsEntry', 'cnEntry', 'rnEntry']:
good = '0123456789'
elif name in ['xsEntry', 'ysEntry', 'aEntry', 'csEntry', 'rsEntry', 'neg']:
good = '-.0123456789'
else:
good = '.0123456789'
out = ''
for t in value:
if t in good and not(t == '-' and len(out) > 0) and not(t == '.' and t in out):
out += t
widget.setText(out)
widget.setCursorPosition(cursor_position)
if value in ['', '.', '-', '-.']:
return True
try:
float(value)
reply = False
except:
widget.setCursorPosition(cursor_position - 1)
reply = True
if not reply and name == 'gsEntry':
# grid size is in inches
W.conv_preview.grid_size = float(value) / P.unitsPerMm / 25.4
W.conv_preview.set_current_view()
return reply
else:
return True
def conv_is_float(entry):
try:
return True, float(entry)
except:
reply = -1 if entry else 0
return False, reply
def conv_is_int(entry):
try:
return True, int(entry)
except:
reply = -1 if entry else 0
return False, reply
def conv_undo_shape(P, W):
# setup for a reload if required
if not P.convPreviewActive:
head = _translate('HandlerClass', 'Reload Request')
btn1 = _translate('HandlerClass', 'CONTINUE')
btn2 = _translate('HandlerClass', 'CANCEL')
if P.fileOpened:
name = os.path.basename(ACTION.prefilter_path)
msg0 = _translate('HandlerClass', 'The original file will be loaded')
msg1 = _translate('HandlerClass', 'If you continue all changes will be deleted')
if not P.dialog_show_yesno(QMessageBox.Warning, f'{head}', f'{msg0}:\n\n{name}\n\n{msg1}\n', f'{btn1}', f'{btn2}'):
return(True)
else:
msg0 = _translate('HandlerClass', 'An empty file will be loaded')
msg1 = _translate('HandlerClass', 'If you continue all changes will be deleted')
if not P.dialog_show_yesno(QMessageBox.Warning, f'{head}', f'{msg0}\n\n{msg1}\n', f'{btn1}', f'{btn2}'):
return(True)
P.validShape = False
W.preview.setEnabled(True)
W.undo.setEnabled(False)
W.conv_save.setEnabled(False)
W.conv_send.setEnabled(False)
# undo the shape
if os.path.exists(P.fNgcBkp) and W.undo.text() == 'UNDO':
COPY(P.fNgcBkp, P.fNgc)
elif os.path.exists(P.filteredBkp) and W.undo.text() == 'RELOAD':
COPY(P.filteredBkp, P.fNgc)
COPY(P.filteredBkp, P.fNgcBkp)
else:
return
W.conv_preview.load(P.fNgc)
W.conv_preview.set_current_view()
W.add.setEnabled(False)
if not P.validShape:
W.undo.setEnabled(False)
conv_preview_button(P, W, False)
conv_enable_tabs(P, W)
if P.isConvBlock == 'created':
P.isConvBlock = None
conv_shape_buttons(W, True)
def conv_add_shape_to_file(P, W):
COPY(P.fNgc, P.fNgcBkp)
try:
if W.xsEntry.text():
P.xSaved = W.xsEntry.text()
except:
pass
try:
if W.ysEntry.text():
P.ySaved = W.ysEntry.text()
except:
pass
# try:
# P.oSaved = W.centLeft.isChecked()
# except:
# pass
P.validShape = True
W.add.setEnabled(False)
W.conv_save.setEnabled(True)
W.conv_send.setEnabled(True)
conv_preview_button(P, W, False)
conv_enable_tabs(P, W)
def conv_accept(P, W):
P.validShape = True
conv_preview_button(P, W, False)
COPY(P.fNgc, P.fNgcBkp)
W.conv_preview.load(P.fNgc)
W.add.setEnabled(False)
W.conv_save.setEnabled(True)
W.conv_send.setEnabled(True)
conv_enable_tabs(P, W)
def conv_clear_widgets(P, W, settings=False):
for i in reversed(range(W.entries.count())):
widget = W.entries.itemAt(i).widget()
try:
widget.disconnect()
except:
pass
name = widget.objectName()
if settings:
if name == 'liEntry':
P.savedSettings['in'] = widget.text()
if name == 'loEntry':
P.savedSettings['out'] = widget.text()
if name == 'centLeft':
P.savedSettings['origin'] = widget.text()
if name == 'intExt':
P.savedSettings['intext'] = widget.text()
else:
if isinstance(widget, QLineEdit) and \
name not in ['liEntry', 'loEntry', 'xsEntry', 'ysEntry']:
widget.setText('')
if name in ['aEntry', 'oxEntry', 'oyEntry', 'rtEntry', 'csEntry', 'rsEntry']:
widget.setText('0.0')
elif name in ['caEntry']:
widget.setText('360')
elif name in ['cnEntry', 'rnEntry']:
widget.setText('1')
elif name in ['scEntry']:
widget.setText('1.0')
elif name in ['ocEntry']:
widget.setText(f'{4 * P.unitsPerMm}')
W.entries.removeWidget(widget)
widget.setParent(None)
def conv_auto_preview_button(P, W, button):
if button == 'intext':
text = 'INTERNAL' if W.intExt.text() == 'EXTERNAL' else 'EXTERNAL'
W.intExt.setText(text)
P.intExt = True if text == 'EXTERNAL' else False
W.intExt.setChecked(False)
elif button == 'center':
text = 'CENTER' if W.centLeft.text() == 'BTM LEFT' else 'BTM LEFT'
W.centLeft.setText(text)
W.centLeft.setChecked(False)
def conv_widgets(P, W):
''' create all required widgets without showing them '''
# common
W.preview = QPushButton(_translate('Conversational', 'PREVIEW'))
W.preview.setFocusPolicy(Qt.ClickFocus)
W.undo = QPushButton(_translate('Conversational', 'RELOAD'))
W.undo.setFocusPolicy(Qt.ClickFocus)
W.centLeft = QPushButton(_translate('Conversational', 'BTM LEFT'), objectName='centLeft')
W.centLeft.setFocusPolicy(Qt.ClickFocus)
W.centLeft.setCheckable(True)
W.intExt = QPushButton(_translate('Conversational', 'EXTERNAL'), objectName='intExt')
W.intExt.setFocusPolicy(Qt.ClickFocus)
W.intExt.setCheckable(True)
W.liLabel = QLabel(_translate('Conversational', 'LEAD IN'))
W.liEntry = QLineEdit(objectName='liEntry')
W.loLabel = QLabel(_translate('Conversational', 'LEAD OUT'))
W.loEntry = QLineEdit(objectName='loEntry')
W.ctLabel = QLabel(_translate('Conversational', 'CUT TYPE'))
W.spLabel = QLabel(_translate('Conversational', 'START'))
W.xsLabel = QLabel(_translate('Conversational', 'X ORIGIN'))
W.xsEntry = QLineEdit('0.000', objectName='xsEntry')
W.ysLabel = QLabel(_translate('Conversational', 'Y ORIGIN'))
W.ysEntry = QLineEdit('0.000', objectName='ysEntry')
W.overcut = QPushButton(_translate('Conversational', 'OVER CUT'))
W.overcut.setFocusPolicy(Qt.ClickFocus)
W.overcut.setEnabled(False)
W.overcut.setCheckable(True)
W.ocLabel = QLabel(_translate('Conversational', 'OC LENGTH'))
W.ocEntry = QLineEdit(objectName='ocEntry')
W.ocEntry.setEnabled(False)
W.ocEntry.setText(f'{4 * P.unitsPerMm}')
W.add = QPushButton(_translate('Conversational', 'ADD'))
W.add.setFocusPolicy(Qt.ClickFocus)
W.lDesc = QLabel('')
W.iLabel = QLabel()
W.iLabel.setAlignment(Qt.AlignRight | Qt.AlignTop)
W.aLabel = QLabel(_translate('Conversational', 'ANGLE'))
W.aEntry = QLineEdit('0.0', objectName='aEntry')
W.dLabel = QLabel(_translate('Conversational', 'DIAMETER'))
W.dEntry = QLineEdit(objectName='')
W.hdLabel = QLabel(_translate('Conversational', 'HOLE DIA'))
W.hdEntry = QLineEdit()
W.hLabel = QLabel('') # shared with different uses
W.hEntry = QLineEdit() # shared with different uses
W.caLabel = QLabel(_translate('Conversational', 'CIRCLE ANG'))
W.caEntry = QLineEdit('360', objectName='caEntry')
W.wLabel = QLabel(_translate('Conversational', 'WIDTH'))
W.wEntry = QLineEdit(objectName='')
W.rLabel = QLabel(_translate('Conversational', 'RADIUS'))
W.rButton = QPushButton(_translate('Conversational', 'RADIUS'))
W.rButton.setFocusPolicy(Qt.ClickFocus)
W.rEntry = QLineEdit('')
W.sLabel = QLabel() # shared with different uses
W.sEntry = QLineEdit() # shared with different uses
W.mCombo = QComboBox()
W.mCombo.setFocusPolicy(Qt.ClickFocus)
W.mCombo.addItem(_translate('Conversational', 'CIRCUMSCRIBED'))
W.mCombo.addItem(_translate('Conversational', 'INSCRIBED'))
W.mCombo.addItem(_translate('Conversational', 'SIDE LENGTH'))
W.r1Button = QPushButton(_translate('Conversational', 'RADIUS 1'))
W.r1Button.setFocusPolicy(Qt.ClickFocus)
W.r1Entry = QLineEdit()
W.r2Button = QPushButton(_translate('Conversational', 'RADIUS 2'))
W.r2Button.setFocusPolicy(Qt.ClickFocus)
W.r2Entry = QLineEdit()
W.r3Button = QPushButton(_translate('Conversational', 'RADIUS 3'))
W.r3Button.setFocusPolicy(Qt.ClickFocus)
W.r3Entry = QLineEdit()
W.r4Button = QPushButton(_translate('Conversational', 'RADIUS 4'))
W.r4Button.setFocusPolicy(Qt.ClickFocus)
W.r4Entry = QLineEdit()
W.lLabel = QLabel(_translate('Conversational', 'LENGTH'))
W.lEntry = QLineEdit()
W.pLabel = QLabel(_translate('Conversational', 'POINTS'))
W.pEntry = QLineEdit(objectName='intEntry')
W.odLabel = QLabel(_translate('Conversational', 'OUTER DIA'))
W.odEntry = QLineEdit()
W.idLabel = QLabel(_translate('Conversational', 'INNER DIA'))
W.idEntry = QLineEdit()
W.shLabel = QLabel(_translate('Conversational', 'SHAPE')) # shared with different uses
# triangle
W.AaLabel = QLabel(_translate('Conversational', 'A ANGLE'))
W.AaEntry = QLineEdit()
W.BaLabel = QLabel(_translate('Conversational', 'B ANGLE'))
W.BaEntry = QLineEdit()
W.CaLabel = QLabel(_translate('Conversational', 'C ANGLE'))
W.CaEntry = QLineEdit()
W.AlLabel = QLabel(_translate('Conversational', 'a LENGTH'))
W.AlEntry = QLineEdit()
W.BlLabel = QLabel(_translate('Conversational', 'b LENGTH'))
W.BlEntry = QLineEdit()
W.ClLabel = QLabel(_translate('Conversational', 'c LENGTH'))
W.ClEntry = QLineEdit()
# block
W.ccLabel = QLabel(_translate('Conversational', 'COLUMNS'))
W.cnLabel = QLabel(_translate('Conversational', 'NUMBER'))
W.cnEntry = QLineEdit('1', objectName='cnEntry')
W.csEntry = QLineEdit('0.0', objectName='csEntry')
W.csLabel = QLabel(_translate('Conversational', 'SPACING'))
W.rrLabel = QLabel(_translate('Conversational', 'ROWS'))
W.rnLabel = QLabel(_translate('Conversational', 'NUMBER'))
W.rnEntry = QLineEdit('1', objectName='rnEntry')
W.rsEntry = QLineEdit('0.0', objectName='rsEntry')
W.rsLabel = QLabel(_translate('Conversational', 'SPACING'))
W.oLabel = QLabel(_translate('Conversational', 'ORIGIN'))
W.oxLabel = QLabel(_translate('Conversational', 'X OFFSET'))
W.oxEntry = QLineEdit('0.0', objectName='xsEntry')
W.oyEntry = QLineEdit('0.0', objectName='ysEntry')
W.oyLabel = QLabel(_translate('Conversational', 'Y OFFSET'))
W.ptLabel = QLabel(_translate('Conversational', 'PATTERN'))
W.scLabel = QLabel(_translate('Conversational', 'SCALE'))
W.scEntry = QLineEdit('1.0', objectName='scEntry')
W.rtEntry = QLineEdit('0.0', objectName='aEntry')
W.rtLabel = QLabel(_translate('Conversational', 'ROTATION'))
W.mirror = QPushButton(_translate('Conversational', 'MIRROR'))
W.mirror.setFocusPolicy(Qt.ClickFocus)
W.flip = QPushButton(_translate('Conversational', 'FLIP'))
W.flip.setFocusPolicy(Qt.ClickFocus)
# lines and arcs
W.lType = QComboBox()
W.lType.setFocusPolicy(Qt.ClickFocus)
W.label1 = QLabel()
W.entry1 = QLineEdit(objectName='neg')
W.label2 = QLabel()
W.entry2 = QLineEdit(objectName='neg')
W.label3 = QLabel()
W.entry3 = QLineEdit()
W.label4 = QLabel()
W.entry4 = QLineEdit(objectName='neg')
W.label5 = QLabel()
W.entry5 = QLineEdit()
W.label6 = QLabel()
W.entry6 = QLineEdit(objectName='neg')
W.g23Arc = QPushButton('CW - G2')
W.g23Arc.setFocusPolicy(Qt.ClickFocus)
W.g23Arc.setCheckable(True)
# settings
W.preLabel = QLabel(_translate('Conversational', 'PREAMBLE'))
W.preEntry = QLineEdit()
W.pstLabel = QLabel(_translate('Conversational', 'POSTAMBLE'))
W.pstEntry = QLineEdit()
W.llLabel = QLabel(_translate('Conversational', 'LEAD LENGTHS'))
W.shEntry = QLineEdit()
W.hsEntry = QLineEdit()
W.hsLabel = QLabel(_translate('Conversational', 'SPEED %'))
W.pvLabel = QLabel(_translate('Conversational', 'PREVIEW'))
W.gsLabel = QLabel(_translate('Conversational', 'GRID SIZE'))
W.gsEntry = QLineEdit(objectName='gsEntry')
W.save = QPushButton(_translate('Conversational', 'SAVE'))
W.save.setFocusPolicy(Qt.ClickFocus)
W.reload = QPushButton(_translate('Conversational', 'RELOAD'))
W.reload.setFocusPolicy(Qt.ClickFocus)
W.cExit = QPushButton(_translate('Conversational', 'EXIT'))
W.cExit.setFocusPolicy(Qt.ClickFocus)
if not W.lType.count():
W.lType.addItem(_translate('Conversational', 'LINE POINT ~ POINT'))
W.lType.addItem(_translate('Conversational', 'LINE BY ANGLE'))
W.lType.addItem(_translate('Conversational', 'ARC 3P'))
W.lType.addItem(_translate('Conversational', 'ARC 2P +RADIUS'))
W.lType.addItem(_translate('Conversational', 'ARC ANGLE +RADIUS'))
if not W.mCombo.count():
W.mCombo.addItem(_translate('Conversational', 'CIRCUMSCRIBED'))
W.mCombo.addItem(_translate('Conversational', 'INSCRIBED'))
W.mCombo.addItem(_translate('Conversational', 'SIDE LENGTH'))
P.convWidgetsLoaded = True

View File

@@ -0,0 +1,670 @@
'''
interlock_rules.py
Copyright (C) 2020-2026 Gregory D Carl
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.
'''
INTERLOCK_RULES = {
# MAIN tab
'touch_xy': {
'all': {
'all_homed': True,
'estop_cleared': True,
'interp_idle': True,
'laser_button_state': True,
'manual_cut_active': False,
'machine_on': True,
'offsets_active': False,
'ohmic_test': False,
'previewstack_is_camera': False,
'previewstack_is_edit': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'probe_test': False,
'single_cut_dialog': False
}
},
'wcs_button': {
'all': {
'all_homed': True,
'estop_cleared': True,
'interp_idle': True,
'manual_cut_active': False,
'machine_on': True,
'offsets_active': False,
'ohmic_test': False,
'previewstack_is_edit': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'probe_test': False,
'single_cut_dialog': False
}
},
'camera': {
'all': {
'all_homed': True,
'estop_cleared': True,
'interp_idle': True,
'laser_button_state': True,
'manual_cut_active': False,
'machine_on': True,
'offsets_active': False,
'ohmic_test': False,
'probe_test': False,
'previewstack_is_edit': False,
'previewstack_is_offsets': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'single_cut_dialog': False
}
},
'laser': {
'all': {
'all_homed': True,
'consumable_changing': False,
'estop_cleared': True,
'manual_cut_active': False,
'machine_on': True,
'offsets_active': False,
'ohmic_test': False,
'previewstack_is_preview': True,
'probe_test': False,
'single_cut_dialog': False
},
'any': {
'interp_idle': True,
'interp_paused': True
}
},
'mdi_show': {
'all': {
'all_homed': True,
'estop_cleared': True,
'interp_idle': True,
'manual_cut_active': False,
'machine_on': True,
'ohmic_test': False,
'previewstack_is_open': False,
'single_cut_dialog': False
}
},
'height_lower': {
'all': {
'all_homed': True,
'estop_cleared': True,
'manual_cut_active': False,
'machine_on': True,
'ohmic_test': False,
'previewstack_is_edit': False,
'previewstack_is_offsets': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'single_cut_dialog': False
},
'any': {'interp_idle': True,
'interp_running': True
}
},
'height_raise': {
'all': {
'all_homed': True,
'estop_cleared': True,
'manual_cut_active': False,
'machine_on': True,
'ohmic_test': False,
'previewstack_is_edit': False,
'previewstack_is_offsets': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'single_cut_dialog': False
},
'any': {'interp_idle': True,
'interp_running': True
}
},
'power': {
'all': {
'estop_cleared': True
}
},
'run': {
'all': {
'all_homed': True,
'consumable_changing': False,
'file_bounds_error': False,
'file_opened': True,
'framing': False,
'interp_idle': True,
'machine_on': True,
'plasmac_idle': True,
'previewstack_is_preview': True,
'probe_bounds_error': False,
'probe_test': False,
'offsets_active': False,
'ohmic_test': False,
'torch_pulse': False,
'single_cut_dialog': False
},
'any': {
'interp_running': False
}
},
'pause_resume': {
'all': {
'consumable_changing': False,
'torch_pulse': False
},
'any': {
'interp_paused': True,
'interp_running': True
}
},
'abort': {
'all': {
},
'any': {
'framing': True,
'interp_paused': True,
'interp_running': True,
'manual_cut_active': True,
'probe_test': True,
'torch_pulse': True
}
},
'jog_frame': {
'all': {
'estop_cleared': True,
'machine_on': True,
'gcodestack_is_mdi': False,
'interp_idle': True,
'previewstack_is_edit': False,
'previewstack_is_offsets': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'probe_test': False,
'torch_pulse': False
}
},
'jog_slider': {
'all': {
'estop_cleared': True,
'machine_on': True,
'interp_idle': True,
'probe_test': False,
'torch_pulse': False,
'manual_cut_active': False
}
},
'jogs_label': {
'all': {
'estop_cleared': True,
'machine_on': True,
'interp_idle': True,
'probe_test': False,
'torch_pulse': False,
'manual_cut_active': False
}
},
'jog_slow': {
'all': {
'estop_cleared': True,
'machine_on': True,
'interp_idle': True,
'probe_test': False,
'torch_pulse': False,
'manual_cut_active': False
}
},
'jogincrements': {
'all': {
'estop_cleared': True,
'machine_on': True,
'interp_idle': True,
'probe_test': False,
'torch_pulse': False,
'manual_cut_active': False
}
},
'material_label': {
'all': {
'interp_idle': True,
'probe_test': False,
'torch_pulse': False,
'manual_cut_active': False
}
},
'material_selector': {
'all': {
'interp_idle': True,
'probe_test': False,
'torch_pulse': False,
'manual_cut_active': False
}
},
'feed_label': {
'all': {
'estop_cleared': True
}
},
'rapid_label': {
'all': {
'estop_cleared': True
}
},
'cut_rec_cancel': {
'all': {
'consumable_changing': False,
'interp_paused': True,
'offsets_active': True
},
'any': {
}
},
# SETTINGS tab
'ub_save': {
'all': {
'interp_running': False,
'probe_test': False,
'torch_pulse': False,
'manual_cut_active': False
}
},
'ub_reload': {
'all': {
'interp_running': False,
'probe_test': False,
'torch_pulse': False,
'manual_cut_active': False
}
},
# user button templates
'toggle-laser_template': {
'all': {
'all_homed': True,
'estop_cleared': True,
'interp_idle': True,
'manual_cut_active': False,
'machine_on': True,
'ohmic_test': False,
'previewstack_is_edit': False,
'previewstack_is_offsets': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'probe_test': False,
'single_cut_dialog': False,
'torch_pulse': False
}
},
'change-consumables_template': {
'all': {
'all_homed': True,
'estop_cleared': True,
'manual_cut_active': False,
'machine_on': True,
'offsets_active': False,
'ohmic_test': False,
'single_cut_dialog': False,
'interp_paused': True
},
'override': {
'consumable_change': True
}
},
'probe-test_template': {
'all': {
'all_homed': True,
'estop_cleared': True,
'interp_idle': True,
'manual_cut_active': False,
'machine_on': True,
'offsets_active': False,
'ohmic_test': False,
'previewstack_is_edit': False,
'previewstack_is_offsets': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'single_cut_dialog': False
},
'override': {
'probe_test': True
}
},
'torch-pulse_template': {
'all': {
'consumable_changing': False,
'estop_cleared': True,
'manual_cut_active': False,
'machine_on': True,
'ohmic_test': False,
'previewstack_is_edit': False,
'previewstack_is_offsets': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'probe_test': False,
'torch_enable': True,
'single_cut_dialog': False
},
'any': {
'interp_idle': True,
'interp_paused': True
}
},
'ohmic-test_template': {
'all': {
'consumable_changing': False,
'estop_cleared': True,
'manual_cut_active': False,
'machine_on': True,
'ohmic_probe_enable': True,
'previewstack_is_edit': False,
'previewstack_is_offsets': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'probe_test': False,
'single_cut_dialog': False
},
'any': {
'interp_idle': True,
'interp_paused': True
}
},
'framing_template': {
'all': {
'all_homed': True,
'estop_cleared': True,
'file_bounds_error': False,
'gcode_loaded': True,
'interp_idle': True,
'manual_cut_active': False,
'machine_on': True,
'ohmic_test': False,
'previewstack_is_edit': False,
'previewstack_is_offsets': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'probe_bounds_error': False,
'rfl_dialog': False,
'single_cut_dialog': False
}
},
'cut-type_template': {
'all': {
'estop_cleared': True,
'interp_idle': True,
'manual_cut_active': False,
'machine_on': True,
'ohmic_test': False,
'previewstack_is_edit': False,
'previewstack_is_offsets': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'single_cut_dialog': False
}
},
'single-cut_template': {
'all': {
'all_homed': True,
'estop_cleared': True,
'file_bounds_error': False,
'interp_idle': True,
'manual_cut_active': False,
'machine_on': True,
'offsets_active': False,
'ohmic_test': False,
'previewstack_is_preview': True,
'probe_test': False,
'probe_bounds_error': False,
'single_cut_dialog': False
}
},
'manual-cut_template': {
'all': {
'all_homed': True,
'estop_cleared': True,
'interp_idle': True,
'machine_on': True,
'offsets_active': False,
'ohmic_test': False,
'previewstack_is_preview': True,
'probe_test': False,
'single_cut_dialog': False
},
'override': {
'manual_cut_active': True
}
},
'load_template': {
'all': {
'estop_cleared': True,
'interp_idle': True,
'manual_cut_active': False,
'machine_on': True,
'ohmic_test': False,
'previewstack_is_edit': False,
'previewstack_is_offsets': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'single_cut_dialog': False
}
},
'toggle-halpin_template': {
'all': {
'machine_on': True
}
},
'pulse-halpin_template': {
'all': {
'machine_on': True
}
},
'offsets-view_template': {
'all': {
'interp_idle': True,
'manual_cut_active': False,
'single_cut_dialog': False
}
},
'latest-file_template': {
'all': {
'interp_idle': True,
'manual_cut_active': False,
'single_cut_dialog': False
}
},
'user-manual_template': {
'all': {
'interp_idle': True,
'manual_cut_active': False,
'single_cut_dialog': False
}
},
'toggle-joint_template': {
'all': {
'all_homed': True,
'estop_cleared': True,
'interp_idle': True,
'manual_cut_active': False,
'machine_on': True,
'ohmic_test': False,
'previewstack_is_edit': False,
'previewstack_is_offsets': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'single_cut_dialog': False
}
},
'dual-code_template': {
'all': {
'all_homed': True,
'estop_cleared': True,
'interp_idle': True,
'manual_cut_active': False,
'machine_on': True,
'ohmic_test': False,
'previewstack_is_edit': False,
'previewstack_is_offsets': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'probe_test': False,
'single_cut_dialog': False,
'torch_pulse': False
}
},
'always-on_template': {
'all': {
}
},
'main_tab': {
'all': {
# main tab is always active
}
},
'conversational_tab': {
'all': {
'interp_idle': True,
'manual_cut_active': False,
'offsets_active': False,
'probe_test': False
}
},
'parameters_tab': {
'all': {
'manual_cut_active': False,
'offsets_active': False,
'probe_test': False,
},
'any': {
'interp_idle': True,
'interp_paused': True
}
},
'settings_tab': {
'all': {
'manual_cut_active': False,
'offsets_active': False,
'probe_test': False,
},
'any': {
'interp_idle': True,
'interp_paused': True
}
},
'statistics_tab': {
'all': {
'manual_cut_active': False,
'offsets_active': False,
'probe_test': False,
},
'any': {
'interp_idle': True,
'interp_paused': True
}
},
}
# previous "idleList"
INTERLOCK_RULES.update({
f'{item}': {'all': {
'interp_idle': True,
'manual_cut_active': False,
'ohmic_test': False,
'single_cut_dialog': False
}}
for item in ['file_clear', 'file_open', 'file_reload', 'file_edit']})
# previous "idleOnList"
INTERLOCK_RULES.update({
f'{item}': {'all': {
'estop_cleared': True,
'interp_idle': True,
'manual_cut_active': False,
'machine_on': True,
'offsets_active': False,
'ohmic_test': False,
'previewstack_is_edit': False,
'previewstack_is_offsets': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'probe_test': False,
'single_cut_dialog': False
}}
for item in ['home_x', 'home_y', 'home_z', 'home_a', 'home_b', 'home_c', 'home_all']})
# previous "idleHomedList"
INTERLOCK_RULES.update({
f'{item}': {'all': {
'all_homed': True,
'estop_cleared': True,
'interp_idle': True,
'manual_cut_active': False,
'machine_on': True,
'ohmic_test': False,
'previewstack_is_edit': False,
'previewstack_is_open': False,
'previewstack_is_user_manual': False,
'probe_test': False,
'single_cut_dialog': False
}}
for item in ['touch_x', 'touch_y', 'touch_z', 'touch_a', 'touch_b', 'touch_c', 'set_offsets']})
# jog buttons a,b,c,x,y - z gets special handling due to manual cut
INTERLOCK_RULES.update({
f'{item}': {'all': {
'all_homed': True,
'interp_idle': True,
'machine_on': True,
'offsets_active': False
}}
for item in ['jog_a_plus', 'jog_a_minus', 'jog_b_plus', 'jog_b_minus','jog_c_plus', 'jog_c_minus','jog_x_plus', 'jog_x_minus','jog_y_plus', 'jog_y_minus']})
INTERLOCK_RULES.update({
f'{item}': {'all': {
'all_homed': True,
'interp_idle': True,
'machine_on': True,
'manual_cut_active': False,
'offsets_active': False
}}
for item in ['jog_z_plus', 'jog_z_minus']})
# cut recovery controls
INTERLOCK_RULES.update({
f'cut_rec_{item}': {'all': {
'consumable_changing': False,
'interp_paused': True
}}
for item in ['fwd', 'rev', 'speed', 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'feed', 'move_label']})
# PARAMETERS tab common
INTERLOCK_RULES.update({
f'{item}': {'all': {
'interp_idle': True,
'probe_test': False,
'torch_pulse': False,
'manual_cut_active': False
}}
for item in ['material_box', 'save_material', 'delete_material', 'new_material', 'reload_material', 'cut_amps', 'cut_feed_rate', 'cut_height', 'cut_mode', 'cut_mode_label', 'cut_volts', 'gas_pressure', 'material_thickness', 'kerf_width', 'pause_at_end', 'pierce_delay', 'pierce_height', 'puddle_jump_delay', 'puddle_jump_height']})
# SETTINGS tab user button fields
INTERLOCK_RULES.update({
f'{item}_{n}': {'all': {
'interp_running': False,
'probe_test': False,
'torch_pulse': False,
'manual_cut_active': False
}}
for item in ('ub_name', 'ub_code')
for n in range(1, 21)})

View File

@@ -0,0 +1,357 @@
'''
set_offsets.py
Copyright (C) 2020 - 2024 Phillip A Carter
Copyright (C) 2020 - 2024 Gregory D Carl
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.
'''
import os
from shutil import copy as COPY
from qtpy import QtCore
from qtpy.QtCore import QCoreApplication
from qtpy.QtWidgets import QDialog, QMessageBox, QPushButton, QGridLayout, QLabel, QComboBox
from qtpy.QtGui import QIcon
_translate = QCoreApplication.translate
def dialog_show(P, W, prefs, iniPath, STATUS, ACTION, TOOL):
dlg = QDialog(W)
dlg.setWindowIcon(QIcon(os.path.join(P.iconBase, P.iconPath)))
dlg.setModal(False)
grid = QGridLayout()
lbl = QLabel()
btn0 = QPushButton('CANCEL')
btn1 = QPushButton()
btn2 = QPushButton()
btn3 = QPushButton()
btn4 = QPushButton()
dlg_set_text(True, dlg, lbl, btn1, btn2, btn3, btn4)
grid.addWidget(lbl, 0, 0, 1, 5)
grid.addWidget(btn0, 1, 0)
grid.addWidget(btn1, 1, 1)
grid.addWidget(btn2, 1, 2)
grid.addWidget(btn3, 1, 3)
grid.addWidget(btn4, 1, 4)
dlg.setLayout(grid)
btn0.clicked.connect(lambda w: dlg_cancel_clicked(P, W, prefs, dlg, lbl, btn1, btn2, btn3, btn4))
btn1.clicked.connect(lambda w: dlg_laser_clicked(P, W, prefs, iniPath, STATUS, ACTION, TOOL, dlg, lbl, btn1, btn2, btn3, btn4))
btn2.clicked.connect(lambda w: dlg_camera_clicked(P, W, prefs, iniPath, STATUS, ACTION, TOOL, dlg, lbl, btn1, btn2, btn3, btn4))
btn3.clicked.connect(lambda w: dlg_scribe_clicked(P, W, prefs, iniPath, STATUS, ACTION, TOOL, dlg, lbl, btn1, btn2, btn3, btn4))
btn4.clicked.connect(lambda w: dlg_probe_clicked(P, W, prefs, iniPath, STATUS, ACTION, TOOL, dlg, lbl, btn1, btn2, btn3, btn4))
dlg.setGeometry(dlg.parent().geometry().x(), dlg.parent().geometry().y(), dlg.width(), dlg.height())
dlg.show()
dlg.setStyleSheet(f'* {{ color: {P.foreColor}; background: {P.backColor}; margin: 4px }} \
QPushButton {{ background: {P.backColor}; height: 40px; font: 12pt; border: 1px solid {P.foreColor}; border-radius: 4px }} \
QPushButton:disabled {{color: {P.disabledColor}; border: 1px solid {P.disabledColor} }} \
QPushButton:pressed {{ color: {P.backColor} ; background: {P.foreColor} }}')
def dlg_cancel_clicked(P, W, prefs, dlg, lbl, btn1, btn2, btn3, btn4):
P.laserOnPin.set(0)
P.offsetSetProbePin.set(0)
P.offsetSetScribePin.set(0)
W.preview_stack.setCurrentIndex(0)
P.camNum = prefs.getpref('Camera port', 0, int, 'CAMERA_OFFSET')
W.camview.set_camnum(P.camNum)
if 'OFFSETS' in btn1.text() or 'OFFSETS' in btn2.text() or 'OFFSETS' in btn3.text() or 'OFFSETS' in btn4.text():
dlg_set_text(True, dlg, lbl, btn1, btn2, btn3, btn4)
else:
dlg.reject()
def dlg_laser_clicked(P, W, prefs, iniPath, STATUS, ACTION, TOOL, dlg, lbl, btn1, btn2, btn3, btn4):
if 'LASER' in btn1.text():
dlg_set_text(False, dlg, lbl, btn1, btn2, btn3, btn4)
P.laserOnPin.set(1)
return
if get_reply(P, STATUS, P.laserOffsetX, P.laserOffsetY):
P.laserOffsetX = round(STATUS.get_position()[1][0], 4) + 0
P.laserOffsetY = round(STATUS.get_position()[1][1], 4) + 0
prefs.putpref('X axis', P.laserOffsetX, float, 'LASER_OFFSET')
prefs.putpref('Y axis', P.laserOffsetY, float, 'LASER_OFFSET')
if P.laserOffsetX or P.laserOffsetY:
W.laser.show()
else:
W.laser.hide()
P.laserOnPin.set(0)
head = _translate('HandlerClass', 'Laser Offsets')
msg0 = _translate('HandlerClass', 'Laser offsets have been saved')
P.dialog_show_ok(QMessageBox.Information, f'{head}', f'\n{msg0}\n')
dlg.close()
else:
dlg_set_text(True, dlg, lbl, btn1, btn2, btn3, btn4)
P.laserOnPin.set(0)
def dlg_camera_clicked(P, W, prefs, iniPath, STATUS, ACTION, TOOL, dlg, lbl, btn1, btn2, btn3, btn4):
if 'CAMERA' in btn2.text():
dlg.hide()
W.setCursor(QtCore.Qt.WaitCursor)
cameras = camera_search(P, W, dlg)
if not cameras:
W.unsetCursor()
dlg.show()
return
W.preview_stack.setCurrentIndex(3)
if len(cameras) > 1:
camera_select(P, W, STATUS, cameras)
else:
P.camNum = cameras[0]
W.camview.set_camnum(cameras[0])
W.unsetCursor()
dlg.show()
if P.camNum == -1: # cancelled from camera selection
W.preview_stack.setCurrentIndex(0)
P.camNum = prefs.getpref('Camera port', 0, int, 'CAMERA_OFFSET')
W.camview.set_camnum(P.camNum)
return
dlg_set_text(False, dlg, lbl, btn2, btn1, btn3, btn4)
return
if get_reply(P, STATUS, P.camOffsetX, P.camOffsetY):
P.camOffsetX = round(STATUS.get_position()[1][0], 4) + 0
P.camOffsetY = round(STATUS.get_position()[1][1], 4) + 0
prefs.putpref('X axis', P.camOffsetX, float, 'CAMERA_OFFSET')
prefs.putpref('Y axis', P.camOffsetY, float, 'CAMERA_OFFSET')
prefs.putpref('Camera port', P.camNum, int, 'CAMERA_OFFSET')
if P.camOffsetX or P.camOffsetY:
W.camera.show()
else:
W.camera.hide()
W.preview_stack.setCurrentIndex(0)
head = _translate('HandlerClass', 'Camera Offsets')
msg0 = _translate('HandlerClass', 'Camera offsets have been saved')
P.dialog_show_ok(QMessageBox.Information, f'{head}', f'\n{msg0}\n')
dlg.close()
else:
dlg_set_text(True, dlg, lbl, btn1, btn2, btn3, btn4)
W.preview_stack.setCurrentIndex(0)
P.camNum = prefs.getpref('Camera port', 0, int, 'CAMERA_OFFSET')
W.camview.set_camnum(P.camNum)
def dlg_scribe_clicked(P, W, prefs, iniPath, STATUS, ACTION, TOOL, dlg, lbl, btn1, btn2, btn3, btn4):
if 'SCRIBE' in btn3.text():
dlg_set_text(False, dlg, lbl, btn3, btn1, btn2, btn4)
P.offsetSetScribePin.set(1)
return
xOffset = yOffset = 0.000
toolFile = os.path.join(os.path.dirname(iniPath), TOOL.toolfile)
inFile = open(f'{toolFile}', 'r')
tool = []
for line in inFile:
if line.startswith('T1'):
tool = line.split()
inFile.close()
break
if tool:
for item in tool:
if item.startswith('X'):
xOffset = float(item.replace('X','').replace('+',''))
elif item.startswith('Y'):
yOffset = float(item.replace('Y','').replace('+',''))
if get_reply(P, STATUS, xOffset, yOffset):
xOffset = round(STATUS.get_position()[1][0], 4) + 0
yOffset = round(STATUS.get_position()[1][1], 4) + 0
do_tool_file(P, W, toolFile, xOffset, yOffset)
ACTION.RELOAD_TOOLTABLE()
P.offsetSetScribePin.set(0)
head = _translate('HandlerClass', 'Scribe Offsets')
msg0 = _translate('HandlerClass', 'Scribe offsets have been saved')
P.dialog_show_ok(QMessageBox.Information, f'{head}', f'\n{msg0}\n')
dlg.close()
else:
dlg_set_text(True, dlg, lbl, btn1, btn2, btn3, btn4)
P.offsetSetScribePin.set(0)
def dlg_probe_clicked(P, W, prefs, iniPath, STATUS, ACTION, TOOL, dlg, lbl, btn1, btn2, btn3, btn4):
if 'PROBE' in btn4.text():
dlg_set_text(False, dlg, lbl, btn4, btn1, btn2, btn3)
P.offsetSetProbePin.set(1)
return
new = 0.0
head = _translate('HandlerClass', 'Offset Probe Delay')
text = _translate('HandlerClass', 'Delay (Seconds)')
btnOk = _translate('HandlerClass', 'OK')
btnCancel = _translate('HandlerClass', 'CANCEL')
virtkb = 4
valid, value = (P.dialog_input(virtkb, head, text, btnOk, btnCancel, P.probeDelay))
if valid:
try:
new = float(value)
except:
head = _translate('HandlerClass', 'Entry Error')
msg0 = _translate('HandlerClass', 'is not a valid number')
P.dialog_show_ok(QMessageBox.Warning, f'{head}', f'\'{value}\' {msg0}\n')
return
else:
dlg_set_text(True, dlg, lbl, btn1, btn2, btn3, btn4)
P.offsetSetProbePin.set(0)
return
if get_reply(P, STATUS, P.probeOffsetX, P.probeOffsetY, True, P.probeDelay, new):
P.probeOffsetX = round(STATUS.get_position()[1][0], 4) + 0
P.probeOffsetY = round(STATUS.get_position()[1][1], 4) + 0
P.probeDelay = new
prefs.putpref('X axis', P.probeOffsetX, float, 'OFFSET_PROBING')
prefs.putpref('Y axis', P.probeOffsetY, float, 'OFFSET_PROBING')
prefs.putpref('Delay', P.probeDelay, float, 'OFFSET_PROBING')
P.set_probe_offset_pins()
P.offsetSetProbePin.set(0)
if P.probeOffsetX or P.probeOffsetY:
W.offset_feed_rate.show()
W.offset_feed_rate_lbl.show()
else:
W.offset_feed_rate.hide()
W.offset_feed_rate_lbl.hide()
head = _translate('HandlerClass', 'Probe Offsets')
msg0 = _translate('HandlerClass', 'Probe offsets have been saved')
P.dialog_show_ok(QMessageBox.Information, f'{head}', f'\n{msg0}\n')
dlg.close()
else:
dlg_set_text(True, dlg, lbl, btn1, btn2, btn3, btn4)
P.offsetSetProbePin.set(0)
def dlg_set_text(main, dlg, lbl, btnA, btnB, btnC, btnD):
if main:
dlg.setWindowTitle(_translate('Offsets', 'Set Peripheral Offsets'))
msg1 = _translate('Offsets', 'Touchoff the torch to X0 Y0')
msg2 = _translate('Offsets', 'Mark the material with a torch pulse')
msg3 = _translate('Offsets', 'Click the appropriate button to activate the peripheral')
btnA.setText('LASER')
btnB.setText('CAMERA')
btnC.setText('SCRIBE')
btnD.setText('PROBE')
btnA.show()
btnB.show()
btnC.show()
btnD.show()
else:
dlg.setWindowTitle(_translate('Offsets', 'Get Peripheral Offsets'))
msg1 = _translate('Offsets', 'Jog until the peripheral is centered on the mark')
msg2 = _translate('Offsets', 'Click the GET OFFSETS button to get the offsets')
msg3 = _translate('Offsets', 'Confirm the setting of the offsets')
btnA.setText('GET\nOFFSETS')
btnB.hide()
btnC.hide()
btnD.hide()
msg0 = _translate('Offsets', 'Usage is as follows')
msg4 = _translate('Offsets', 'Note: It may be necessary to click the preview window to enable jogging')
lbl.setText(f'{msg0}:\n\n1. {msg1}.\n2. {msg2}.\n3. {msg3}.\n\n{msg4}.\n')
def get_reply(P, STATUS, xOffset, yOffset, probe=False, delay=0.0, new=0.0):
head = _translate('HandlerClass', 'Offset Change')
btn1 = _translate('HandlerClass', 'SET OFFSETS')
btn2 = _translate('HandlerClass', 'CANCEL')
msg0 = _translate('HandlerClass', 'Change offsets from')
if probe:
msg0 += f':\nX:{xOffset:0.4f} Y:{yOffset:0.4f} Delay:{delay:0.2f}\n\n'
else:
msg0 += f':\nX:{xOffset:0.4f} Y:{yOffset:0.4f}\n\n'
msg0 += _translate('HandlerClass', 'To')
xP = round(STATUS.get_position()[1][0], 4) + 0
yP = round(STATUS.get_position()[1][1], 4) + 0
if probe:
msg0 += f':\nX:{xP:0.4f} Y:{yP:0.4f} Delay:{new:0.2f}\n'
else:
msg0 += f':\nX:{xP:0.4f} Y:{yP:0.4f}\n'
if P.dialog_show_yesno(QMessageBox.Warning, f'{head}', f'\n{msg0}', f'{btn1}', f'{btn2}'):
return True
else:
return False
def camera_search(P, W, dlg):
head = _translate('Offsets', 'Camera Search')
cameras = []
try:
import cv2
except:
msg0 = _translate('Offsets', 'Could not load the cv2 module')
msg1 = _translate('Offsets', 'Try installing by entering the following in a terminal')
msg2 = _translate('Offsets', 'sudo apt install python3-opencv')
W.unsetCursor()
P.dialog_show_ok(QMessageBox.Critical, f'{head}', f'\n{msg0}.\n\n{msg1}:\n\n{msg2}\n')
return
for file in os.listdir('/dev'):
if file.startswith('video'):
cap = cv2.VideoCapture(int(file.replace('video', '')))
if cap is None or not cap.isOpened():
pass
else:
cameras.append(int(file.replace('video', '')))
cap.release()
if not cameras:
msg0 = _translate('HandlerClass', 'No cameras have been found')
P.dialog_show_ok(QMessageBox.Warning, f'{head}', f'\n{msg0}\n')
return cameras
def camera_select(P, W, STATUS, cameras):
dlg = QDialog(W)
dlg.setWindowIcon(QIcon(os.path.join(P.iconBase, P.iconPath)))
dlg.setWindowTitle(_translate('Offsets', 'Select Camera'))
dlg.setModal(True)
grid = QGridLayout()
label = QLabel()
combo = QComboBox()
for camera in cameras:
combo.addItem(f'Camera_{camera}')
cam = P.camNum if P.camNum in cameras else cameras[0]
combo.setCurrentIndex(cameras.index(cam))
btn0 = QPushButton('CANCEL', dlg)
btn1 = QPushButton('OK', dlg)
grid.addWidget(label, 0, 0, 1, 2)
grid.addWidget(combo, 1, 0, 1, 2)
grid.addWidget(btn0, 2, 0)
grid.addWidget(btn1, 2, 1)
dlg.setLayout(grid)
msg0 = _translate('Offsets', 'Select the camera to use')
label.setText(f'{msg0}.\n')
combo.currentIndexChanged.connect(lambda w: camera_changed(P, W, STATUS, dlg, int(combo.currentText()[-1:])))
btn0.clicked.connect(lambda w: camera_btn_clicked(P, W, dlg, -1))
btn1.clicked.connect(lambda w: camera_btn_clicked(P, W, dlg, int(combo.currentText()[-1:])))
dlg.setStyleSheet(f'* {{ color: {P.foreColor}; background: {P.backColor}; margin: 4px }} \
QPushButton {{ background: {P.backColor}; height: 40px; font: 12pt; border: 1px solid {P.foreColor}; border-radius: 4px }} \
QPushButton:disabled {{color: {P.disabledColor}; border: 1px solid {P.disabledColor} }} \
QPushButton:pressed {{ color: {P.backColor} ; background: {P.foreColor} }}')
dlg.setGeometry(dlg.parent().geometry().x(), dlg.parent().geometry().y(), dlg.width(), dlg.height())
W.camview.set_camnum(int(combo.currentText()[-1:]))
W.unsetCursor()
dlg.exec()
def camera_changed(P, W, STATUS, dlg, camnum):
dlg.setCursor(QtCore.Qt.WaitCursor)
W.setCursor(QtCore.Qt.WaitCursor)
W.camview.hideEvent(None)
W.camview.set_camnum(camnum)
W.camview.showEvent(None)
dlg.unsetCursor()
W.unsetCursor()
def camera_btn_clicked(P, W, dlg, camnum):
P.camNum = int(camnum)
dlg.reject()
def do_tool_file(P, W, toolFile, xOffset, yOffset):
written = False
COPY(toolFile, f'{toolFile}~')
inFile = open(f'{toolFile}~', 'r')
outFile = open(toolFile, 'w')
for line in inFile:
if line.startswith('T1'):
outFile.write(f'T1 P1 X{xOffset:0.4f} Y{yOffset:0.4f} ;scribe\n')
written = True
else:
outFile.write(line)
if not written:
outFile.write(f'T1 P1 X{xOffset:0.4f} Y{yOffset:0.4f} ;scribe\n')
inFile.close()
outFile.close()
os.remove(f'{toolFile}~')

View File

@@ -0,0 +1,548 @@
'''
tooltips.py
Copyright (C) 2021 - 2024 Phillip A Carter
Copyright (C) 2021 - 2026 Gregory D Carl
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.
'''
from qtpy.QtCore import QCoreApplication
_translate = QCoreApplication.translate
#########################################################################################################################
# TOOL TIP FUNCTIONS #
#########################################################################################################################
def tool_tips_changed(P, W):
if W.chk_tool_tips.isChecked():
set_tool_tips(P, W)
else:
clear_tool_tips(W)
def clear_tool_tips(W):
main_preview_widgets = [
'material_selector', 'velocity_show', 'view_p', 'view_z', 'view_t', 'view_clear',
'pan_right', 'pan_left', 'pan_up', 'pan_down', 'zoom_in', 'zoom_out']
main_machine_widgets = [
'estop', 'power', 'run', 'pause_resume', 'abort', 'feed_slider', 'rapid_slider',
'jog_slider', 'feed_label', 'rapid_label', 'jogs_label']
main_button_widgets = [
'file_edit', 'mdi_show']
main_arc_widgets = [
'arc_voltage', 'led_arc_ok', 'height_reset', 'height_lower', 'height_ovr_label',
'height_raise']
main_control_widgets = [
'led_torch_on', 'led_corner_lock', 'led_void_lock']
main_sensor_widgets = [
'mesh_enable', 'ignore_arc_ok', 'pmx485_label', 'torch_enable',
'cornerlock_enable', 'voidlock_enable', 'use_auto_volts',
'ohmic_probe_enable', 'pmx485_enable']
main_thc_widgets = [
'led_float_switch', 'led_ohmic_probe', 'led_breakaway_switch', 'thc_auto',
'thc_enable', 'led_thc_up', 'led_thc_enabled', 'led_thc_down', 'led_thc_active']
main_jog_widgets = [
'jogincrements', 'jog_slow', 'jog_z_minus', 'jog_z_plus', 'jog_x_minus',
'jog_x_plus', 'jog_a_plus', 'jog_a_minus', 'jog_y_plus', 'jog_y_minus',
'jog_b_minus', 'jog_b_plus', 'jog_c_minus', 'jog_c_plus']
main_cut_rec_widgets = [
'cut_rec_cancel', 'cut_rec_rev', 'cut_rec_speed', 'cut_rec_fwd', 'cut_rec_feed',
'cut_rec_se', 'cut_rec_s', 'cut_rec_nw', 'cut_rec_e', 'cut_rec_sw', 'cut_rec_w',
'cut_rec_n', 'cut_rec_ne', 'cut_rec_move_label']
main_gcode_widgets = [
'file_clear', 'file_open', 'file_reload']
main_dro_widgets = [
'dro_a', 'dro_b', 'dro_x', 'dro_y', 'dro_z', 'home_a', 'home_b', 'home_x', 'home_y',
'home_z', 'home_all', 'touch_a', 'touch_b', 'touch_x', 'touch_y', 'touch_z',
'touch_xy', 'wcs_button', 'camera', 'laser']
main_file_widgets = [
'file_select', 'file_next', 'file_prev', 'file_cancel']
main_camera_widgets = [
'cam_dia_plus', 'cam_dia_minus', 'cam_zoom_plus', 'cam_zoom_minus', 'cam_goto',
'cam_mark']
conversational_widgets = [
'conv_line', 'conv_circle', 'conv_ellipse', 'conv_triangle', 'conv_rectangle',
'conv_polygon', 'conv_bolt', 'conv_slot', 'conv_star', 'conv_gusset', 'conv_sector',
'conv_block', 'conv_new', 'conv_save', 'conv_settings', 'conv_send']
conv_preview_widgets = [
'conv_material', 'conv_view_z', 'conv_view_t','conv_pan_right', 'conv_pan_left',
'conv_pan_up', 'conv_pan_down', 'conv_zoom_in', 'conv_zoom_out']
parameters_configuration_widgets = [
'arc_fail_delay', 'arc_max_starts', 'arc_restart_delay', 'arc_voltage_scale',
'arc_voltage_offset', 'height_per_volt', 'arc_ok_high', 'arc_ok_low',
'thc_delay', 'thc_threshold', 'pid_p_gain', 'pid_i_gain', 'pid_d_gain',
'cornerlock_threshold', 'voidlock_slope', 'float_switch_travel',
'probe_feed_rate', 'slat_height', 'probe_start_height', 'ohmic_probe_offset',
'ohmic_max_attempts', 'skip_ihs_distance', 'offset_feed_rate', 'safe_height',
'scribe_arm_delay', 'scribe_on_delay', 'spotting_threshold', 'spotting_time',
'setup_feed_rate', 'save_plasma', 'reload_plasma']
parameters_material_widgets = [
'material_thickness','kerf_width', 'pierce_height', 'pierce_delay', 'cut_height',
'cut_feed_rate', 'cut_amps', 'cut_volts', 'puddle_jump_height', 'puddle_jump_delay',
'pause_at_end', 'gas_pressure', 'cut_mode', 'save_material', 'reload_material',
'new_material', 'delete_material']
settings_gui_widgets = [
'color_foregrnd', 'color_foregalt', 'color_led', 'color_backgrnd',
'color_backgalt', 'color_frams', 'color_estop', 'color_disabled',
'color_preview', 'chk_soft_keyboard', 'chk_keyboard_shortcuts',
'chk_overlay', 'opt_stp', 'chk_run_from_line', 'chk_override_limits',
'chk_tool_tips', 'opt_blk', 'grid_size', 'cone_size', 'table_zoom_scale',
'default_material', 'chk_exit_warning']
settings_user_buttons = [
'ub_save', 'ub_reload']
settigns_shutdown_widgets = [
'sd_save', 'sd_reload', 'sd_text']
settings_utilities_widgets = [
'actionbutton_halshow', 'actionbutton_halscope', 'actionbutton_halmeter',
'actionbutton_calibration', 'actionbutton_lcnc_status', 'set_offsets', 'backup']
statistics_widgets = [
'pierce_reset', 'cut_length_reset', 'cut_time_reset', 'torch_time_reset',
'run_time_reset', 'rapid_time_reset', 'probe_time_reset', 'paused_time_reset',
'all_reset', 'pierce_count', 'cut_length', 'cut_time', 'torch_time', 'run_time',
'rapid_time', 'probe_time', 'pierce_count_t', 'cut_length_t', 'cut_time_t',
'torch_time_t', 'run_time_t', 'rapid_time_t', 'probe_time_t','pmx_arc_time_t']
W.statusbar.setToolTip('')
for widget in main_preview_widgets:
W[widget].setToolTip('')
for widget in main_machine_widgets:
W[widget].setToolTip('')
for widget in main_button_widgets:
W[widget].setToolTip('')
for b in range(1, 21):
W[f'button_{b}'].setToolTip('')
for widget in main_arc_widgets:
W[widget].setToolTip('')
for widget in main_control_widgets:
W[widget].setToolTip('')
for widget in main_sensor_widgets:
W[widget].setToolTip('')
for widget in main_thc_widgets:
W[widget].setToolTip('')
for widget in main_jog_widgets:
W[widget].setToolTip('')
for widget in main_cut_rec_widgets:
W[widget].setToolTip('')
for widget in main_gcode_widgets:
W[widget].setToolTip('')
for widget in main_dro_widgets:
W[widget].setToolTip('')
for widget in main_file_widgets:
W[widget].setToolTip('')
for widget in main_camera_widgets:
W[widget].setToolTip('')
for widget in conversational_widgets:
W[widget].setToolTip('')
for widget in conv_preview_widgets:
W[widget].setToolTip('')
for widget in parameters_configuration_widgets:
W[widget].setToolTip('')
for widget in parameters_material_widgets:
W[widget].setToolTip('')
for widget in settings_gui_widgets:
W[widget].setToolTip('')
for widget in settings_user_buttons:
W[widget].setToolTip('')
for b in range(1, 21):
W[f'ub_name_{b}'].setToolTip('')
for b in range(1, 21):
W[f'ub_code_{b}'].setToolTip('')
for widget in settigns_shutdown_widgets:
W[widget].setToolTip('')
for widget in settings_utilities_widgets:
W[widget].setToolTip('')
for widget in statistics_widgets:
W[widget].setToolTip('')
def set_tool_tips(P, W):
# main widgets
W.statusbar.setToolTip(_translate('ToolTips', 'Shows active G and M Codes'))
# main_preview_widgets
text0 = _translate('ToolTips', 'Shows the currently loaded material')
text1 = _translate('ToolTips', 'Click to change material')
W.material_selector.setToolTip(f'{text0}\n{text1}')
W.velocity_show.setToolTip(_translate('ToolTips', 'Shows the current velocity in units per minute'))
W.view_p.setToolTip(_translate('ToolTips', 'Changes the view to perspective view'))
W.view_z.setToolTip(_translate('ToolTips', 'Show the view from the top with zoom level set to program extents'))
W.view_t.setToolTip(_translate('ToolTips', 'Show the view from the top with zoom level set to machine travel extents'))
W.view_clear.setToolTip(_translate('ToolTips', 'Clears motion segments from preview'))
W.pan_right.setToolTip(_translate('ToolTips', 'Pans the view right'))
W.pan_left.setToolTip(_translate('ToolTips', 'Pans the view left'))
W.pan_up.setToolTip(_translate('ToolTips', 'Pans the view up'))
W.pan_down.setToolTip(_translate('ToolTips', 'Pans the view down'))
W.zoom_in.setToolTip(_translate('ToolTips', 'Zooms in'))
W.zoom_out.setToolTip(_translate('ToolTips', 'Zooms out'))
# main_machine_widgets
W.estop.setToolTip(_translate('ToolTips', 'Shows the Estop status'))
text0 = _translate('ToolTips', 'Switches the GUI on or off')
text1 = _translate('ToolTips', 'A long press displays the GUI shutdown dialog')
W.power.setToolTip(f'{text0}\n{text1}')
W.run.setToolTip(_translate('ToolTips', 'Runs the currently loaded G-Code program'))
W.pause_resume.setToolTip(_translate('ToolTips', 'Pauses or resume the currently running G-Code program'))
W.abort.setToolTip(_translate('ToolTips', 'Stops the currently running process'))
W.feed_slider.setToolTip(_translate('ToolTips', 'Sets the feed override percentage'))
W.rapid_slider.setToolTip(_translate('ToolTips', 'Sets the rapid override percentage'))
W.jog_slider.setToolTip(_translate('ToolTips', 'Sets the jog feed rate'))
W.feed_label.setToolTip(_translate('ToolTips', 'Click to reset the feed slider to 100%'))
W.rapid_label.setToolTip(_translate('ToolTips', 'Click to reset the rapid slider to 100%'))
W.jogs_label.setToolTip(_translate('ToolTips', 'Click to reset the jog slider to the default velocity'))
# main_button_widgets
W.file_edit.setToolTip(_translate('ToolTips', 'Toggles the use of the G-Code file editor'))
W.mdi_show.setToolTip(_translate('ToolTips', 'Toggles the use of Manual Data Input mode'))
text0 = _translate('ToolTips', 'User button')
text1 = _translate('ToolTips', 'configured on the SETTINGS tab')
for b in range(1, 21):
W[f'button_{b}'].setToolTip(f'{text0} #{b} {text1}')
# main_arc_widgets
W.arc_voltage.setToolTip(_translate('ToolTips', 'Shows the current arc voltage'))
W.led_arc_ok.setToolTip(_translate('ToolTips', 'Shows the Arc OK signal status'))
W.height_reset.setToolTip(_translate('ToolTips', 'Click to reset the THC override voltage to zero'))
W.height_lower.setToolTip(_translate('ToolTips', 'Lowers the target voltage for THC override'))
W.height_ovr_label.setToolTip(_translate('ToolTips', 'Shows the THC target voltage override amount'))
W.height_raise.setToolTip(_translate('ToolTips', 'Raises the target voltage for THC override'))
# main_control_widgets
W.led_torch_on.setToolTip(_translate('ToolTips', 'Shows the status of the torch on signal'))
W.led_corner_lock.setToolTip(_translate('ToolTips', 'Shows the velocity anti-dive status'))
W.led_void_lock.setToolTip(_translate('ToolTips', 'Shows the void anti-dive status'))
W.mesh_enable.setToolTip(_translate('ToolTips', 'Toggles the use of mesh mode cutting'))
W.ignore_arc_ok.setToolTip(_translate('ToolTips', 'Toggles the need for an Arc OK signal before XY motion begins'))
W.pmx485_label.setToolTip(_translate('ToolTips', 'Shows the status of PMX485 communications'))
W.torch_enable.setToolTip(_translate('ToolTips', 'Toggles the use of the torch'))
W.cornerlock_enable.setToolTip(_translate('ToolTips', 'Toggles the use of velocity anti-dive'))
W.voidlock_enable.setToolTip(_translate('ToolTips', 'Toggles the use of void anti-dive'))
W.use_auto_volts.setToolTip(_translate('ToolTips', 'Toggles the use of automatic voltage for THC'))
W.ohmic_probe_enable.setToolTip(_translate('ToolTips', 'Toggles the use of ohmic probing'))
W.pmx485_enable.setToolTip(_translate('ToolTips', 'Toggles the use of Powermax communications'))
# main_sensor_widgets
W.led_float_switch.setToolTip(_translate('ToolTips', 'Shows the float switch status'))
W.led_ohmic_probe.setToolTip(_translate('ToolTips', 'Shows the ohmic probe status'))
W.led_breakaway_switch.setToolTip(_translate('ToolTips', 'Shows the breakaway switch status'))
# main_thc_widgets
W.thc_auto.setToolTip(_translate('ToolTips', 'Toggles the type of automatic THC activation'))
W.thc_enable.setToolTip(_translate('ToolTips', 'Toggles the use of torch height control'))
W.led_thc_up.setToolTip(_translate('ToolTips', 'Shows the THC is moving the Z axis up'))
W.led_thc_enabled.setToolTip(_translate('ToolTips', 'Shows the THC status'))
W.led_thc_down.setToolTip(_translate('ToolTips', 'Shows the THC is moving the Z axis down'))
W.led_thc_active.setToolTip(_translate('ToolTips', 'Shows the THC is currently in control of the Z axis'))
# main_jog_widgets():
W.jogincrements.setToolTip(_translate('ToolTips', 'Sets the jog increment'))
W.jog_slow.setToolTip(_translate('ToolTips', 'Toggles the jog feed rate by a factor of 10'))
W.jog_a_minus.setToolTip(_translate('ToolTips', 'Jogs the A axis counter negative'))
W.jog_a_plus.setToolTip(_translate('ToolTips', 'Jogs the A axis positive'))
W.jog_b_minus.setToolTip(_translate('ToolTips', 'Jogs the B axis negative'))
W.jog_b_plus.setToolTip(_translate('ToolTips', 'Jogs the B axis positive'))
W.jog_c_minus.setToolTip(_translate('ToolTips', 'Jogs the C axis negative'))
W.jog_c_plus.setToolTip(_translate('ToolTips', 'Jogs the C axis positive'))
W.jog_x_minus.setToolTip(_translate('ToolTips', 'Jogs the X axis negative'))
W.jog_x_plus.setToolTip(_translate('ToolTips', 'Jogs the X axis positive'))
W.jog_y_minus.setToolTip(_translate('ToolTips', 'Jogs the Y axis negative'))
W.jog_y_plus.setToolTip(_translate('ToolTips', 'Jogs the Y axis positive'))
W.jog_z_minus.setToolTip(_translate('ToolTips', 'Jogs the Z axis negative'))
W.jog_z_plus.setToolTip(_translate('ToolTips', 'Jogs the Z axis positive'))
# main_cut_rec_widgets
W.cut_rec_cancel.setToolTip(_translate('ToolTips', 'Cancels cut recovery'))
W.cut_rec_fwd.setToolTip(_translate('ToolTips', 'Moves the torch forward along current motion segment'))
W.cut_rec_rev.setToolTip(_translate('ToolTips', 'Moves the torch reverse along current motion segment'))
text0 = _translate('ToolTips', 'Changes the feed rate for paused motion')
text1 = _translate('ToolTips', 'Slider position indicates percentage of feed rate for current material')
W.cut_rec_speed.setToolTip(f'{text0}\n{text1}')
W.cut_rec_feed.setToolTip(_translate('ToolTips', 'Shows the feed rate for paused motion'))
W.cut_rec_move_label.setToolTip(_translate('ToolTips', 'Shows the distance the torch will move'))
text0 = _translate('ToolTips', 'Moves the torch in the')
text1 = _translate('ToolTips', 'direction')
W.cut_rec_e.setToolTip(f'{text0} X+ {text1}')
W.cut_rec_n.setToolTip(f'{text0} Y+ {text1}')
W.cut_rec_ne.setToolTip(f'{text0} X+ Y+ {text1}')
W.cut_rec_nw.setToolTip(f'{text0} X- Y+ {text1}')
W.cut_rec_s.setToolTip(f'{text0} Y- {text1}')
W.cut_rec_se.setToolTip(f'{text0} X+ Y- {text1}')
W.cut_rec_sw.setToolTip(f'{text0} X- Y- {text1}')
W.cut_rec_w.setToolTip(f'{text0} X- {text1}')
# main gcode widgets
W.file_clear.setToolTip(_translate('ToolTips', 'Clears the current G-Code file'))
W.file_open.setToolTip(_translate('ToolTips', 'Opens the file selector'))
W.file_reload.setToolTip(_translate('ToolTips', 'Reloads the current G-Code file'))
# main dro widgets
text0 = _translate('ToolTips', 'Shows the current')
text1 = _translate('ToolTips', 'axis position')
W.dro_a.setToolTip(f'{text0} A {text1}')
W.dro_b.setToolTip(f'{text0} B {text1}')
W.dro_c.setToolTip(f'{text0} C {text1}')
W.dro_x.setToolTip(f'{text0} X {text1}')
W.dro_y.setToolTip(f'{text0} Y {text1}')
W.dro_z.setToolTip(f'{text0} Z {text1}')
text0 = _translate('ToolTips', 'Homes the')
text1 = _translate('ToolTips', 'axis')
W.home_a.setToolTip(f'{text0} A {text1}')
W.home_b.setToolTip(f'{text0} B {text1}')
W.home_c.setToolTip(f'{text0} C {text1}')
W.home_x.setToolTip(f'{text0} X {text1}')
W.home_y.setToolTip(f'{text0} Y {text1}')
W.home_z.setToolTip(f'{text0} Z {text1}')
W.home_all.setToolTip(_translate('ToolTips', 'Homes all axes'))
text0 = _translate('ToolTips', 'Touches off the')
text1 = _translate('ToolTips', 'axis')
W.touch_a.setToolTip(f'{text0} A {text1}')
W.touch_b.setToolTip(f'{text0} B {text1}')
W.touch_c.setToolTip(f'{text0} C {text1}')
W.touch_x.setToolTip(f'{text0} X {text1}')
W.touch_y.setToolTip(f'{text0} Y {text1}')
W.touch_z.setToolTip(f'{text0} Z {text1}')
text1 = _translate('ToolTips', 'axes to zero')
W.touch_xy.setToolTip(f'{text0} X & Y {text1}')
W.wcs_button.setToolTip(_translate('ToolTips', 'Selects the active work coordinate system'))
W.camera.setToolTip(_translate('ToolTips', 'Use camera view to set origin/rotation'))
text0 = _translate('ToolTips', 'Use laser to set origin/rotation')
text1 = _translate('ToolTips', 'Long press to begin a dry run using the laser')
W.laser.setToolTip(f'{text0}\n{text1}')
# main file widgets
W.file_select.setToolTip(_translate('ToolTips', 'Opens the selected G-Code file'))
W.file_next.setToolTip(_translate('ToolTips', 'Moves the file selector down'))
W.file_prev.setToolTip(_translate('ToolTips', 'Moves the file selector up'))
W.file_cancel.setToolTip(_translate('ToolTips', 'Closes the file selector'))
# main camera widgets
W.cam_dia_plus.setToolTip(_translate('ToolTips', 'Increases the diameter of the overlay circle'))
W.cam_dia_minus.setToolTip(_translate('ToolTips', 'Decreases the diameter of the overlay circle'))
W.cam_zoom_plus.setToolTip(_translate('ToolTips', 'Zooms in'))
W.cam_zoom_minus.setToolTip(_translate('ToolTips', 'Zooms out'))
text0 = _translate('ToolTips', 'Moves the torch to the origin')
W.cam_goto.setToolTip(f'{text0} (X0 Y0)')
W.cam_mark.setToolTip(_translate('ToolTips', 'Starts the origin marking process'))
# conversational widgets
W.conv_line.setToolTip(_translate('ToolTips', 'Create a line or arc'))
W.conv_circle.setToolTip(_translate('ToolTips', 'Create a circle'))
W.conv_ellipse.setToolTip(_translate('ToolTips', 'Create an ellipse'))
W.conv_triangle.setToolTip(_translate('ToolTips', 'Create a triangle'))
W.conv_rectangle.setToolTip(_translate('ToolTips', 'Create a rectangle'))
W.conv_polygon.setToolTip(_translate('ToolTips', 'Create a polygon'))
W.conv_bolt.setToolTip(_translate('ToolTips', 'Create a circular bolt pattern'))
W.conv_slot.setToolTip(_translate('ToolTips', 'Create a slot'))
W.conv_star.setToolTip(_translate('ToolTips', 'Create a star'))
W.conv_gusset.setToolTip(_translate('ToolTips', 'Create a gusset'))
W.conv_sector.setToolTip(_translate('ToolTips', 'Create a sector'))
W.conv_block.setToolTip(_translate('ToolTips', 'Rotate, Scale, and Array the current G-Code program'))
W.conv_new.setToolTip(_translate('ToolTips', 'Starts a new file'))
W.conv_save.setToolTip(_translate('ToolTips', 'Saves the current file'))
W.conv_settings.setToolTip(_translate('ToolTips', 'Opens the conversational settings panel'))
W.conv_send.setToolTip(_translate('ToolTips', 'Loads the current file for cutting'))
# conv_preview_widgets
text0 = _translate('ToolTips', 'Shows the currently loaded material')
text1 = _translate('ToolTips', 'Click to change material')
W.conv_material.setToolTip(f'{text0}\n{text1}')
W.conv_view_z.setToolTip(_translate('ToolTips', 'Show the view from the top with zoom level set to program extents'))
W.conv_view_t.setToolTip(_translate('ToolTips', 'Show the view from the top with zoom level set to machine travel extents'))
W.conv_pan_right.setToolTip(_translate('ToolTips', 'Pans the view right'))
W.conv_pan_left.setToolTip(_translate('ToolTips', 'Pans the view left'))
W.conv_pan_up.setToolTip(_translate('ToolTips', 'Pans the view up'))
W.conv_pan_down.setToolTip(_translate('ToolTips', 'Pans the view down'))
W.conv_zoom_in.setToolTip(_translate('ToolTips', 'Zooms in'))
W.conv_zoom_out.setToolTip(_translate('ToolTips', 'Zooms out'))
# parameters configuration widgets
W.arc_fail_delay.setToolTip(_translate('ToolTips', 'Time for torch on with no Arc OK before failing (seconds)'))
W.arc_max_starts.setToolTip(_translate('ToolTips', 'Number of arc start attempts before pausing'))
W.arc_restart_delay.setToolTip(_translate('ToolTips', 'Delay between arc failure and next arc start attempt (seconds)'))
W.arc_voltage_scale.setToolTip(_translate('ToolTips', 'Sets the input scale to display correct arc voltage'))
W.arc_voltage_offset.setToolTip(_translate('ToolTips', 'Sets the offset to display zero volts at zero input'))
W.height_per_volt.setToolTip(_translate('ToolTips', 'Distance the torch moves per volt (affects manual override only)'))
W.arc_ok_high.setToolTip(_translate('ToolTips', 'Voltage value below which Arc OK is valid'))
W.arc_ok_low.setToolTip(_translate('ToolTips', 'Voltage value above which Arc OK is valid'))
W.thc_delay.setToolTip(_translate('ToolTips', 'Delay between Arc OK and THC activation (seconds)'))
W.thc_sample_counts.setToolTip(_translate('ToolTips', 'Number of consecutive arc voltage readings within the sample threshold required to activate THC'))
W.thc_sample_threshold.setToolTip(_translate('ToolTips', 'Maximum voltage deviation allowed for THC Sample Counts'))
W.thc_threshold.setToolTip(_translate('ToolTips', 'Deviation from target voltage before THC attempts correction'))
W.pid_p_gain.setToolTip(_translate('ToolTips', 'Proportional gain for the THC PID loop'))
W.cornerlock_threshold.setToolTip(_translate('ToolTips', 'Percentage of cut feed rate reduction before THC locks'))
W.voidlock_slope.setToolTip(_translate('ToolTips', 'Voltage change required to activate void anti-dive in volts per second'))
W.pid_i_gain.setToolTip(_translate('ToolTips', 'Integral gain for the THC PID loop'))
W.pid_d_gain.setToolTip(_translate('ToolTips', 'Derivative gain for the THC PID loop'))
W.float_switch_travel.setToolTip(_translate('ToolTips', 'Distance of float travel before switch activation'))
W.probe_feed_rate.setToolTip(_translate('ToolTips', 'Feed rate for probe move after move to Probe Height'))
text0 = _translate('ToolTips', 'Height above Z minimum limit that Probe Speed begins')
text1 = _translate('ToolTips', 'If set to zero, Probe Speed will begin from the current Z axis position')
W.probe_start_height.setToolTip(f'{text0}\n{text1}')
text0 = _translate('ToolTips', 'Height from Z minimum to the top of the slats')
text1 = _translate('ToolTips', 'If both Slat Height and Material Thickness are greater than zero,')
text2 = _translate('ToolTips', 'Probe Speed will begin at Slat Height + Material Thickness')
W.slat_height.setToolTip(f'{text0}\n{text1}\n{text2}')
W.ohmic_probe_offset.setToolTip(_translate('ToolTips', 'Distance above material Z should move after an ohmic probe'))
W.ohmic_max_attempts.setToolTip(_translate('ToolTips', 'Number of retry attempts before defaulting to float switch'))
W.skip_ihs_distance.setToolTip(_translate('ToolTips', 'Initial Height Sense distance, refer to user guide for detailed explanation'))
text0 = _translate('ToolTips', 'Feed rate for offset probe moves in the X and Y axes')
text1 = _translate('ToolTips', 'Maximum')
W.offset_feed_rate.setToolTip(f'{text0}\n{text1} = {int(P.offsetFeedRate)}')
W.safe_height.setToolTip(_translate('ToolTips', 'Height above material the torch will retract to before rapid moves'))
W.scribe_arm_delay.setToolTip(_translate('ToolTips', 'Delay from scribe command to activation of scribe (seconds)'))
W.scribe_on_delay.setToolTip(_translate('ToolTips', 'Delay from scribe activation to XY motion (seconds)'))
text0 = _translate('ToolTips', 'Arc voltage threshold to start the spotting timer')
text1 = _translate('ToolTips', 'Setting to 0V will start the Time On counter upon torch activation')
W.spotting_threshold.setToolTip(f'{text0}\n{text1}')
W.spotting_time.setToolTip(_translate('ToolTips', 'Length of time torch is on after spotting threshold is met (milliseconds)'))
text0 = _translate('ToolTips', 'Z axis velocity for setup moves (Probe Height, Pierce Height, Cut Height)')
text1 = _translate('ToolTips', 'Maximum')
W.setup_feed_rate.setToolTip(f'{text0}\n{text1} = {int(P.thcFeedRate)}')
W.save_plasma.setToolTip(_translate('ToolTips', 'Saves the configuration changes'))
W.reload_plasma.setToolTip(_translate('ToolTips', 'Discards the configuration changes and reloads the configuration'))
# parameters material widgets
text0 = _translate('ToolTips', 'Shows the currently loaded material')
text1 = _translate('ToolTips', 'Click to change material')
W.materials_box.setToolTip(f'{text0}\n{text1}')
text0 = _translate('ToolTips', 'Thickness of the material')
text1 = _translate('ToolTips', 'If both Material Thickness and Slat Height are greater than zero,')
text2 = _translate('ToolTips', 'Probe Speed will begin at Slat Height + Material Thickness')
W.material_thickness.setToolTip(f'{text0}\n{text1}\n{text2}')
W.kerf_width.setToolTip(_translate('ToolTips', 'Width of the material removed by the plasma arc'))
W.pierce_height.setToolTip(_translate('ToolTips', 'Distance above the material the arc start will occur'))
W.pierce_delay.setToolTip(_translate('ToolTips', 'Delay at Pierce Height after Arc OK before cut movements (seconds)'))
W.cut_height.setToolTip(_translate('ToolTips', 'Distance above the material cut movements will occur at'))
W.cut_feed_rate.setToolTip(_translate('ToolTips', 'Speed the torch will travel during cut movements'))
text0 = _translate('ToolTips', 'Cutting current measured in Amps')
text1 = _translate('ToolTips', 'Indicator only, unless using Powermax communications')
W.cut_amps.setToolTip(f'{text0}\n{text1}')
W.cut_volts.setToolTip(_translate('ToolTips', 'Voltage target used for torch height adjustment if not using auto volts'))
W.puddle_jump_height.setToolTip(_translate('ToolTips', 'Height transition between Pierce Height and Cut Height (percentage of Pierce Height)'))
W.puddle_jump_delay.setToolTip(_translate('ToolTips', 'Length of time at Puddle Height before moving to Cut Height (seconds)'))
W.pause_at_end.setToolTip(_translate('ToolTips', 'Delay before turning torch off at end of cut (seconds)'))
text0 = _translate('ToolTips', 'Sets torch gas pressure')
text1 = _translate('ToolTips', 'Use Powermax automatic pressure mode')
W.gas_pressure.setToolTip(f'{text0}\n0 = {text1}')
text0 = _translate('ToolTips', 'Powermax cut modes')
text1 = _translate('ToolTips', 'Normal')
text2 = _translate('ToolTips', 'Constant Pilot Arc')
text3 = _translate('ToolTips', 'Gouge/Mark')
W.cut_mode.setToolTip(f'{text0}:\n1 = {text1}\n2 = CPA ({text2})\n3 = {text3}')
W.save_material.setToolTip(_translate('ToolTips', 'Saves current material set'))
W.reload_material.setToolTip(_translate('ToolTips', 'Discards any changes and reloads the material set'))
W.new_material.setToolTip(_translate('ToolTips', 'Creates a new material'))
W.delete_material.setToolTip(_translate('ToolTips', 'Deletes a material'))
# settings gui widgets
W.color_foregrnd.setToolTip(_translate('ToolTips', 'Shows and changes the color of the foreground'))
W.color_foregalt.setToolTip(_translate('ToolTips', 'Shows and changes the color of highlights'))
W.color_led.setToolTip(_translate('ToolTips', 'Shows and changes the color of the LEDs'))
W.color_backgrnd.setToolTip(_translate('ToolTips', 'Shows and changes the color of the background'))
W.color_backgalt.setToolTip(_translate('ToolTips', 'Shows and changes the color of the alternate background'))
W.color_frams.setToolTip(_translate('ToolTips', 'Shows and changes the color of the frames'))
W.color_estop.setToolTip(_translate('ToolTips', 'Shows and changes the color of the estop button/indicator'))
W.color_disabled.setToolTip(_translate('ToolTips', 'Shows and changes the color of disabled items'))
W.color_preview.setToolTip(_translate('ToolTips', 'Shows and changes the color of the preview screen background'))
W.chk_soft_keyboard.setToolTip(_translate('ToolTips', 'Toggles the use of the soft keyboard'))
W.chk_keyboard_shortcuts.setToolTip(_translate('ToolTips', 'Toggles the use of keyboard shortcuts'))
W.chk_overlay.setToolTip(_translate('ToolTips', 'Toggles the display of material property visibility on the preview screen'))
W.opt_stp.setToolTip(_translate('ToolTips', 'Toggles pausing G-Code execution at M1 optional stops'))
W.chk_run_from_line.setToolTip(_translate('ToolTips', 'Toggles the use of run from line'))
W.chk_override_limits.setToolTip(_translate('ToolTips', 'Toggles the override of limit switches'))
W.chk_tool_tips.setToolTip(_translate('ToolTips', 'Toggles the display of tooltips'))
W.chk_exit_warning.setToolTip(_translate('ToolTips', 'Toggles always display an exit warning'))
W.opt_blk.setToolTip(_translate('ToolTips', 'Toggles the execution of G-Code lines starting with "/"'))
W.grid_size.setToolTip(_translate('ToolTips', 'Changes the size of the grid on the MAIN tab preview screen'))
W.cone_size.setToolTip(_translate('ToolTips', 'Changes the size of the cone on the MAIN tab preview screen'))
W.table_zoom_scale.setToolTip(_translate('ToolTips', 'Changes the default table zoom level'))
W.default_material.setToolTip(_translate('ToolTips', 'Sets the default material number'))
# settings user buttons
W.ub_save.setToolTip(_translate('ToolTips', 'Saves the user button set'))
W.ub_reload.setToolTip(_translate('ToolTips', 'Reloads the user button set'))
text0 = _translate('ToolTips', 'User button')
text1 = _translate('ToolTips', 'name field')
text2 = _translate('ToolTips', 'For multiple lines add a')
text3 = _translate('ToolTips', 'between words')
for b in range (1,21):
W[f'ub_name_{b}'].setToolTip(f'{text0} #{b} {text1}\n{text2} "\\" {text3}')
text0 = _translate('ToolTips', 'User button')
text1 = _translate('ToolTips', 'code field')
for b in range (1,21):
W[f'ub_code_{b}'].setToolTip(f'{text0} #{b} {text1}')
# settings shutdown widgets
W.sd_save.setToolTip(_translate('ToolTips', 'Saves the shutdown message'))
W.sd_reload.setToolTip(_translate('ToolTips', 'Reloads the shutdown message'))
W.sd_text.setToolTip(_translate('ToolTips', 'The message that will be displayed during shutdown'))
# settings utilities widgets
W.actionbutton_halshow.setToolTip(_translate('ToolTips', 'Loads the HalShow application'))
W.actionbutton_halscope.setToolTip(_translate('ToolTips', 'Loads the HalScope application'))
W.actionbutton_halmeter.setToolTip(_translate('ToolTips', 'Loads the HalMeter application'))
W.actionbutton_calibration.setToolTip(_translate('ToolTips', 'Loads the LinuxCNC Calibration application'))
W.actionbutton_lcnc_status.setToolTip(_translate('ToolTips', 'Loads the LinuxCNC Status application'))
W.set_offsets.setToolTip(_translate('ToolTips', 'Launches tool to set offsets for laser, camera, scribe, or offset probe'))
W.backup.setToolTip(_translate('ToolTips', 'Creates a complete backup of the current machine configuration'))
# statistics widgets
W.pierce_reset.setToolTip(_translate('ToolTips', 'Resets the pierce counter'))
W.cut_length_reset.setToolTip(_translate('ToolTips', 'Resets the cut length counter'))
W.cut_time_reset.setToolTip(_translate('ToolTips', 'Resets the cut time counter'))
W.paused_time_reset.setToolTip(_translate('ToolTips', 'Resets the paused time counter'))
W.torch_time_reset.setToolTip(_translate('ToolTips', 'Resets the torch on time counter'))
W.run_time_reset.setToolTip(_translate('ToolTips', 'Resets the program run time counter'))
W.rapid_time_reset.setToolTip(_translate('ToolTips', 'Resets the rapid time counter'))
W.probe_time_reset.setToolTip(_translate('ToolTips', 'Resets the probe time counter'))
W.all_reset.setToolTip(_translate('ToolTips', 'Resets all counters'))
W.pierce_count.setToolTip(_translate('ToolTips', 'Shows the pierce count for the last job'))
W.cut_length.setToolTip(_translate('ToolTips', 'Shows the cut length for the last job'))
W.cut_time.setToolTip(_translate('ToolTips', 'Shows the cut time for the last job'))
W.torch_time.setToolTip(_translate('ToolTips', 'Shows the torch in time for the last job'))
W.run_time.setToolTip(_translate('ToolTips', 'Shows the program run time for the last job'))
W.rapid_time.setToolTip(_translate('ToolTips', 'Shows the rapid time for the last job'))
W.probe_time.setToolTip(_translate('ToolTips', 'Shows the probe time for the last job'))
W.pierce_count_t.setToolTip(_translate('ToolTips', 'Shows the total pierce count since the last reset'))
W.cut_length_t.setToolTip(_translate('ToolTips', 'Shows the total cut length since the last reset'))
W.cut_time_t.setToolTip(_translate('ToolTips', 'Shows the total cut time since the last reset'))
W.torch_time_t.setToolTip(_translate('ToolTips', 'Shows the total torch on time since the last reset'))
W.run_time_t.setToolTip(_translate('ToolTips', 'Shows the total program run time since the last reset'))
W.rapid_time_t.setToolTip(_translate('ToolTips', 'Shows the total rapid time since the last reset'))
W.probe_time_t.setToolTip(_translate('ToolTips', 'Shows the total probe time since the last reset'))
text0 = _translate('ToolTips', 'Shows the total arc on time for the Powermax')
W.pmx_arc_time_t.setToolTip(f'{text0} (hh:mm:ss)')

View File

@@ -0,0 +1,536 @@
'''
updater.py
Copyright (C) 2020 - 2024 Phillip A Carter
Copyright (C) 2020 - 2024 Gregory D Carl
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.
'''
import os
from shutil import copy as COPY
###########################################################################################################
# add newlines between codes [CONVERSATIONAL] Preamble and Postamble (pre V2.10-009.071 2025/08/09) #
###########################################################################################################
def add_newlines(prefs):
for option in ('Preamble', 'Postamble'):
value = prefs.getpref(option, '', str, 'CONVERSATIONAL')
newlines = '\n'.join(value.strip().split())
prefs.putpref(option, newlines, str, 'CONVERSATIONAL')
with open(prefs.fn, 'w') as f:
prefs.write(f)
return(False, False, 'Updated to V2.10-009.071')
###########################################################################################################
# add M52P1 to the [CONVERSATIONAL] Preamble and Postamble (pre V2.10-009.070 2025/08/07) #
###########################################################################################################
def add_adaptive(prefs):
for option in ('Preamble', 'Postamble'):
value = prefs.getpref(option, '', str, 'CONVERSATIONAL')
if 'M52P1' not in value:
prefs.putpref(option, f'{value.strip()} M52P1'.strip(), str, 'CONVERSATIONAL')
with open(prefs.fn, 'w') as f:
prefs.write(f)
return(False, False, 'Updated to V2.10-009.070')
###########################################################################################################
# helper function to expand ini file if #INCLUDE is used in the ini file #
###########################################################################################################
def ini_expander(string, iniFile):
name, ext = os.path.splitext(iniFile)
if '.expanded' in ext:
iniFile = name
with open(iniFile, 'r') as inFile:
contents = inFile.read()
if not string in contents:
includeFiles = []
inFile.seek(0)
for line in inFile:
if line.startswith("#INCLUDE"):
includeFile = line.split()[1].strip()
includeFiles.append(includeFile)
for file in includeFiles:
path = os.path.join(os.path.dirname(iniFile), file)
with open(path, 'r') as inFile:
content = inFile.read()
if string in content:
iniFile = path
break
return iniFile
###########################################################################################################
# set user_m_path to include ../../nc_files/plasmac/m_files (pre V2.10-001.017 2024/01/23) #
###########################################################################################################
def insert_user_m_path(configPath, simPath):
try:
if os.path.isfile(os.path.join(configPath, 'M190')):
os.rename(os.path.join(configPath, 'M190'), os.path.join(configPath, 'M190.bak'))
if simPath and os.path.isfile(os.path.join(simPath, 'M190')):
os.remove(os.path.join(simPath, 'M190'))
return(False, False, '')
except Exception as e:
return(False, True, e)
def insert_user_m_path_iniwrite(iniFile, data=None):
try:
iniFile = ini_expander('USER_M_PATH', iniFile)
tmpFile = f'{iniFile}~'
COPY(iniFile, tmpFile)
with open(tmpFile, 'r') as inFile:
with open(iniFile, 'w') as outFile:
for line in inFile:
if line.startswith('USER_M_PATH'):
line = line.split('=')[1].strip().replace('./:', '')
if line.endswith('./'):
line = line[:-2]
line = f'USER_M_PATH = ./:{data}:{line}\n'
outFile.write(line)
if os.path.isfile(tmpFile):
os.remove(tmpFile)
except Exception as e:
return(False, True, e)
return(True, False, 'Updated to V2.10-001.017')
###########################################################################################################
# change runcritical to cutcritical in <machine_name>.prefs file (pre V2.10-001.015 2023/12/23) #
###########################################################################################################
def rename_runcritical(prefs):
with open(prefs, 'r+') as file:
text = file.read()
text = text.replace('runcritical', 'cutcritical')
file.seek(0)
file.truncate()
file.write(text)
return(False, False, 'Updated to V2.10-001.015')
###########################################################################################################
# move default material from prefs file to material 0 in materials file (pre V2.9-236.278 2023/07/07) #
###########################################################################################################
def move_default_material(prefs, materials, unitsPerMm):
if os.path.isfile(materials):
with open(materials, 'r') as f_in:
mats = f_in.readlines()
else:
mats = None
mat = '[MATERIAL_NUMBER_0]\n'
mat += f'NAME = Default\n'
mat += f'KERF_WIDTH = {prefs.getpref("Kerf width", round(1 * unitsPerMm, 2), float, "DEFAULT MATERIAL")}\n'
mat += f'PIERCE_HEIGHT = {prefs.getpref("Pierce height", round(3 * unitsPerMm, 2), float, "DEFAULT MATERIAL")}\n'
mat += f'PIERCE_DELAY = {prefs.getpref("Pierce delay", 0, float, "DEFAULT MATERIAL")}\n'
mat += f'PUDDLE_JUMP_HEIGHT = {prefs.getpref("Puddle jump height", 0, float, "DEFAULT MATERIAL")}\n'
mat += f'PUDDLE_JUMP_DELAY = {prefs.getpref("Puddle jump delay", 0, float, "DEFAULT MATERIAL")}\n'
mat += f'CUT_HEIGHT = {prefs.getpref("Cut height", round(1 * unitsPerMm, 2), float, "DEFAULT MATERIAL")}\n'
mat += f'CUT_SPEED = {prefs.getpref("Cut feed rate", round(4000 * unitsPerMm, 0), float, "DEFAULT MATERIAL")}\n'
mat += f'CUT_AMPS = {prefs.getpref("Cut amps", 45, float, "DEFAULT MATERIAL")}\n'
mat += f'CUT_VOLTS = {prefs.getpref("Cut volts", 99, float, "DEFAULT MATERIAL")}\n'
mat += f'PAUSE_AT_END = {prefs.getpref("Pause at end", 0, float, "DEFAULT MATERIAL")}\n'
mat += f'GAS_PRESSURE = {prefs.getpref("Gas pressure", 0, float, "DEFAULT MATERIAL")}\n'
mat += f'CUT_MODE = {prefs.getpref("Cut mode", 1, float, "DEFAULT MATERIAL")}\n\n'
with open(materials, 'w') as f_out:
f_out.write(mat)
if mats:
valid = False
for line in mats:
if line[0] != '#':
if line[0] == '[':
if line[1:17] == 'MATERIAL_NUMBER_' and line.strip()[-3:] != '_0]':
valid = True
else:
valid = False
if valid:
f_out.write(line)
prefs.remove_section('DEFAULT MATERIAL')
prefs.write(open(prefs.fn, 'w'))
return(False, False, 'Updated to V2.9-236.278')
###########################################################################################################
# move port info from [GUI_OPTIONS] section (if it was moved via V2.9-227.219 update) to [POWERMAX] section #
###########################################################################################################
def move_port(prefs):
if not prefs.has_option('POWERMAX', 'Port'):
data = prefs.getpref('Port', '', str, 'GUI_OPTIONS')
prefs.putpref('Port', data, str, 'POWERMAX')
prefs.removepref('Port', 'GUI_OPTIONS')
prefs.write(open(prefs.fn, 'w'))
return(False, False, 'Updated to V2.9-232.240')
###########################################################################################################
# move qtplasmac options from INI file to prefs file (pre V2.9-227.219 2022/07/14) #
###########################################################################################################
def move_options_to_prefs_file(iniFile, prefs):
try:
iniFile = ini_expander(f'QTPLASMAC', iniFile)
text = prefs.getpref('shutdown_msg_detail', '', str, 'SHUTDOWN_OPTIONS')
prefs.putpref('Exit warning text', text, str, 'GUI_OPTIONS')
prefs.remove_section('SHUTDOWN_OPTIONS')
prefs.write(open(prefs.fn, 'w'))
data = iniFile.find('QTPLASMAC', 'MODE') or None
if data:
prefs.putpref('Mode', data, int, 'GUI_OPTIONS')
data = iniFile.find('QTPLASMAC', 'ESTOP_TYPE') or None
if data:
prefs.putpref('Estop type', data, int, 'GUI_OPTIONS')
data = iniFile.find('QTPLASMAC', 'DRO_POSITION') or None
if data:
prefs.putpref('DRO position', data, str, 'GUI_OPTIONS')
data = iniFile.find('QTPLASMAC', 'FLASH_ERROR') or None
if data:
data = True if data.lower() in ('yes', 'y', 'true', 't', '1') else False
prefs.putpref('Flash error', data, bool, 'GUI_OPTIONS')
data = iniFile.find('QTPLASMAC', 'HIDE_RUN') or None
if data:
data = True if data.lower() in ('yes', 'y', 'true', 't', '1') else False
prefs.putpref('Hide run', data, bool, 'GUI_OPTIONS')
data = iniFile.find('QTPLASMAC', 'HIDE_PAUSE') or None
if data:
data = True if data.lower() in ('yes', 'y', 'true', 't', '1') else False
prefs.putpref('Hide pause', data, bool, 'GUI_OPTIONS')
data = iniFile.find('QTPLASMAC', 'HIDE_ABORT') or None
if data:
data = True if data.lower() in ('yes', 'y', 'true', 't', '1') else False
prefs.putpref('Hide abort', data, bool, 'GUI_OPTIONS')
data = iniFile.find('QTPLASMAC', 'CUSTOM_STYLE') or None
if data:
prefs.putpref('Custom style', data, str, 'GUI_OPTIONS')
data = iniFile.find('QTPLASMAC', 'AUTOREPEAT_ALL') or None
if data:
data = True if data.lower() in ('yes', 'y', 'true', 't', '1') else False
prefs.putpref('Autorepeat all', data, bool, 'GUI_OPTIONS')
data = iniFile.find('QTPLASMAC', 'LASER_TOUCHOFF') or None
except Exception as e:
return(False, True, e)
if data:
x, y, d, error = get_offsets(data, 'LASER_OFFSET')
if error:
return(False, True, error)
prefs.putpref('X axis', x, float, 'LASER_OFFSET')
prefs.putpref('Y axis', y, float, 'LASER_OFFSET')
data = iniFile.find('QTPLASMAC', 'CAMERA_TOUCHOFF') or None
if data:
x, y, d, error = get_offsets(data, 'CAMERA_OFFSET')
if error:
return(False, True, error)
prefs.putpref('X axis', x, float, 'CAMERA_OFFSET')
prefs.putpref('Y axis', y, float, 'CAMERA_OFFSET')
data = iniFile.find('QTPLASMAC', 'OFFSET_PROBING') or None
if data:
x, y, d, error = get_offsets(data, 'OFFSET_PROBING')
if error:
return(False, True, error)
prefs.putpref('X axis', x, float, 'OFFSET_PROBING')
prefs.putpref('Y axis', y, float, 'OFFSET_PROBING')
prefs.putpref('Delay', d, float, 'OFFSET_PROBING')
data = iniFile.find('QTPLASMAC', 'PM_PORT') or None
if data:
prefs.putpref('Port', data, str, 'POWERMAX')
for bNum in range(1, 21):
bName = iniFile.find('QTPLASMAC', f'BUTTON_{bNum}_NAME') or None
bCode = iniFile.find('QTPLASMAC', f'BUTTON_{bNum}_CODE') or None
if bName and bCode:
prefs.putpref(f'{bNum} Name', bName, str, 'BUTTONS')
prefs.putpref(f'{bNum} Code', bCode, str, 'BUTTONS')
return(False, False, '')
def move_options_to_prefs_file_iniwrite(iniFile):
try:
iniFile = ini_expander('QTPLASMAC', iniFile)
tmpFile = f'{iniFile}~'
COPY(iniFile, tmpFile)
with open(tmpFile, 'r') as inFile:
with open(iniFile, 'w') as outFile:
remove = False
for line in inFile:
if not line:
break
elif line.startswith('[QTPLASMAC]'):
remove = True
continue
elif remove:
if line.startswith('['):
remove = False
else:
continue
outFile.write(line)
if os.path.isfile(tmpFile):
os.remove(tmpFile)
except Exception as e:
return(False, True, e)
return(True, False, 'Updated to V2.9-227.219')
def get_offsets(data, oType):
x = y = d = 0
error = False
parms = data.lower().split()
for parm in parms:
if parm.startswith('x'):
x = float(parm.replace('x', ''))
elif parm.startswith('y'):
y = float(parm.replace('y', ''))
elif oType == 'OFFSET_PROBING':
d = float(parm)
else:
error = f'Parameter error in {oType}. "{data}" is invalid.'
return x, y, d, error
###########################################################################################################
# remove the qtplasmac link from the config directory (pre V2.9-225.208 2022/06/29) #
###########################################################################################################
def remove_qtplasmac_link_iniwrite(iniFile):
try:
iniFile = ini_expander('FILTER', iniFile)
tmpFile = f'{iniFile}~'
COPY(iniFile, tmpFile)
with open(tmpFile, 'r') as inFile:
with open(iniFile, 'w') as outFile:
for line in inFile:
if line.replace(' ', '').startswith('ngc='):
line = 'ngc = qtplasmac_gcode\n'
elif line.replace(' ', '').startswith('nc='):
line = 'nc = qtplasmac_gcode\n'
elif line.replace(' ', '').startswith('tap='):
line = 'tap = qtplasmac_gcode\n'
elif (line.startswith('SUBROUTINE_PATH') or line.startswith('USER_M_PATH')) and ':./qtplasmac' in line:
line = line.replace(':./qtplasmac', '')
outFile.write(line)
if os.path.isfile(tmpFile):
os.remove(tmpFile)
except Exception as e:
return(False, True, e)
return(True, False, 'Updated to V2.9-225.208')
###########################################################################################################
# change startup parameters from a subroutine (pre V2.9-225.207 2022/06/22) #
###########################################################################################################
def rs274ngc_startup_code_iniwrite(iniFile):
try:
iniFile = ini_expander('RS274NGC', iniFile)
tmpFile = f'{iniFile}~'
COPY(iniFile, tmpFile)
with open(tmpFile, 'r') as inFile:
with open(iniFile, 'w') as outFile:
for line in inFile:
if line.startswith('RS274NGC_STARTUP_CODE') and ('metric' in line or 'imperial' in line):
units = 21 if 'metric' in line else 20
line = f'RS274NGC_STARTUP_CODE = G{units} G40 G49 G80 G90 G92.1 G94 G97 M52P1\n'
outFile.write(line)
if os.path.isfile(tmpFile):
os.remove(tmpFile)
except Exception as e:
return(False, True, e)
return(True, False, 'Updated to V2.9-225.207')
###########################################################################################################
# move [CONVERSATIONAL] prefs from qtvcp.prefs to <machine_name>.prefs (pre V2.9-222.187 2022/05/03) #
###########################################################################################################
def move_prefs(qtvcp, machine):
try:
deleteMachineLine = False
moveQtvcpLine = False
with open(machine, 'r') as inFile:
machineData = inFile.readlines()
with open(qtvcp, 'r') as inFile:
qtvcpData = inFile.readlines()
with open(machine, 'w') as machineFile:
with open(qtvcp, 'w') as qtvcpFile:
for line in machineData:
if line.strip() == '[CONVERSATIONAL]':
deleteMachineLine = True
elif line.startswith('['):
deleteMachineLine = False
if not deleteMachineLine:
machineFile.write(line)
for line in qtvcpData:
if line.strip() == '[CONVERSATIONAL]':
moveQtvcpLine = True
elif line.startswith('['):
moveQtvcpLine = False
if moveQtvcpLine:
machineFile.write(line)
else:
qtvcpFile.write(line)
except Exception as e:
return(False, True, e)
return(False, False, 'Updated to V2.9-222.187')
###########################################################################################################
# split out qtplasmac.prefs into <machine_name>.prefs and qtvcp.prefs (pre V2.9-222.170 2022/03/08) #
###########################################################################################################
def split_prefs_file(old, new, prefs):
try:
move = False
copy = False
moves = ['[GUI_OPTIONS]', '[COLOR_OPTIONS]', '[ENABLE_OPTIONS]', '[STATISTICS]',
'[PLASMA_PARAMETERS]', '[DEFAULT MATERIAL]', '[SINGLE CUT]', '[CONVERSATIONAL]']
copies = ['[SHUTDOWN_OPTIONS]']
with open(old, 'r') as inFile:
data = inFile.readlines()
with open(new, 'w') as newFile:
with open(prefs, 'w') as prefsFile:
for line in data:
if line.strip() in moves:
move = True
copy = False
elif line.strip() in copies:
move = False
copy = True
elif line.strip().startswith('['):
move = False
copy = False
if move:
prefsFile.write(line)
elif copy:
if line.strip().startswith('['):
prefsFile.write(line)
if 'shutdown_msg_detail' in line:
prefsFile.write(line)
prefsFile.write('\n')
newFile.write(line)
else:
newFile.write(line)
if os.path.isfile(old):
os.remove(old)
except Exception as e:
return(False, True, e)
return(False, False, 'Updated to V2.9-222.170')
###########################################################################################################
# use qtplasmac_comp.hal for component connections (pre V2.9-221.154 2022/01/18) #
###########################################################################################################
def add_component_hal_file(path, halfiles):
try:
tmpFile = None
pinsToCheck = ['PLASMAC COMPONENT INPUTS', 'plasmac.arc-ok-in', 'plasmac.axis-x-position',
'plasmac.axis-y-position', 'plasmac.breakaway', 'plasmac.current-velocity',
'plasmac.cutting-start', 'plasmac.cutting-stop', 'plasmac.feed-override',
'plasmac.feed-reduction', 'plasmac.float-switch', 'plasmac.feed-upm',
'plasmac.ignore-arc-ok-0', 'plasmac.machine-is-on', 'plasmac.motion-type',
'plasmac.offsets-active', 'plasmac.ohmic-probe', 'plasmac.program-is-idle',
'plasmac.program-is-paused', 'plasmac.program-is-running', 'plasmac.scribe-start',
'plasmac.spotting-start', 'plasmac.thc-disable', 'plasmac.torch-off',
'plasmac.units-per-mm', 'plasmac.x-offset-current', 'plasmac.y-offset-current',
'plasmac.z-offset-current',
'PLASMAC COMPONENT OUTPUTS', 'plasmac.adaptive-feed', 'plasmac.feed-hold',
'plasmac.offset-scale', 'plasmac.program-pause', 'plasmac.program-resume',
'plasmac.program-run', 'plasmac.program-stop', 'plasmac.torch-on',
'plasmac.x-offset-counts', 'plasmac.y-offset-counts', 'plasmac.xy-offset-enable',
'plasmac.z-offset-counts', 'plasmac.z-offset-enable', 'plasmac.requested-velocity']
for f in halfiles:
f = os.path.expanduser(f)
if 'custom' not in f:
halfile = os.path.join(path, f)
with open(halfile, 'r') as inFile:
if 'plasmac.cutting-start' in inFile.read():
inFile.seek(0)
tmpFile = f'{halfile}~'
COPY(halfile, tmpFile)
with open(tmpFile, 'r') as inFile:
with open(f, 'w') as outFile:
for line in inFile:
if any(pin in line for pin in pinsToCheck):
continue
outFile.write(line)
if tmpFile and os.path.isfile(tmpFile):
os.remove(tmpFile)
except Exception as e:
return(False, True, e)
return(False, False, '')
def add_component_hal_file_iniwrite(iniFile):
try:
iniFile = ini_expander('HALFILE', iniFile)
written = False
tmpFile = f'{iniFile}~'
COPY(iniFile, tmpFile)
with open(tmpFile, 'r') as inFile:
with open(iniFile, 'w') as outFile:
while 1:
line = inFile.readline()
if not line:
break
elif line.startswith('[HAL]'):
outFile.write(line)
break
else:
outFile.write(line)
while 1:
line = inFile.readline()
if not line:
if not written:
outFile.write('HALFILE = qtplasmac_comp.hal\n')
break
elif line.startswith('['):
if not written:
outFile.write('HALFILE = qtplasmac_comp.hal\n')
outFile.write(line)
break
elif 'custom.hal' in line.lower():
outFile.write('HALFILE = qtplasmac_comp.hal\n')
outFile.write(line)
written = True
break
else:
outFile.write(line)
while 1:
line = inFile.readline()
if not line:
break
else:
outFile.write(line)
if os.path.isfile(tmpFile):
os.remove(tmpFile)
except Exception as e:
return(False, True, e)
return(True, False, 'Updated to V2.9-221.154')

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,298 @@
#!/usr/bin/env python3
# QTVcp Notification Module
# Provides a consistent and easy to use facility for showing system notifications.
# Copyright (c) 2018 Kurt Jacobson
# <kurtcjacobson@gmail.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.
import dbus
from collections import OrderedDict
# Set up logging
from qtvcp import logger
LOG = logger.getLogger(__name__)
DBusQtMainLoop = None
for _mod in ('dbus.mainloop.pyqt5', 'dbus.mainloop.pyqt6'):
try:
import importlib
DBusQtMainLoop = importlib.import_module(_mod).DBusQtMainLoop
break
except ImportError:
pass
if DBusQtMainLoop is None:
LOG.warning("Could not import a DBus Qt main loop integration. "
"Install python3-dbus.mainloop.pyqt5 or python3-dbus.mainloop.pyqt6 "
"for desktop notification callbacks.")
APP_NAME = ''
DBUS_IFACE = None
NOTIFICATIONS = {}
class Urgency:
"""freedesktop.org notification urgency levels"""
LOW, NORMAL, CRITICAL = list(range(3))
class UninitializedError(RuntimeError):
"""Error raised if you try to show an error before initializing"""
pass
def init(app_name):
"""Initializes the DBus connection"""
global APP_NAME, DBUS_IFACE
APP_NAME = app_name
name = "org.freedesktop.Notifications"
path = "/org/freedesktop/Notifications"
interface = "org.freedesktop.Notifications"
try:
# Probe on a throwaway no-mainloop connection first. Wiring the
# Qt dbus mainloop before a daemon is confirmed leaves a dangling
# QSocketNotifier that segfaults on its next dispatch.
probe = dbus.SessionBus(private=True)
try:
present = probe.name_has_owner(name)
finally:
probe.close()
if not present:
# No daemon: pop-up notifications cannot be shown.
raise RuntimeError('no notification daemon on the session bus; desktop notifications disabled')
mainloop = DBusQtMainLoop(set_as_default=True) if DBusQtMainLoop else None
bus = dbus.SessionBus(mainloop=mainloop)
proxy = bus.get_object(name, path)
DBUS_IFACE = dbus.Interface(proxy, interface)
if mainloop is not None:
DBUS_IFACE.connect_to_signal('ActionInvoked', _onActionInvoked)
DBUS_IFACE.connect_to_signal('NotificationClosed', _onNotificationClosed)
except Exception as e:
LOG.warning('Desktop Notify not available:: {}'.format(e))
DBUS_IFACE = None
def _onActionInvoked(nid, action):
"""Called when a notification action is clicked"""
nid, action = int(nid), str(action)
try:
notification = NOTIFICATIONS[nid]
except KeyError:
# must have been created by some other program
return
notification._onActionInvoked(action)
def _onNotificationClosed(nid, reason):
"""Called when the notification is closed"""
nid, reason = int(nid), int(reason)
try:
notification = NOTIFICATIONS[nid]
except KeyError:
# must have been created by some other program
return
notification._onNotificationClosed(notification)
del NOTIFICATIONS[nid]
class Notification(object):
"""Notification object"""
id = 0
timeout = -1
_onNotificationClosed = lambda *args: None
def __init__(self, title, body='', icon='', timeout=-1):
"""Initializes a new notification object.
Args:
title (str): The title of the notification
body (str, optional): The body text of the notification
icon (str, optional): The icon to display with the notification
timeout (TYPE, optional): The time in ms before the notification hides, -1 for default, 0 for never
"""
self.title = title # title of the notification
self.body = body # the body text of the notification
if icon is None:
icon = '' # Fix for legacy use
self.icon = icon # the path to the icon to use
self.timeout = timeout # time in ms before the notification disappears
self.hints = {} # dict of various display hints
self.actions = OrderedDict() # actions names and their callbacks
self.data = {} # arbitrary user data
self.isVisible = False
def show(self):
try:
if DBUS_IFACE is None:
raise UninitializedError("You must call 'notify.init()' before 'notify.show()'")
"""Asks the notification server to show the notification"""
nid = DBUS_IFACE.Notify(APP_NAME,
self.id,
self.icon,
self.title,
self.body,
self._makeActionsList(),
self.hints,
self.timeout,
)
self.id = int(nid)
self.isVisible = True
NOTIFICATIONS[self.id] = self
return True
except Exception as e:
LOG.debug('Desktop Notify: {}'.format(e))
def close(self):
"""Ask the notification server to close the notification"""
self.isVisible = False
try:
if self.id != 0:
DBUS_IFACE.CloseNotification(self.id)
except:
pass
def onClose(self, callback):
"""Set the callback called when the notification is closed"""
self.isVisible = False
self._onNotificationClosed = callback
def setUrgency(self, value):
"""Set the freedesktop.org notification urgency level"""
if value not in list(range(3)):
raise ValueError("Unknown urgency level '%s' specified" % value)
self.hints['urgency'] = dbus.Byte(value)
def setSoundFile(self, sound_file):
"""Sets a sound file to play when the notification shows"""
self.hints['sound-file'] = sound_file
def setSoundName(self, sound_name):
"""Set a freedesktop.org sound name to play when notification shows"""
self.hints['sound-name'] = sound_name
def setIconPath(self, icon_path):
"""Set the URI of the icon to display in the notification"""
self.hints['image-path'] = 'file://' + icon_path
def setQIcon(self, q_icon):
# FixMe this would be convenient, but may not be possible
raise NotImplementedError
def setLocation(self, x_pos, y_pos):
"""Sets the location to display the notification"""
self.hints['x'] = int(x_pos)
self.hints['y'] = int(y_pos)
def setCategory(self, category):
"""Sets the the freedesktop.org notification category"""
self.hints['category'] = category
def setTimeout(self, timeout):
"""Set the display duration in milliseconds, -1 for default"""
if not isinstance(timeout, int):
raise TypeError("Timeout value '%s' was not int" % timeout)
self.timeout = timeout
def setHint(self, key, value):
"""Set one of the other hints"""
self.hints[key] = value
def addAction(self, action, label, callback, user_data=None):
"""Add an action to the notification.
Args:
action (str): A sort key identifying the action
label (str): The text to display on the action button
callback (bound method): The method to call when the action is activated
user_data (any, optional): Any user data to be passed to the action callback
"""
self.actions[action] = (label, callback, user_data)
def _makeActionsList(self):
"""Make the actions array to send over DBus"""
arr = []
for action, (label, callback, user_data) in list(self.actions.items()):
arr.append(action)
arr.append(label)
return arr
def _onActionInvoked(self, action):
"""Called when the user activates a notification action"""
try:
label, callback, user_data = self.actions[action]
except KeyError:
return
if callback is None:
LOG.INFO('Callback is None: {}'.format(label))
return
if user_data is None:
callback(self, action)
else:
callback(self, action, user_data)
# ----------------------- E X A M P L E -----------------------
def onHelp(n, action):
assert (action == "help"), "Action was not help!"
print("You clicked Help action")
n.close()
def onIgnore(n, action, data):
assert (action == "ignore"), "Action was not ignore!"
print("You clicked Ignore action")
print("Passed user data was: ", data)
n.close()
def onClose(n):
print("Notification closed")
app.quit()
if __name__ == "__main__":
import sys
from qtpy.QtCore import QCoreApplication
app = QCoreApplication(sys.argv)
# Initialize the DBus connection to the notification server
init("demo")
# Initialize a new notification object
n = Notification("Demo Notification",
"This notification is very important as it " +
"notifies you that notifications are working.",
timeout=3000
)
n.setUrgency(Urgency.NORMAL)
n.setCategory("device")
n.setIconPath("/usr/share/icons/Tango/scalable/status/dialog-error.svg")
# no user data
n.addAction("help", "Help", onHelp)
# passing arbitrary user data to the callback
n.addAction("ignore", "Ignore", onIgnore, 12345)
n.onClose(onClose)
n.show()
app.exec()

View File

@@ -0,0 +1,869 @@
#!/usr/bin/env python3
# QTvcp Tool Bar Action
#
# Copyright (c) 2019 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 os
from qtpy import QtWidgets, QtCore
from qtvcp.core import Status, Action, Info
from qtvcp.qt_makegui import VCPWindow
from qtvcp.lib.aux_program_loader import Aux_program_loader
from qtvcp import logger
# Instantiate the libraries with global reference
# INFO holds INI file details
# STATUS gives us status messages from linuxcnc
# LOG is for running code logging
STATUS = Status()
ACTION = Action()
INFO = Info()
AUX_PRGM = Aux_program_loader()
LOG = logger.getLogger(__name__)
WIDGETS = VCPWindow()
# Force the log level for this module
# LOG.setLevel(logger.INFO) # One of DEBUG, INFO, WARNING, ERROR, CRITICAL
CONFIGDIR = os.environ['CONFIG_DIR']
class ToolBarActions():
def __init__(self):
self._recentActionWidget = None
self.recentNum = 0
self.gcode_properties = None
self.maxRecent = 5
self.selected_line = 0
self._viewActiongroup = QtWidgets.QActionGroup(None)
self._touchoffActiongroup = QtWidgets.QActionGroup(None)
self._machineModeActiongroup = QtWidgets.QActionGroup(None)
self._homeSelectedActiongroup = QtWidgets.QActionGroup(None)
self._homeSelectedActiongroup.setExclusive(False)
self.runfromLineWidget = None
def configure_action(self, widget, action, extFunction=None):
action = action.lower()
function = None
def homed_on_loaded_test():
return (STATUS.machine_is_on()
and (STATUS.is_all_homed() or INFO.NO_HOME_REQUIRED)
and STATUS.is_file_loaded())
def homed_on_test():
return (STATUS.machine_is_on()
and (STATUS.is_all_homed() or INFO.NO_HOME_REQUIRED))
def update_properties(d):
self.gcode_properties = d
def update_selected(line):
self.selected_line = line
if self.runfromLineWidget is not None:
self.runfromLineWidget.setText('Run From Line: {}'.format(line))
if action == 'estop':
STATUS.connect('state-estop', lambda w: self.statusOfEstop(widget,True))
STATUS.connect('state-estop-reset', lambda w: self.statusOfEstop(widget,False))
function = (self.actOnEstop)
elif action == 'power':
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop-reset', lambda w: widget.setEnabled(True))
STATUS.connect('state-estop', lambda w: widget.setChecked(False))
STATUS.connect('state-on', lambda w: widget.setChecked(True))
STATUS.connect('state-off', lambda w: widget.setChecked(False))
function = (self.actOnPower)
elif action == 'load_restricted':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(STATUS.machine_is_on()))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
STATUS.connect('all-homed', lambda w: widget.setChecked(True))
function = (self.actOnLoad)
elif action == 'load':
STATUS.connect('interp-idle', lambda w: widget.setEnabled(True))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
function = (self.actOnLoad)
elif action == 'reload':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(STATUS.machine_is_on()))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
STATUS.connect('all-homed', lambda w: widget.setChecked(True))
function = (self.actOnReload)
elif action == 'gcode_properties':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(STATUS.machine_is_on()))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
STATUS.connect('all-homed', lambda w: widget.setChecked(True))
STATUS.connect('graphics-gcode-properties', lambda w, d: update_properties(d))
function = (self.actOnProperties)
elif action == 'run':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(homed_on_test()))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
STATUS.connect('all-homed', lambda w: widget.setEnabled(homed_on_test()))
STATUS.connect('not-all-homed', lambda w, data: widget.setEnabled(False))
STATUS.connect('interp-paused', lambda w: widget.setEnabled(homed_on_test()))
STATUS.connect('file-loaded', lambda w, f: widget.setEnabled(homed_on_test()))
function = (self.actOnRun)
elif action == 'step':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(homed_on_test()))
STATUS.connect('all-homed', lambda w: widget.setEnabled(True))
STATUS.connect('not-all-homed', lambda w, data: widget.setEnabled(False))
function = (self.actOnStep)
elif action == 'pause':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(homed_on_test()))
STATUS.connect('all-homed', lambda w: widget.setEnabled(True))
STATUS.connect('not-all-homed', lambda w, data: widget.setEnabled(False))
STATUS.connect('program-pause-changed', lambda w, state: widget.setChecked(state))
function = (self.actOnPause)
elif action == 'abort':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(homed_on_test()))
STATUS.connect('all-homed', lambda w: widget.setEnabled(True))
STATUS.connect('not-all-homed', lambda w, data: widget.setEnabled(False))
function = (self.actOnAbort)
elif action == 'block_delete':
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('mode-mdi', lambda w: widget.setEnabled(True))
STATUS.connect('mode-manual', lambda w: widget.setEnabled(True))
STATUS.connect('mode-auto', lambda w: widget.setEnabled(False))
STATUS.connect('block-delete-changed', lambda w, data: widget.setChecked(data))
function = (self.actOnBlockDelete)
elif action == 'optional_stop':
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('mode-mdi', lambda w: widget.setEnabled(True))
STATUS.connect('mode-manual', lambda w: widget.setEnabled(True))
STATUS.connect('mode-auto', lambda w: widget.setEnabled(False))
function = (self.actOnOptionalStop)
elif action == 'touchoffworkplace':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(STATUS.machine_is_on()))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
STATUS.connect('all-homed', lambda w: widget.setChecked(True))
function = None
self._touchoffActiongroup.addAction(widget)
self._touchoffActiongroup.setExclusive(True)
elif action == 'touchofffixture':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(STATUS.machine_is_on()))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
STATUS.connect('all-homed', lambda w: widget.setChecked(True))
function = None
self._touchoffActiongroup.addAction(widget)
self._touchoffActiongroup.setExclusive(True)
elif action == 'runfromline':
self.runfromLineWidget = widget
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(homed_on_test()))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
STATUS.connect('mode-auto', lambda w: widget.setEnabled(homed_on_test()))
STATUS.connect('all-homed', lambda w: widget.setChecked(homed_on_test()))
STATUS.connect('gcode-line-selected', lambda w, line: update_selected(line))
function = (self.actOnRunFromLine)
elif action == 'load_calibration':
function = (self.actOnLoadCalibration)
elif action == 'load_halmeter':
function = (self.actOnLoadHalmeter)
elif action == 'load_halshow':
function = (self.actOnLoadHalshow)
elif action == 'load_status':
function = (self.actOnLoadStatus)
elif action == 'load_halscope':
function = (self.actOnLoadHalscope)
elif action == 'about':
function = (self.actOnAbout)
elif action == 'zoom_in':
function = (self.actOnZoomIn)
elif action == 'zoom_out':
function = (self.actOnZoomOut)
elif action == 'view_x':
self._viewActiongroup.addAction(widget)
self._viewActiongroup.setExclusive(True)
function = (self.actOnViewX)
elif action == 'view_y':
self._viewActiongroup.addAction(widget)
self._viewActiongroup.setExclusive(True)
function = (self.actOnViewY)
elif action == 'view_y2':
self._viewActiongroup.addAction(widget)
self._viewActiongroup.setExclusive(True)
function = (self.actOnViewY2)
elif action == 'view_z':
self._viewActiongroup.addAction(widget)
self._viewActiongroup.setExclusive(True)
function = (self.actOnViewZ)
elif action == 'view_z2':
self._viewActiongroup.addAction(widget)
self._viewActiongroup.setExclusive(True)
function = (self.actOnViewZ2)
elif action == 'view_p':
self._viewActiongroup.addAction(widget)
self._viewActiongroup.setExclusive(True)
function = (self.actOnViewp)
elif action == 'view_clear':
function = (self.actOnViewClear)
elif action == 'show_offsets':
function = (self.actOnViewOffsets)
elif action == 'large_dro':
function = (self.actOnLargeDRO)
elif action == 'quit':
function = (self.actOnQuit)
elif action == 'system_shutdown':
function = (self.actOnSystemShutdown)
elif action == 'tooloffsetdialog':
function = (self.actOnToolOffsetDialog)
elif action == 'toolchooserdialog':
function = (self.actOnToolChooserDialog)
elif action == 'originoffsetdialog':
function = (self.actOnOriginOffsetDialog)
elif action == 'calculatordialog':
function = (self.actOnCalculatorDialog)
elif action == 'alpha_mode':
function = (self.actOnAlphaMode)
elif action == 'inhibit_selection':
function = (self.actOnInhibitSelection)
elif action == 'show_dimensions':
function = (self.actOnShowDimensions)
elif action == 'message_recall':
function = (self.actOnMessageRecall)
elif action == 'message_close':
function = (self.actOnMessageClose)
elif action == 'homeall':
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop-reset', lambda w: widget.setEnabled(True))
STATUS.connect('state-estop', lambda w: widget.setChecked(False))
function = (self.actOnHomeAll)
elif action == 'unhomeall':
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop-reset', lambda w: widget.setEnabled(True))
STATUS.connect('state-estop', lambda w: widget.setChecked(False))
function = (self.actOnUnHomeAll)
elif action == 'homeselected':
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop-reset', lambda w: widget.setEnabled(True))
STATUS.connect('state-estop', lambda w: widget.setChecked(False))
function = (self.actOnHomeSelected)
elif action == 'unhomeselected':
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop-reset', lambda w: widget.setEnabled(True))
STATUS.connect('state-estop', lambda w: widget.setChecked(False))
function = (self.actOnUnHomeSelected)
elif action in ('selecthomex'):
widget.JOINT = 0
self._homeSelectedActiongroup.addAction(widget)
elif action in ('selecthomez'):
widget.JOINT = 2
self._homeSelectedActiongroup.addAction(widget)
elif action == 'manual':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(STATUS.machine_is_on()))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
STATUS.connect('mode-manual', lambda w: widget.setChecked(True))
#STATUS.connect('mode-mdi', lambda w: widget.setChecked(False))
self._machineModeActiongroup.addAction(widget)
self._machineModeActiongroup.setExclusive(True)
function = (self.actOnManualMode)
elif action == 'mdi':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(STATUS.machine_is_on()))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
STATUS.connect('mode-mdi', lambda w: widget.setChecked(True))
self._machineModeActiongroup.addAction(widget)
self._machineModeActiongroup.setExclusive(True)
function = (self.actOnMDIMode)
elif action == 'auto':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(STATUS.machine_is_on()))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
STATUS.connect('mode-auto', lambda w: widget.setChecked(True))
self._machineModeActiongroup.addAction(widget)
self._machineModeActiongroup.setExclusive(True)
function = (self.actOnAutoMode)
elif action == 'joint_mode':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(STATUS.machine_is_on()))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
STATUS.connect('mode-auto', lambda w: widget.setChecked(True))
STATUS.connect('motion-mode-changed', lambda w,data: \
widget.setChecked(STATUS.is_joint_mode()))
function = (self.actOnJointMode)
elif action == 'axis_mode':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(STATUS.machine_is_on()))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
STATUS.connect('mode-auto', lambda w: widget.setChecked(True))
STATUS.connect('motion-mode-changed', lambda w,data: \
widget.setChecked(STATUS.is_world_mode()))
function = (self.actOnAxisMode)
elif not extFunction:
LOG.warning('Unrecogzied action command: {}'.format(action))
# Call an external function when triggered. If it's checkable; add state
if extFunction:
if widget.isCheckable():
widget.triggered.connect(lambda state: extFunction(widget, state))
else:
widget.triggered.connect(lambda: extFunction(widget))
# Call a function when triggered. If it's checkable; add state
elif function:
if widget.isCheckable():
widget.triggered.connect(lambda state: function(widget, state))
else:
widget.triggered.connect(lambda: function(widget))
def configure_submenu(self, widget, submenu):
submenu = submenu.lower()
if submenu == 'home_submenu':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(STATUS.machine_is_on()))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
self.addHomeActions(widget)
elif submenu == 'unhome_submenu':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(STATUS.machine_is_on()))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
self.addUnHomeActions(widget)
elif submenu == 'recent_submenu':
self._recentActionWidget = widget
STATUS.connect('interp-idle', lambda w: widget.setEnabled(True))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
STATUS.connect('file-loaded', lambda w, d: self.updateRecentPaths(widget, d))
self.addRecentPaths()
elif submenu == 'recent_submenu_restricted':
self._recentActionWidget = widget
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(STATUS.machine_is_on()))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
STATUS.connect('all-homed', lambda w: widget.setEnabled(True))
STATUS.connect('file-loaded', lambda w, d: self.updateRecentPaths(widget, d))
self.addRecentPaths()
elif submenu == 'zero_systems_submenu':
STATUS.connect('state-off', lambda w: widget.setEnabled(False))
STATUS.connect('state-estop', lambda w: widget.setEnabled(False))
STATUS.connect('interp-idle', lambda w: widget.setEnabled(STATUS.machine_is_on()))
STATUS.connect('interp-run', lambda w: widget.setEnabled(False))
STATUS.connect('all-homed', lambda w: widget.setEnabled(True))
self.addZeroSystemsActions(widget)
elif submenu == 'grid_size_submenu':
self.addGridSize(widget)
else:
LOG.warning('Unrecogzied sunmenu command: {}'.format(submenu))
def configure_statusbar(self, widget, option):
if option == 'message_controls':
self.addMessageControlsClose(widget)
self.addMessageControlsRecall(widget)
elif option == 'message_recall':
self.addMessageControlsRecall(widget)
elif option == 'message_close':
self.addMessageControlsClose(widget)
else:
LOG.warning('Unrecogzied statusbar command: {}'.format(option))
#########################################################
# Standard Actions
#########################################################
# estop button checked status follows linuxcnc E stop state
# we kep the button state the same, while we request a linuxcnc state
# change
def actOnEstop(self, widget, state):
widget.blockSignals(True)
if STATUS.estop_is_clear():
widget.setChecked(False)
else:
widget.setChecked(True)
widget.blockSignals(False)
ACTION.SET_ESTOP_STATE(state)
# estop button checked status follows linuxcnc E stop state
def statusOfEstop(self, widget, state):
if STATUS.estop_is_clear():
widget.setChecked(False)
else:
widget.setChecked(True)
def actOnPower(self, widget, state):
ACTION.SET_MACHINE_STATE(state)
def actOnLoad(self, widget, state=None):
STATUS.emit('dialog-request', {'NAME': 'LOAD'})
def actOnReload(self, widget, state=None):
STATUS.emit('reload-display')
def actOnProperties(self, widget, state=None):
# substitute nice looking text:
property_names = {
'name': "Name:", 'size': "Size:",
' tools': "Tool order:", 'g0': "Rapid distance:",
'g1': "Feed distance:", 'g': "Total distance:",
'run': "Run time:",'machine_unit_sys':"Machine Unit System:",
'x': "X bounds:",'x_zero_rxy':'X @ Zero Rotation:',
'y': "Y bounds:",'y_zero_rxy':'Y @ Zero Rotation:',
'z': "Z bounds:",'z_zero_rxy':'Z @ Zero Rotation:',
'a': "A bounds:", 'b': "B bounds:",
'c': "C bounds:",'toollist':'Tool Change List:',
'gcode_units':"Gcode Units:"
}
mess = ''
if self.gcode_properties:
for i in self.gcode_properties:
mess += '<span style=" font-size:16pt; font-weight:600; color:black;">%s </span>\
<span style=" font-size:12pt; font-weight:600; color:#aa0000;">%s</span>\
<br>'% (property_names.get(i), self.gcode_properties[i])
# pop a dialog of the properties
msg = QtWidgets.QMessageBox()
msg.setIcon(QtWidgets.QMessageBox.Information)
msg.setText(mess)
msg.setWindowTitle("Gcode Properties")
msg.setStandardButtons(QtWidgets.QMessageBox.Ok)
msg.show()
retval = msg.exec()
def actOnRun(self, widget, state=None):
ACTION.RUN()
def actOnStep(self, widget, state=None):
ACTION.STEP()
def actOnPause(self, widget, state=None):
ACTION.PAUSE()
def actOnAbort(self, widget, state=None):
ACTION.ABORT()
def actOnBlockDelete(self, widget, state):
if state:
ACTION.SET_BLOCK_DELETE_ON()
else:
ACTION.SET_BLOCK_DELETE_OFF()
def actOnOptionalStop(self, widget, state):
if state:
ACTION.SET_OPTIONAL_STOP_ON()
else:
ACTION.SET_OPTIONAL_STOP_OFF()
def actOnLoadCalibration(self, widget, state=None):
AUX_PRGM.load_calibration()
def actOnLoadHalmeter(self, widget, state=None):
AUX_PRGM.load_halmeter()
def actOnLoadStatus(self, widget, state=None):
AUX_PRGM.load_status()
def actOnLoadHalshow(self, widget, state=None):
AUX_PRGM.load_halshow()
def actOnLoadHalscope(self, widget, state=None):
AUX_PRGM.load_halscope()
def actOnLoadExtTooledit(self, widget, state=None):
AUX_PRGM.load_tooledit()
def actOnLoadClassicladder(self, widget, state=None):
AUX_PRGM.load_ladder()
def actOnZoomIn(self, widget, state=None):
ACTION.SET_GRAPHICS_VIEW('zoom-in')
def actOnZoomOut(self, widget, state=None):
ACTION.SET_GRAPHICS_VIEW('zoom-out')
def actOnViewX(self, widget, state=None):
ACTION.SET_GRAPHICS_VIEW('x')
def actOnViewY(self, widget, state=None):
ACTION.SET_GRAPHICS_VIEW('y')
def actOnViewY2(self, widget, state=None):
ACTION.SET_GRAPHICS_VIEW('y2')
def actOnViewZ(self, widget, state=None):
ACTION.SET_GRAPHICS_VIEW('z')
def actOnViewZ2(self, widget, state=None):
ACTION.SET_GRAPHICS_VIEW('z2')
def actOnViewp(self, widget, state=None):
ACTION.SET_GRAPHICS_VIEW('p')
def actOnViewClear(self, widget, state=None):
ACTION.SET_GRAPHICS_VIEW('clear')
def actOnViewOffsets(self, widget, state=None):
if state:
ACTION.SET_GRAPHICS_VIEW('overlay-offsets-on')
else:
ACTION.SET_GRAPHICS_VIEW('overlay-offsets-off')
def actOnLargeDRO(self, widget, state=None):
if state:
ACTION.SET_GRAPHICS_VIEW('set-large-dro')
else:
ACTION.SET_GRAPHICS_VIEW('set-small-dro')
def actOnQuit(self, widget, state=None):
WIDGETS.close()
def actOnSystemShutdown(self, widget, state=None):
if 'system_shutdown_request__' in dir(WIDGETS):
# do whatever the handler file's function requires
WIDGETS.system_shutdown_request__()
# make sure to close qtvcp/linuxcnc properly
# screenoptions widget redirects the close function to add a prompt
# now we re-redirect to remove the prompt
WIDGETS.closeEvent = WIDGETS.originalCloseEvent_
WIDGETS.close()
else:
ACTION.SHUT_SYSTEM_DOWN_PROMPT()
def actOnAbout(self, widget, state=None):
# there should be a default dialog loaded from screenoptions
try:
info = ACTION.GET_ABOUT_INFO()
WIDGETS.aboutDialog_.showdialog()
return
except:
pass
# ok we will build one then
msg = QtWidgets.QMessageBox()
mess = ''
path = os.path.join(CONFIGDIR, 'README')
if os.path.exists(path):
for line in open(path):
mess += line
msg.setWindowTitle("README")
else:
msg.setWindowTitle("About")
mess = 'This is a QtVCP based screen for Linuxcnc'
msg.setText(mess)
msg.setIcon(QtWidgets.QMessageBox.Information)
msg.setStandardButtons(QtWidgets.QMessageBox.Ok)
msg.show()
retval = msg.exec()
def actOnRunFromLine(self, widget, state=False):
STATUS.emit('dialog-request', {'NAME': 'RUNFROMLINE', 'LINE':self.selected_line})
#ACTION.RUN(self.selected_line)
def actOnToolChooserDialog(self, widget, state=None):
STATUS.emit('dialog-request', {'NAME': 'TOOLCHOOSER'})
def actOnToolOffsetDialog(self, widget, state=None):
STATUS.emit('dialog-request', {'NAME': 'TOOLOFFSET'})
def actOnOriginOffsetDialog(self, widget, state=None):
STATUS.emit('dialog-request', {'NAME': 'ORIGINOFFSET'})
def actOnCalculatorDialog(self, widget, state=None):
STATUS.emit('dialog-request', {'NAME': 'CALCULATOR'})
def actOnAlphaMode(self, widget, state):
if state:
ACTION.SET_GRAPHICS_VIEW('alpha-mode-on')
else:
ACTION.SET_GRAPHICS_VIEW('alpha-mode-off')
def actOnInhibitSelection(self, widget, state):
if state:
ACTION.SET_GRAPHICS_VIEW('inhibit-selection-on')
else:
ACTION.SET_GRAPHICS_VIEW('inhibit-selection-off')
def actOnShowDimensions(self, widget, state):
if state:
ACTION.SET_GRAPHICS_VIEW('dimensions-on')
else:
ACTION.SET_GRAPHICS_VIEW('dimensions-off')
def actOnMessageClose(self, widget, state=None):
WIDGETS._NOTICE.external_close()
def actOnMessageRecall(self, widget, state=None):
WIDGETS._NOTICE.show_last()
def actOnHomeAll(self, widget, state=None):
ACTION.SET_MACHINE_HOMING(-1)
def actOnUnHomeAll(self, widget, state=None):
ACTION.SET_MACHINE_UNHOMED(-1)
# assumed there are axis selection actions
# and one for every available axis
def actOnHomeSelected(self, widget, state=None):
l = self._homeSelectedActiongroup.actions()
temp = []
for i in l:
if i.isChecked():
temp.append(i)
if len(temp) == len(l):
ACTION.SET_MACHINE_HOMING(-1)
else:
for i in temp:
ACTION.SET_MACHINE_HOMING(i.JOINT)
# assumed there are axis selection actions
# and one for every available axis
def actOnUnHomeSelected(self, widget, state=None):
l = self._homeSelectedActiongroup.actions()
temp = []
for i in l:
if i.isChecked():
temp.append(i)
if len(temp) == len(l):
ACTION.SET_MACHINE_UNHOMED(-1)
else:
for i in temp:
ACTION.SET_MACHINE_UNHOMED(i.JOINT)
def actOnManualMode(self, widget, state=None):
ACTION.SET_MANUAL_MODE()
def actOnMDIMode(self, widget, state=None):
ACTION.SET_MDI_MODE()
def actOnAutoMode(self, widget, state=None):
ACTION.SET_AUTO_MODE()
def actOnJointMode(self, widget, state=None):
ACTION.SET_MOTION_TELEOP(0)
def actOnAxisMode(self, widget, state=None):
ACTION.SET_MOTION_TELEOP(1)
#########################################################
# Sub menus
#########################################################
def addHomeActions(self, widget):
def home(joint):
ACTION.SET_MACHINE_HOMING(joint)
conversion = {"X": 0, "Y": 1, "Z": 2, "A": 3, "B": 4, "C": 5, "U": 6, "V": 7, "W": 8}
homeAct = QtWidgets.QAction('Home ALL', widget)
homeAct.triggered.connect(lambda: home(-1))
widget.addAction(homeAct)
for i in INFO.AVAILABLE_AXES:
homeAct = QtWidgets.QAction('Home %s' % i, widget)
# weird lambda i=i to work around 'function closure'
homeAct.triggered.connect(lambda state, i=i: home(conversion[i]))
widget.addAction(homeAct)
def addUnHomeActions(self, widget):
def unHome(joint):
ACTION.SET_MACHINE_UNHOMED(joint)
conversion = {"X": 0, "Y": 1, "Z": 2, "A": 3, "B": 4, "C": 5, "U": 6, "V": 7, "W": 8}
homeAct = QtWidgets.QAction('Unhome ALL', widget)
homeAct.triggered.connect(lambda: unHome(-1))
widget.addAction(homeAct)
for i in INFO.AVAILABLE_AXES:
homeAct = QtWidgets.QAction('Unhome %s' % i, widget)
# weird lambda i=i to work around 'function closure'
homeAct.triggered.connect(lambda state, i=i: unHome(conversion[i]))
widget.addAction(homeAct)
def addZeroSystemsActions(self, widget):
# no idea why I can't use a for loop to build this like above
# but it never returned the right system index
zeroSysAct = QtWidgets.QAction('G54', widget)
zeroSysAct.triggered.connect(lambda: ACTION.ZERO_G5X_OFFSET(1))
widget.addAction(zeroSysAct)
zeroSysAct = QtWidgets.QAction('G55', widget)
zeroSysAct.triggered.connect(lambda: ACTION.ZERO_G5X_OFFSET(2))
widget.addAction(zeroSysAct)
zeroSysAct = QtWidgets.QAction('G56', widget)
zeroSysAct.triggered.connect(lambda: ACTION.ZERO_G5X_OFFSET(3))
widget.addAction(zeroSysAct)
zeroSysAct = QtWidgets.QAction('G57', widget)
zeroSysAct.triggered.connect(lambda: ACTION.ZERO_G5X_OFFSET(4))
widget.addAction(zeroSysAct)
zeroSysAct = QtWidgets.QAction('G58', widget)
zeroSysAct.triggered.connect(lambda: ACTION.ZERO_G5X_OFFSET(5))
widget.addAction(zeroSysAct)
zeroSysAct = QtWidgets.QAction('G59', widget)
zeroSysAct.triggered.connect(lambda: ACTION.ZERO_G5X_OFFSET(6))
widget.addAction(zeroSysAct)
zeroSysAct = QtWidgets.QAction('G59.1', widget)
zeroSysAct.triggered.connect(lambda: ACTION.ZERO_G5X_OFFSET(7))
widget.addAction(zeroSysAct)
zeroSysAct = QtWidgets.QAction('G59.2', widget)
zeroSysAct.triggered.connect(lambda: ACTION.ZERO_G5X_OFFSET(8))
widget.addAction(zeroSysAct)
zeroSysAct = QtWidgets.QAction('G59.3', widget)
zeroSysAct.triggered.connect(lambda: ACTION.ZERO_G5X_OFFSET(9))
widget.addAction(zeroSysAct)
zeroSysAct = QtWidgets.QAction('G92', widget)
zeroSysAct.triggered.connect(lambda: ACTION.ZERO_G92_OFFSET())
widget.addAction(zeroSysAct)
zeroSysAct = QtWidgets.QAction('Rotaional', widget)
zeroSysAct.triggered.connect(lambda: ACTION.ZERO_ROTATIONAL_OFFSET())
widget.addAction(zeroSysAct)
def updateRecentPaths(self, widget, filename):
def loadRecent(w):
ACTION.OPEN_PROGRAM(w.text())
# get a list of the current actions
alist = widget.actions()
# build the action
impAct = QtWidgets.QAction(filename, widget)
impAct.triggered.connect(lambda: loadRecent(impAct))
# adding actions is different if it's the first
# if it's not the first add it before the first
try:
widget.insertAction(alist[0], impAct)
except:
widget.addAction(impAct)
# is this a duplicate ?
for i in alist:
if i.text() == filename:
widget.removeAction(i)
return
# are we past 5 files? remove the lowest
# else update current number
if self.recentNum > self.maxRecent:
widget.removeAction(alist[self.maxRecent])
else:
self.recentNum += 1
def addRecentPaths(self):
if self._recentActionWidget is not None and WIDGETS.PREFS_ is not None:
for num in range(self.maxRecent, -1, -1):
path_string = WIDGETS.PREFS_.getpref('RecentPath_%d' % num, None, str, 'BOOK_KEEPING')
if not path_string in ('None', None):
self.updateRecentPaths(self._recentActionWidget, path_string)
def saveRecentPaths(self):
if self._recentActionWidget is not None and WIDGETS.PREFS_ is not None:
for num, i in enumerate(self._recentActionWidget.actions()):
WIDGETS.PREFS_.putpref('RecentPath_%d' % num, i.text(), str, 'BOOK_KEEPING')
def addGridSize(self, widget):
def setSize(data):
ACTION.SET_GRAPHICS_GRID_SIZE(data)
print(INFO.GRID_INCREMENTS)
for temp in (INFO.GRID_INCREMENTS):
if temp == '0':
sizeAct = QtWidgets.QAction('Off', widget)
sizeAct.triggered.connect(lambda: setSize(0))
widget.addAction(sizeAct)
continue
i = self.parse_increment(temp)
sizeAct = QtWidgets.QAction('%s' % temp, widget)
# weird lambda i=i to work around 'function closure'
sizeAct.triggered.connect(lambda state, i=i: setSize(i))
widget.addAction(sizeAct)
# We convert INI parced increments to machine units
def parse_increment(self, gridIncr):
if gridIncr.endswith("mm"):
scale = self.conversion(1)
elif gridIncr.endswith("cm"):
scale = self.conversion(10)
elif gridIncr.endswith("um"):
scale = self.conversion(.001)
elif gridIncr.endswith("in") or gridIncr.endswith("inch"):
scale = self.conversion(1., metric=False)
elif gridIncr.endswith("mil"):
scale = self.conversion(.001, metric=False)
else:
scale = 1
incr = gridIncr.rstrip(" inchmuil")
if "/" in incr:
p, q = incr.split("/")
incr = float(p) / float(q)
else:
incr = float(incr)
LOG.debug("parceed: text: {} Increment: {} scaled: {}".format(gridIncr, incr, (incr * scale)))
return incr * scale
# This does the conversion
# calling function must tell us if the data is metric or not.
def conversion(self, data, metric=True):
if INFO.MACHINE_IS_METRIC:
if metric:
return INFO.convert_metric_to_machine(data)
else:
return INFO.convert_imperial_to_machine(data)
else:
if metric:
return INFO.convert_metric_to_machine(data)
else:
return INFO.convert_imperial_to_machine(data)
###############################################
# status bar
###############################################
def addMessageControlsClose(self, bar):
def close():
WIDGETS._NOTICE.external_close()
bar.setMaximumHeight(20)
bar.setSizeGripEnabled(False)
WIDGETS.statusClear = QtWidgets.QPushButton()
icon = QtWidgets.QApplication.style().standardIcon(QtWidgets.QStyle.SP_MessageBoxCritical)
WIDGETS.statusClear.setIcon(icon)
WIDGETS.statusClear.setMaximumSize(20, 20)
WIDGETS.statusClear.setIconSize(QtCore.QSize(22, 22))
WIDGETS.statusClear.clicked.connect(lambda: close())
bar.addPermanentWidget(WIDGETS.statusClear)
def addMessageControlsRecall(self, bar):
def last():
WIDGETS._NOTICE.show_last()
bar.setMaximumHeight(20)
bar.setSizeGripEnabled(False)
icon = QtWidgets.QApplication.style().standardIcon(QtWidgets.QStyle.SP_MessageBoxInformation)
WIDGETS.statusLast = QtWidgets.QPushButton()
WIDGETS.statusLast.setIcon(icon)
WIDGETS.statusLast.setMaximumSize(20, 20)
WIDGETS.statusLast.setIconSize(QtCore.QSize(22, 22))
WIDGETS.statusLast.clicked.connect(lambda: last())
bar.addPermanentWidget(WIDGETS.statusLast)

View File

@@ -0,0 +1,295 @@
#!/usr/bin/env python3
# Qtvcp touchoff and workpiece height measurement
#
# Copyright (c) 2022 Jim Sloot <persei802@gmail.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.
# This subprogram is used for qtdragon_handler touchoff routines
# and the qtdragon workpiece height measurement utility.
# It enables the probe routines to run without blocking the main GUI.
import sys
import json
import time
import linuxcnc
from qtpy.QtCore import QObject
from qtvcp.core import Status, Action, Info
from qtvcp import logger
LOG = logger.getLogger(__name__)
# Force the log level for this module
#LOG.setLevel(logger.ERROR) # One of DEBUG, INFO, WARNING, ERROR, CRITICAL
STATUS = Status()
ACTION = Action()
INFO = Info()
class TouchOffSubprog(QObject):
def __init__(self):
QObject.__init__(self)
self.timeout = 30
# input parameters
self.search_vel = 10.0
self.probe_vel = 10.0
self.max_probe = 10.0
self.retract_distance = 10.0
self.z_safe_travel = 10.0
self.z_offset = 0.0
self.pos_x1 = 10.0
self.pos_y1 = 10.0
self.pos_z1 = 10.0
self.pos_x2 = 10.0
self.pos_y2 = 10.0
self.pos_z2 = 10.0
# output results
self.status_z1 = 0.0
self.status_z2 = 0.0
self.send_dict = {}
self.string_to_send = ""
self.parm_list = ['search_vel',
'probe_vel',
'max_probe',
'retract_distance',
'z_safe_travel',
'pos_x1',
'pos_y1',
'pos_z1',
'pos_x2',
'pos_y2',
'pos_z2']
self.process()
# mdi timeout setting
def set_timeout(self, time):
self.timeout = time
def process(self):
while 1:
try:
cmd = sys.stdin.readline()
if cmd:
error = self.process_command(cmd)
# block polling here. main program should start polling in their end
STATUS.block_error_polling()
# error = 1 means success, error = None means ignore, anything else is an error
if error is not None:
if error != 1:
if type(error) == str:
sys.stdout.write("ERROR Touchoff routine: {}\n".format(error))
else:
sys.stdout.write("ERROR Touchoff returned with error from cmd:{}\n".format(cmd))
else:
self.collect_status()
sys.stdout.write("{} COMPLETE$ {}\n".format(cmd.rstrip().split('$')[0], self.string_to_send))
else:
sys.stdout.write("COMPLETE$ returned FROM COMMAND:{}\n".format(cmd))
sys.stdout.flush()
except KeyboardInterrupt:
break
except Exception as e:
sys.stdout.write("ERROR Touchoff command error: {}\n".format(e))
sys.stdout.flush()
break
def process_command(self, cmd):
cmd = cmd.rstrip().split('$')
if not STATUS.is_on_and_idle(): return None
pre = self.prechecks()
if pre is not None: return pre
# start polling errors here - parent program should have blocked their polling
STATUS.unblock_error_polling()
ACTION.CALL_MDI("G49")
LOG.debug('COMMAND= {}'.format(cmd))
if cmd[0] == "touchoff":
self.search_vel = float(cmd[1])
self.probe_vel = float(cmd[2])
self.max_probe = float(cmd[3])
self.retract_distance = float(cmd[4])
self.z_safe_travel = float(cmd[5])
self.z_offset = float(cmd[6])
error = self.touchoff()
elif cmd[0] == "probe_z":
parms = json.loads(cmd[1])
self.update_data(parms)
error = self.probe_z()
else:
return 'No such touchoff routine'
self.postreset()
return error
def CALL_MDI_WAIT(self, code, timeout = 5):
LOG.debug('MDI_WAIT_COMMAND= {}, maxt = {}'.format(code, timeout))
for l in code:
try:
ACTION.CALL_MDI( l )
result = ACTION.cmd.wait_complete(timeout)
# give a chance for the error message to get to stdin
time.sleep(.1)
error = STATUS.ERROR.poll()
if not error is None:
ACTION.ABORT()
LOG.debug('MDI error= {}'.format( error[1]))
return error[1]
except Exception as e:
ACTION.ABORT()
return e
if result == -1:
ACTION.ABORT()
return 'Command timed out: ({} second)'.format(timeout)
elif result == linuxcnc.RCS_ERROR:
ACTION.ABORT()
return 'MDI_COMMAND_WAIT RCS error'
return 1
# need to be in the right mode - entries are in machine units
def prechecks(self):
ACTION.RECORD_CURRENT_MODE()
# This is a work around. If a user sets the spindle running in MDI
# but turn it off with a manual button, then when M72 will turn the
# spindle back on! So we explicitly set M5 here.
ACTION.CALL_MDI('M5')
ACTION.CALL_MDI('M70')
if INFO.MACHINE_IS_METRIC and STATUS.is_metric_mode():
return None
if not INFO.MACHINE_IS_METRIC and not STATUS.is_metric_mode():
return None
# record motion modes
if INFO.MACHINE_IS_METRIC:
ACTION.CALL_MDI('g21')
else:
ACTION.CALL_MDI('g20')
return None
# return to previous motion modes
def postreset(self):
ACTION.CALL_MDI('M72')
ACTION.RESTORE_RECORDED_MODE()
def touchoff(self):
name = 'Touchoff'
ACTION.CALL_MDI("G10 L20 P0 Z0")
rtn = self.probe_down()
if rtn != 1:
ACTION.CALL_MDI("G90")
return '{} failed: {}'.format(name, rtn)
cmdList = []
cmdList.append("G10 L20 P0 Z{}".format(self.z_offset))
cmdList.append("G1 Z{} F{}".format(self.retract_distance, self.search_vel))
cmdList.append("G90")
rtn = self.CALL_MDI_WAIT(cmdList, self.timeout)
if rtn != 1:
return '{} failed: {}'.format(name, rtn)
return 1
def probe_z(self):
name = 'Probe Z 1st positioning'
# rapid jog to first probe position
cmdList = []
cmdList.append( "G0 Z{}".format(self.z_safe_travel))
cmdList.append( "G0 X{} Y{}".format(self.pos_x1, self.pos_y1))
cmdList.append( "G0 Z{}".format(self.pos_z1))
rtn = self.CALL_MDI_WAIT(cmdList, self.timeout)
if rtn != 1:
return '{} failed: {}'.format(name, rtn)
error = self.probe_down()
ACTION.CALL_MDI("G90")
if error != 1: return error
pos = STATUS.get_probed_position_with_offsets()
self.status_z1 = float(pos[2])
name = 'Probe Z 2nd positioning'
# rapid jog to second probe position
cmdList=[]
cmdList.append("G0 Z{}".format(self.z_safe_travel))
cmdList.append("G0 X{} Y{}".format(self.pos_x2, self.pos_y2))
cmdList.append("G0 Z{}".format(self.pos_z2))
rtn = self.CALL_MDI_WAIT(cmdList, self.timeout)
if rtn != 1:
return '{} failed: {}'.format(name, rtn)
error = self.probe_down()
ACTION.CALL_MDI("G90")
if error != 1: return error
pos = STATUS.get_probed_position_with_offsets()
self.status_z2 = float(pos[2])
s = "G0 Z{}".format(self.z_safe_travel)
rtn = self.CALL_MDI_WAIT([s], self.timeout)
if rtn != 1:
return 'Probe {} failed: {}'.format(name, rtn)
return 1
def probe_down(self):
name = '1st Probe down'
ACTION.CALL_MDI("G91")
cmd = "G38.2 Z-{} F{}".format(self.max_probe, self.search_vel)
rtn = self.CALL_MDI_WAIT([cmd], self.timeout)
if rtn != 1:
return '{} failed: {}'.format(name, rtn)
name = 'Probe retract'
cmd = "G1 Z{} F{}".format(self.retract_distance, self.search_vel)
rtn = self.CALL_MDI_WAIT([cmd], self.timeout)
if rtn != 1:
return '{} failed: {}'.format(name, rtn)
name = '2nd Probe down'
ACTION.CALL_MDI("G4 P0.5")
cmd = "G38.2 Z-{} F{}".format(1.1 * self.retract_distance, self.probe_vel)
rtn = self.CALL_MDI_WAIT([cmd], self.timeout)
if rtn != 1:
return '{} failed: {}'.format(name, rtn)
# success
return 1
def update_data(self, parms):
for key in parms:
self[key] = float(parms[key].encode('utf-8'))
# clear previous probe result
self.status_z1 = 0.0
self.status_z2 = 0.0
def collect_status(self):
data = format(self.status_z1, '.3f')
self.send_dict.update( {'z1': data} )
data = format(self.status_z2, '.3f')
self.send_dict.update( {'z2': data} )
self.string_to_send = json.dumps(self.send_dict)
# required code for subscriptable iteration
def __getitem__(self, item):
return getattr(self, item)
def __setitem__(self, item, value):
return setattr(self, item, value)
####################################
# Testing
####################################
if __name__ == "__main__":
w = TouchOffSubprog()

View File

@@ -0,0 +1,63 @@
# Set up logging
from qtvcp import logger
log = logger.getLogger(__name__)
import subprocess
import os
from qtvcp.qt_glib import GStat
# Instantiate the libraries with global reference
# GSTAT gives us status messages from linuxcnc
GSTAT = GStat()
class virt_keyboard():
def _init__(self):
pass
def _hal_init(self):
GSTAT.connect('virtual-keyboard', self.command)
def command(self, w, command):
if command.lower() == 'show':
self.init_keyboard()
else:
self.kiil_keyboard()
def init_keyboard(self, args="", x="", y=""):
# now we check if onboard or matchbox-keyboard is installed
try:
if os.path.isfile("/usr/bin/onboard"):
self.onboard_kb = subprocess.Popen(["onboard", "--xid", args, x, y],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
close_fds=True)
elif os.path.isfile("/usr/bin/matchbox-keyboard"):
self.onboard_kb = subprocess.Popen(["matchbox-keyboard", "--xid"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
close_fds=True)
else:
return
sid = self.onboard_kb.stdout.readline()
log.debug("XID: {}".format(sid))
# socket = gtk.Socket()
# socket.show()
# self.widgets.key_box.add( socket )
# socket.add_id( long( sid ) )
except Exception as e:
pass
def kill_keyboard(self):
try:
self.onboard_kb.kill()
self.onboard_kb.terminate()
self.onboard_kb = None
except:
try:
self.onboard_kb.kill()
self.onboard_kb.terminate()
self.onboard_kb = None
except:
pass

View File

View File

@@ -0,0 +1 @@
__all__ = ["find","datetime","wordcount","table"]

View File

@@ -0,0 +1,62 @@
from qtpy import QtWidgets
#PYQT5 QDialog, QPushButton, QGridLayout, QComboBox
from qtpy import QtGui, QtCore
from qtpy.QtCore import Qt
from time import strftime
class DateTime(QtWidgets.QDialog):
def __init__(self,parent = None):
QtWidgets.QDialog.__init__(self, parent)
self.parent = parent
self.formats = ["%A, %d. %B %Y %H:%M",
"%A, %d. %B %Y",
"%d. %B %Y %H:%M",
"%d.%m.%Y %H:%M",
"%d. %B %Y",
"%d %m %Y",
"%d.%m.%Y",
"%x",
"%X",
"%H:%M"]
self.initUI()
def initUI(self):
self.box = QtWidgets.QComboBox(self)
for i in self.formats:
self.box.addItem(strftime(i))
insert = QtWidgets.QPushButton("Insert",self)
insert.clicked.connect(self.insert)
cancel = QtWidgets.QPushButton("Cancel",self)
cancel.clicked.connect(self.close)
layout = QtWidgets.QGridLayout()
layout.addWidget(self.box,0,0,1,2)
layout.addWidget(insert,1,0)
layout.addWidget(cancel,1,1)
self.setGeometry(300,300,400,80)
self.setWindowTitle("Date and Time")
self.setLayout(layout)
def insert(self):
# Grab cursor
cursor = self.parent.text.textCursor()
datetime = strftime(self.formats[self.box.currentIndex()])
# Insert the comboBox's current text
cursor.insertText(datetime)
# Close the window
self.close()

View File

@@ -0,0 +1,159 @@
from qtpy import QtWidgets
#PYQT5 QTextEdit, QDialog, QPushButton, QRadioButton, QGridLayout
from qtpy import QtGui, QtCore
from qtpy.QtCore import Qt
import re
class Find(QtWidgets.QDialog):
def __init__(self, parent = None):
QtWidgets.QDialog.__init__(self, parent)
self.parent = parent
self.lastStart = 0
self.initUI()
def initUI(self):
# Button to search the document for something
findButton = QtWidgets.QPushButton("Find",self)
findButton.clicked.connect(self.find)
# Button to replace the last finding
replaceButton = QtWidgets.QPushButton("Replace",self)
replaceButton.clicked.connect(self.replace)
# Button to remove all findings
allButton = QtWidgets.QPushButton("Replace all",self)
allButton.clicked.connect(self.replaceAll)
# Normal mode - radio button
self.normalRadio = QtWidgets.QRadioButton("Normal",self)
# Regular Expression Mode - radio button
regexRadio = QtWidgets.QRadioButton("RegEx",self)
# The field into which to type the query
self.findField = QtWidgets.QTextEdit(self)
self.findField.resize(250,50)
# The field into which to type the text to replace the
# queried text
self.replaceField = QtWidgets.QTextEdit(self)
self.replaceField.resize(250,50)
layout = QtWidgets.QGridLayout()
layout.addWidget(self.findField,1,0,1,4)
layout.addWidget(self.normalRadio,2,2)
layout.addWidget(regexRadio,2,3)
layout.addWidget(findButton,2,0,1,2)
layout.addWidget(self.replaceField,3,0,1,4)
layout.addWidget(replaceButton,4,0,1,2)
layout.addWidget(allButton,4,2,1,2)
self.setGeometry(300,300,360,250)
self.setWindowTitle("Find and Replace")
self.setLayout(layout)
# By default the normal mode is activated
self.normalRadio.setChecked(True)
def find(self):
# Grab the parent's text
text = self.parent.text.toPlainText()
# And the text to find
query = self.findField.toPlainText()
if self.normalRadio.isChecked():
# Use normal string search to find the query from the
# last starting position
self.lastStart = text.find(query,self.lastStart + 1)
# If the find() method didn't return -1 (not found)
if self.lastStart >= 0:
end = self.lastStart + len(query)
self.moveCursor(self.lastStart,end)
else:
# Make the next search start from the beginning again
self.lastStart = 0
self.parent.text.moveCursor(QtGui.QTextCursor.End)
else:
# Compile the pattern
pattern = re.compile(query)
# The actual search
match = pattern.search(text,self.lastStart + 1)
if match:
self.lastStart = match.start()
self.moveCursor(self.lastStart,match.end())
else:
self.lastStart = 0
# We set the cursor to the end if the search was unsuccessful
self.parent.text.moveCursor(QtGui.QTextCursor.End)
def replace(self):
# Grab the text cursor
cursor = self.parent.text.textCursor()
# Security
if cursor.hasSelection():
# We insert the new text, which will override the selected
# text
cursor.insertText(self.replaceField.toPlainText())
# And set the new cursor
self.parent.text.setTextCursor(cursor)
def replaceAll(self):
self.lastStart = 0
self.find()
# Replace and find until self.lastStart is 0 again
while self.lastStart:
self.replace()
self.find()
def moveCursor(self,start,end):
# We retrieve the QTextCursor object from the parent's QTextEdit
cursor = self.parent.text.textCursor()
# Then we set the position to the beginning of the last match
cursor.setPosition(start)
# Next we move the Cursor by over the match and pass the KeepAnchor parameter
# which will make the cursor select the the match's text
cursor.movePosition(QtGui.QTextCursor.Right,QtGui.QTextCursor.KeepAnchor,end - start)
# And finally we set this new cursor as the parent's
self.parent.text.setTextCursor(cursor)

View File

@@ -0,0 +1,102 @@
import sys
from qtpy import QtWidgets
#PYQT5 QSpinBox, QMessageBox, QDialog, QPushButton, QGridLayout, QLabel
from qtpy import QtGui, QtCore
from qtpy.QtCore import Qt
class Table(QtWidgets.QDialog):
def __init__(self,parent = None):
QtWidgets.QDialog.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
# Rows
rowsLabel = QtWidgets.QLabel("Rows: ",self)
self.rows = QtWidgets.QSpinBox(self)
# Columns
colsLabel = QtWidgets.QLabel("Columns",self)
self.cols = QtWidgets.QSpinBox(self)
# Cell spacing (distance between cells)
spaceLabel = QtWidgets.QLabel("Cell spacing",self)
self.space = QtWidgets.QSpinBox(self)
# Cell padding (distance between cell and inner text)
padLabel = QtWidgets.QLabel("Cell padding",self)
self.pad = QtWidgets.QSpinBox(self)
self.pad.setValue(10)
# Button
insertButton = QtWidgets.QPushButton("Insert",self)
insertButton.clicked.connect(self.insert)
# Layout
layout = QtWidgets.QGridLayout()
layout.addWidget(rowsLabel,0,0)
layout.addWidget(self.rows,0,1)
layout.addWidget(colsLabel,1,0)
layout.addWidget(self.cols,1,1)
layout.addWidget(padLabel,2,0)
layout.addWidget(self.pad,2,1)
layout.addWidget(spaceLabel,3,0)
layout.addWidget(self.space,3,1)
layout.addWidget(insertButton,4,0,1,2)
self.setWindowTitle("Insert Table")
self.setGeometry(300,300,200,100)
self.setLayout(layout)
def insert(self):
cursor = self.parent.text.textCursor()
# Get the configurations
rows = self.rows.value()
cols = self.cols.value()
if not rows or not cols:
popup = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning,
"Parameter error",
"Row and column numbers may not be zero!",
QtWidgets.QMessageBox.Ok,
self)
popup.show()
else:
padding = self.pad.value()
space = self.space.value()
# Set the padding and spacing
fmt = QtGui.QTextTableFormat()
fmt.setCellPadding(padding)
fmt.setCellSpacing(space)
# Insert the new table
cursor.insertTable(rows,cols,fmt)
self.close()

View File

@@ -0,0 +1,90 @@
from qtpy import QtWidgets
#PYQT5 QDialog, QGridLayout, QLabel, QWidget
from qtpy import QtGui, QtCore
from qtpy.QtCore import Qt
class WordCount(QtWidgets.QDialog):
def __init__(self,parent = None):
QtWidgets.QDialog.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
# Word count in selection
currentLabel = QtWidgets.QLabel("Current selection",self)
currentLabel.setStyleSheet("font-weight:bold; font-size: 15px;")
currentWordsLabel = QtWidgets.QLabel("Words: ", self)
currentSymbolsLabel = QtWidgets.QLabel("Symbols: ",self)
self.currentWords = QtWidgets.QLabel(self)
self.currentSymbols = QtWidgets.QLabel(self)
# Total word/symbol count
totalLabel = QtWidgets.QLabel("Total",self)
totalLabel.setStyleSheet("font-weight:bold; font-size: 15px;")
totalWordsLabel = QtWidgets.QLabel("Words: ", self)
totalSymbolsLabel = QtWidgets.QLabel("Symbols: ",self)
self.totalWords = QtWidgets.QLabel(self)
self.totalSymbols = QtWidgets.QLabel(self)
# Layout
layout = QtWidgets.QGridLayout(self)
layout.addWidget(currentLabel,0,0)
layout.addWidget(currentWordsLabel,1,0)
layout.addWidget(self.currentWords,1,1)
layout.addWidget(currentSymbolsLabel,2,0)
layout.addWidget(self.currentSymbols,2,1)
spacer = QtWidgets.QWidget()
spacer.setFixedSize(0,5)
layout.addWidget(spacer,3,0)
layout.addWidget(totalLabel,4,0)
layout.addWidget(totalWordsLabel,5,0)
layout.addWidget(self.totalWords,5,1)
layout.addWidget(totalSymbolsLabel,6,0)
layout.addWidget(self.totalSymbols,6,1)
self.setWindowTitle("Word count")
self.setGeometry(300,300,200,200)
self.setLayout(layout)
def getText(self):
# Get the text currently in selection
text = self.parent.text.textCursor().selectedText()
# Split the text to get the word count
words = str(len(text.split()))
# And just get the length of the text for the symbols
# count
symbols = str(len(text))
self.currentWords.setText(words)
self.currentSymbols.setText(symbols)
# For the total count, same thing as above but for the
# total text
text = self.parent.text.toPlainText()
words = str(len(text.split()))
symbols = str(len(text))
self.totalWords.setText(words)
self.totalSymbols.setText(symbols)

View File

@@ -0,0 +1,881 @@
#!/usr/bin/env python3
# https://www.binpress.com/building-text-editor-pyqt-1/
import sys
import os
from qtpy import QtWidgets
from qtpy import QtPrintSupport
from qtpy import QtGui, QtCore
from qtpy.QtCore import Qt
from .ext import *
from qtvcp.core import Path
PATH = Path()
ICONPATH = os.path.join(PATH.SHAREDIR, 'images/widgets/writer')
IMAGEPATH = os.path.join(PATH.SHAREDIR, 'images')
class Main(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
self.filename = None
self.image_filename = None
self.changesSaved = True
self.initUI()
self.default_path = (os.path.join(os.path.expanduser('~'), 'linuxcnc/nc_files/examples'))
def initToolbar(self):
self.newAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/blue-document.png")), "New", self)
self.newAction.setShortcut("Ctrl+N")
self.newAction.setStatusTip("Create a new document from scratch.")
self.newAction.triggered.connect(self.new)
self.openAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/blue-folder-open.png")),
"Open file", self)
self.openAction.setStatusTip("Open existing document")
self.openAction.setShortcut("Ctrl+O")
self.openAction.triggered.connect(self.open)
self.saveAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/disk-black.png")), "Save", self)
self.saveAction.setStatusTip("Save document")
self.saveAction.setShortcut("Ctrl+S")
self.saveAction.triggered.connect(self.save)
self.printAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/printer.png")), "Print document",
self)
self.printAction.setStatusTip("Print document")
self.printAction.setShortcut("Ctrl+P")
self.printAction.triggered.connect(self.printHandler)
self.previewAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/eye.png")), "Page view", self)
self.previewAction.setStatusTip("Preview page before printing")
self.previewAction.setShortcut("Ctrl+Shift+P")
self.previewAction.triggered.connect(self.preview)
self.findAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/magnifier-left.png")),
"Find and replace", self)
self.findAction.setStatusTip("Find and replace words in your document")
self.findAction.setShortcut("Ctrl+F")
self.findAction.triggered.connect(find.Find(self).show)
self.cutAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/scissors.png")),
"Cut to clipboard", self)
self.cutAction.setStatusTip("Delete and copy text to clipboard")
self.cutAction.setShortcut("Ctrl+X")
self.cutAction.triggered.connect(self.text.cut)
self.copyAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/document-copy.png")),
"Copy to clipboard", self)
self.copyAction.setStatusTip("Copy text to clipboard")
self.copyAction.setShortcut("Ctrl+C")
self.copyAction.triggered.connect(self.text.copy)
self.pasteAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/stamp.png")),
"Paste from clipboard", self)
self.pasteAction.setStatusTip("Paste text from clipboard")
self.pasteAction.setShortcut("Ctrl+V")
self.pasteAction.triggered.connect(self.text.paste)
self.undoAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/arrow-curve-180.png")),
"Undo last action", self)
self.undoAction.setStatusTip("Undo last action")
self.undoAction.setShortcut("Ctrl+Z")
self.undoAction.triggered.connect(self.text.undo)
self.redoAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/arrow-curve.png")),
"Redo last undone thing", self)
self.redoAction.setStatusTip("Redo last undone thing")
self.redoAction.setShortcut("Ctrl+Y")
self.redoAction.triggered.connect(self.text.redo)
dateTimeAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/calendar-blue.png")),
"Insert current date/time", self)
dateTimeAction.setStatusTip("Insert current date/time")
dateTimeAction.setShortcut("Ctrl+D")
dateTimeAction.triggered.connect(datetime.DateTime(self).show)
wordCountAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/counter.png")),
"See word/symbol count", self)
wordCountAction.setStatusTip("See word/symbol count")
wordCountAction.setShortcut("Ctrl+W")
wordCountAction.triggered.connect(self.wordCount)
tableAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/table.png")), "Insert table", self)
tableAction.setStatusTip("Insert table")
tableAction.setShortcut("Ctrl+T")
tableAction.triggered.connect(table.Table(self).show)
imageAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/image-import.png")), "Insert image",
self)
imageAction.setStatusTip("Insert image")
imageAction.setShortcut("Ctrl+Shift+I")
imageAction.triggered.connect(self.insertImage)
bulletAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/edit-list.png")),
"Insert bullet List", self)
bulletAction.setStatusTip("Insert bullet list")
bulletAction.setShortcut("Ctrl+Shift+B")
bulletAction.triggered.connect(self.bulletList)
numberedAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/edit-list-order.png")),
"Insert numbered List", self)
numberedAction.setStatusTip("Insert numbered list")
numberedAction.setShortcut("Ctrl+Shift+L")
numberedAction.triggered.connect(self.numberList)
self.toolbar = self.addToolBar("Options")
self.toolbar.addAction(self.newAction)
self.toolbar.addAction(self.openAction)
self.toolbar.addAction(self.saveAction)
self.toolbar.addSeparator()
self.toolbar.addAction(self.printAction)
self.toolbar.addAction(self.previewAction)
self.toolbar.addSeparator()
self.toolbar.addAction(self.cutAction)
self.toolbar.addAction(self.copyAction)
self.toolbar.addAction(self.pasteAction)
self.toolbar.addAction(self.undoAction)
self.toolbar.addAction(self.redoAction)
self.toolbar.addSeparator()
self.toolbar.addAction(self.findAction)
self.toolbar.addAction(dateTimeAction)
self.toolbar.addAction(wordCountAction)
self.toolbar.addAction(tableAction)
self.toolbar.addAction(imageAction)
self.toolbar.addSeparator()
self.toolbar.addAction(bulletAction)
self.toolbar.addAction(numberedAction)
self.addToolBarBreak()
def initFormatbar(self):
fontBox = QtWidgets.QFontComboBox(self)
fontBox.currentFontChanged.connect(lambda font: self.text.setCurrentFont(font))
fontSize = QtWidgets.QSpinBox(self)
# Will display " pt" after each value
fontSize.setSuffix(" pt")
fontSize.valueChanged.connect(lambda size: self.text.setFontPointSize(size))
fontSize.setValue(14)
fontColor = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/edit-color.png")), "Change font color",
self)
fontColor.triggered.connect(self.fontColorChanged)
boldAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/edit-bold.png")), "Bold", self)
boldAction.setCheckable(True)
boldAction.triggered.connect(self.bold)
italicAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/edit-italic.png")), "Italic", self)
italicAction.setCheckable(True)
italicAction.triggered.connect(self.italic)
underlAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/edit-underline.png")), "Underline",
self)
underlAction.setCheckable(True)
underlAction.triggered.connect(self.underline)
strikeAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/edit-strike.png")), "Strike-out",
self)
strikeAction.setCheckable(True)
strikeAction.triggered.connect(self.strike)
superAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/edit-superscript.png")),
"Superscript", self)
superAction.setCheckable(True)
superAction.triggered.connect(self.superScript)
subAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/edit-subscript.png")), "Subscript",
self)
subAction.setCheckable(True)
subAction.triggered.connect(self.subScript)
alignLeft = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/edit-alignment.png")), "Align left",
self)
alignLeft.setCheckable(True)
alignLeft.triggered.connect(self.alignLeft)
alignCenter = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/edit-alignment-center.png")),
"Align center", self)
alignCenter.setCheckable(True)
alignCenter.triggered.connect(self.alignCenter)
alignRight = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/edit-alignment-right.png")),
"Align right", self)
alignRight.setCheckable(True)
alignRight.triggered.connect(self.alignRight)
alignJustify = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/edit-alignment-justify.png")),
"Align justify", self)
alignJustify.setCheckable(True)
alignJustify.triggered.connect(self.alignJustify)
indentAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/edit-outdent.png")), "Indent Area",
self)
indentAction.setShortcut("Ctrl+Tab")
indentAction.triggered.connect(self.indent)
dedentAction = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/edit-outdent-rtl.png")),
"Dedent Area", self)
dedentAction.setShortcut("Shift+Tab")
dedentAction.triggered.connect(self.dedent)
backColor = QtWidgets.QAction(QtGui.QIcon(os.path.join(ICONPATH, "icons/color-swatch.png")),
"Change background color", self)
backColor.triggered.connect(self.highlight)
self.formatbar = self.addToolBar("Format")
self.formatbar.addWidget(fontBox)
self.formatbar.addWidget(fontSize)
self.formatbar.addSeparator()
self.formatbar.addAction(fontColor)
self.formatbar.addAction(backColor)
self.formatbar.addSeparator()
self.formatbar.addAction(boldAction)
self.formatbar.addAction(italicAction)
self.formatbar.addAction(underlAction)
self.formatbar.addAction(strikeAction)
self.formatbar.addAction(superAction)
self.formatbar.addAction(subAction)
self.formatbar.addSeparator()
self.formatbar.addAction(alignLeft)
self.formatbar.addAction(alignCenter)
self.formatbar.addAction(alignRight)
self.formatbar.addAction(alignJustify)
format_group = QtWidgets.QActionGroup(self)
format_group.setExclusive(True)
format_group.addAction(alignLeft)
format_group.addAction(alignCenter)
format_group.addAction(alignRight)
format_group.addAction(alignJustify)
self.formatbar.addSeparator()
self.formatbar.addAction(indentAction)
self.formatbar.addAction(dedentAction)
def initMenubar(self):
menubar = self.menuBar()
file = menubar.addMenu("File")
edit = menubar.addMenu("Edit")
view = menubar.addMenu("View")
# Add the most important actions to the menubar
file.addAction(self.newAction)
file.addAction(self.openAction)
file.addAction(self.saveAction)
file.addAction(self.printAction)
file.addAction(self.previewAction)
edit.addAction(self.undoAction)
edit.addAction(self.redoAction)
edit.addAction(self.cutAction)
edit.addAction(self.copyAction)
edit.addAction(self.pasteAction)
edit.addAction(self.findAction)
# Toggling actions for the various bars
toolbarAction = QtWidgets.QAction("Toggle Toolbar", self)
toolbarAction.triggered.connect(self.toggleToolbar)
formatbarAction = QtWidgets.QAction("Toggle Formatbar", self)
formatbarAction.triggered.connect(self.toggleFormatbar)
statusbarAction = QtWidgets.QAction("Toggle Statusbar", self)
statusbarAction.triggered.connect(self.toggleStatusbar)
view.addAction(toolbarAction)
view.addAction(formatbarAction)
view.addAction(statusbarAction)
def initUI(self):
self.text = QtWidgets.QTextEdit(self)
# Set the tab stop width to around 33 pixels which is
# more or less 8 spaces
self.text.setTabStopWidth(33)
self.initToolbar()
self.initFormatbar()
self.initMenubar()
self.setCentralWidget(self.text)
# Initialize a statusbar for the window
self.statusbar = self.statusBar()
# If the cursor position changes, call the function that displays
# the line and column number
self.text.cursorPositionChanged.connect(self.cursorPosition)
# We need our own context menu for tables
self.text.setContextMenuPolicy(Qt.CustomContextMenu)
self.text.customContextMenuRequested.connect(self.context)
self.text.textChanged.connect(self.changed)
self.setGeometry(100, 100, 1030, 800)
self.setWindowTitle("HTML Writer")
self.setWindowIcon(QtGui.QIcon(os.path.join(ICONPATH, "icons/pencil.png")))
def changed(self):
self.changesSaved = False
def closeEvent(self, event):
if self.changesSaved:
event.accept()
else:
popup = QtWidgets.QMessageBox(self)
popup.setIcon(QtWidgets.QMessageBox.Warning)
popup.setText("The document has been modified")
popup.setInformativeText("Do you want to save your changes?")
popup.setStandardButtons(QtWidgets.QMessageBox.Save |
QtWidgets.QMessageBox.Cancel |
QtWidgets.QMessageBox.Discard)
popup.setDefaultButton(QtWidgets.QMessageBox.Save)
answer = popup.exec()
if answer == QtWidgets.QMessageBox.Save:
self.save()
elif answer == QtWidgets.QMessageBox.Discard:
event.accept()
else:
event.ignore()
def context(self, pos):
# Grab the cursor
cursor = self.text.textCursor()
# Grab the current table, if there is one
table = cursor.currentTable()
# Above will return 0 if there is no current table, in which case
# we call the normal context menu. If there is a table, we create
# our own context menu specific to table interaction
if table:
menu = QtWidgets.QMenu(self)
appendRowAction = QtWidgets.QAction("Append row", self)
appendRowAction.triggered.connect(lambda: table.appendRows(1))
appendColAction = QtWidgets.QAction("Append column", self)
appendColAction.triggered.connect(lambda: table.appendColumns(1))
removeRowAction = QtWidgets.QAction("Remove row", self)
removeRowAction.triggered.connect(self.removeRow)
removeColAction = QtWidgets.QAction("Remove column", self)
removeColAction.triggered.connect(self.removeCol)
insertRowAction = QtWidgets.QAction("Insert row", self)
insertRowAction.triggered.connect(self.insertRow)
insertColAction = QtWidgets.QAction("Insert column", self)
insertColAction.triggered.connect(self.insertCol)
mergeAction = QtWidgets.QAction("Merge cells", self)
mergeAction.triggered.connect(lambda: table.mergeCells(cursor))
# Only allow merging if there is a selection
if not cursor.hasSelection():
mergeAction.setEnabled(False)
splitAction = QtWidgets.QAction("Split cells", self)
cell = table.cellAt(cursor)
# Only allow splitting if the current cell is larger
# than a normal cell
if cell.rowSpan() > 1 or cell.columnSpan() > 1:
splitAction.triggered.connect(lambda: table.splitCell(cell.row(), cell.column(), 1, 1))
else:
splitAction.setEnabled(False)
menu.addAction(appendRowAction)
menu.addAction(appendColAction)
menu.addSeparator()
menu.addAction(removeRowAction)
menu.addAction(removeColAction)
menu.addSeparator()
menu.addAction(insertRowAction)
menu.addAction(insertColAction)
menu.addSeparator()
menu.addAction(mergeAction)
menu.addAction(splitAction)
# Convert the widget coordinates into global coordinates
pos = self.mapToGlobal(pos)
# Add pixels for the tool and formatbars, which are not included
# in mapToGlobal(), but only if the two are currently visible and
# not toggled by the user
if self.toolbar.isVisible():
pos.setY(pos.y() + 45)
if self.formatbar.isVisible():
pos.setY(pos.y() + 45)
# Move the menu to the new position
menu.move(pos)
menu.show()
else:
event = QtGui.QContextMenuEvent(QtGui.QContextMenuEvent.Mouse, QtCore.QPoint())
self.text.contextMenuEvent(event)
def removeRow(self):
# Grab the cursor
cursor = self.text.textCursor()
# Grab the current table (we assume there is one, since
# this is checked before calling)
table = cursor.currentTable()
# Get the current cell
cell = table.cellAt(cursor)
# Delete the cell's row
table.removeRows(cell.row(), 1)
def removeCol(self):
# Grab the cursor
cursor = self.text.textCursor()
# Grab the current table (we assume there is one, since
# this is checked before calling)
table = cursor.currentTable()
# Get the current cell
cell = table.cellAt(cursor)
# Delete the cell's column
table.removeColumns(cell.column(), 1)
def insertRow(self):
# Grab the cursor
cursor = self.text.textCursor()
# Grab the current table (we assume there is one, since
# this is checked before calling)
table = cursor.currentTable()
# Get the current cell
cell = table.cellAt(cursor)
# Insert a new row at the cell's position
table.insertRows(cell.row(), 1)
def insertCol(self):
# Grab the cursor
cursor = self.text.textCursor()
# Grab the current table (we assume there is one, since
# this is checked before calling)
table = cursor.currentTable()
# Get the current cell
cell = table.cellAt(cursor)
# Insert a new row at the cell's position
table.insertColumns(cell.column(), 1)
def toggleToolbar(self):
state = self.toolbar.isVisible()
# Set the visibility to its inverse
self.toolbar.setVisible(not state)
def toggleFormatbar(self):
state = self.formatbar.isVisible()
# Set the visibility to its inverse
self.formatbar.setVisible(not state)
def toggleStatusbar(self):
state = self.statusbar.isVisible()
# Set the visibility to its inverse
self.statusbar.setVisible(not state)
def new(self):
spawn = Main()
spawn.show()
def open(self):
# Get filename and show only .writer files
# PYQT5 Returns a tuple in PyQt5, we only need the filename
if self.filename is None:
searchDir = self.default_path
else:
searchDir = self.filename
self.filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File', searchDir, "(*.html)")[0]
if self.filename:
with open(self.filename, "rt") as file:
self.text.setText(file.read())
def save(self):
if self.filename is None:
searchDir = self.default_path
else:
searchDir = self.filename
self.filename = QtWidgets.QFileDialog.getSaveFileName(self, 'Save File', searchDir)[0]
if self.filename:
# Append extension if not there yet
if not self.filename.endswith(".html"):
self.filename += ".html"
# We just store the contents of the text file along with the
# format in html, which Qt does in a very nice way for us
with open(self.filename, "wt") as file:
file.write(self.text.toHtml())
self.changesSaved = True
def preview(self):
# Open preview dialog
preview = QtPrintSupport.QPrintPreviewDialog()
# If a print is requested, open print dialog
preview.paintRequested.connect(lambda p: self.text.print_(p))
preview.exec()
def printHandler(self):
# Open printing dialog
dialog = QtPrintSupport.QPrintDialog()
if dialog.exec() == QtWidgets.QDialog.Accepted:
self.text.document().print_(dialog.printer())
def cursorPosition(self):
cursor = self.text.textCursor()
# Mortals like 1-indexed things
line = cursor.blockNumber() + 1
col = cursor.columnNumber()
self.statusbar.showMessage("Line: {} | Column: {}".format(line, col))
def wordCount(self):
wc = wordcount.WordCount(self)
wc.getText()
wc.show()
def insertImage(self):
if self.image_filename is None:
imagePath = IMAGEPATH
else:
imagePath = self.image_filename
# Get image file name
filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Insert image', imagePath,
"Images (*.png *.xpm *.jpg *.bmp *.gif)")[0]
if filename:
self.image_filename = filename
# Create image object
image = QtGui.QImage(filename)
# Error if unloadable
if image.isNull():
popup = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Critical,
"Image load error",
"Could not load image file!",
QtWidgets.QMessageBox.Ok,
self)
popup.show()
else:
cursor = self.text.textCursor()
cursor.insertImage(image, filename)
def fontColorChanged(self):
# Get a color from the text dialog
color = QtWidgets.QColorDialog.getColor()
# Set it as the new text color
self.text.setTextColor(color)
def highlight(self):
color = QtWidgets.QColorDialog.getColor()
self.text.setTextBackgroundColor(color)
def bold(self):
if self.text.fontWeight() == QtGui.QFont.Bold:
self.text.setFontWeight(QtGui.QFont.Normal)
else:
self.text.setFontWeight(QtGui.QFont.Bold)
def italic(self):
state = self.text.fontItalic()
self.text.setFontItalic(not state)
def underline(self):
state = self.text.fontUnderline()
self.text.setFontUnderline(not state)
def strike(self):
# Grab the text's format
fmt = self.text.currentCharFormat()
# Set the fontStrikeOut property to its opposite
fmt.setFontStrikeOut(not fmt.fontStrikeOut())
# And set the next char format
self.text.setCurrentCharFormat(fmt)
def superScript(self):
# Grab the current format
fmt = self.text.currentCharFormat()
# And get the vertical alignment property
align = fmt.verticalAlignment()
# Toggle the state
if align == QtGui.QTextCharFormat.AlignNormal:
fmt.setVerticalAlignment(QtGui.QTextCharFormat.AlignSuperScript)
else:
fmt.setVerticalAlignment(QtGui.QTextCharFormat.AlignNormal)
# Set the new format
self.text.setCurrentCharFormat(fmt)
def subScript(self):
# Grab the current format
fmt = self.text.currentCharFormat()
# And get the vertical alignment property
align = fmt.verticalAlignment()
# Toggle the state
if align == QtGui.QTextCharFormat.AlignNormal:
fmt.setVerticalAlignment(QtGui.QTextCharFormat.AlignSubScript)
else:
fmt.setVerticalAlignment(QtGui.QTextCharFormat.AlignNormal)
# Set the new format
self.text.setCurrentCharFormat(fmt)
def alignLeft(self):
self.text.setAlignment(Qt.AlignLeft)
def alignRight(self):
self.text.setAlignment(Qt.AlignRight)
def alignCenter(self):
self.text.setAlignment(Qt.AlignCenter)
def alignJustify(self):
self.text.setAlignment(Qt.AlignJustify)
def indent(self):
# Grab the cursor
cursor = self.text.textCursor()
if cursor.hasSelection():
# Store the current line/block number
temp = cursor.blockNumber()
# Move to the selection's end
cursor.setPosition(cursor.anchor())
# Calculate range of selection
diff = cursor.blockNumber() - temp
direction = QtGui.QTextCursor.Up if diff > 0 else QtGui.QTextCursor.Down
# Iterate over lines (diff absolute value)
for n in range(abs(diff) + 1):
# Move to start of each line
cursor.movePosition(QtGui.QTextCursor.StartOfLine)
# Insert tabbing
cursor.insertText("\t")
# And move back up
cursor.movePosition(direction)
# If there is no selection, just insert a tab
else:
cursor.insertText("\t")
def handleDedent(self, cursor):
cursor.movePosition(QtGui.QTextCursor.StartOfLine)
# Grab the current line
line = cursor.block().text()
# If the line starts with a tab character, delete it
if line.startswith("\t"):
# Delete next character
cursor.deleteChar()
# Otherwise, delete all spaces until a non-space character is met
else:
for char in line[:8]:
if char != " ":
break
cursor.deleteChar()
def dedent(self):
cursor = self.text.textCursor()
if cursor.hasSelection():
# Store the current line/block number
temp = cursor.blockNumber()
# Move to the selection's last line
cursor.setPosition(cursor.anchor())
# Calculate range of selection
diff = cursor.blockNumber() - temp
direction = QtGui.QTextCursor.Up if diff > 0 else QtGui.QTextCursor.Down
# Iterate over lines
for n in range(abs(diff) + 1):
self.handleDedent(cursor)
# Move up
cursor.movePosition(direction)
else:
self.handleDedent(cursor)
def bulletList(self):
cursor = self.text.textCursor()
# Insert bulleted list
cursor.insertList(QtGui.QTextListFormat.ListDisc)
def numberList(self):
cursor = self.text.textCursor()
# Insert list with numbers
cursor.insertList(QtGui.QTextListFormat.ListDecimal)
def main():
app = QtWidgets.QApplication(sys.argv)
main = Main()
main.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,130 @@
#!/usr/bin/env python3
# Qtvcp
#
# Copyright (c) 2018 Chris Morley <chrisinnanaimo@hotmail.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.
#
# This was repurposed from gladevcp
#
###############################################################################
# embed qt instance 'window' into X11 window 'parent'
def reparent_qt_to_x11(window, parent):
""" Forced reparent. When reparenting pyqt5 applications into Tk
some extra protocol calls are needed.
"""
try:
from Xlib import display
from Xlib.xobject import drawable
except:
print('Problem importing xlib - Is python3-xlib installed?')
if not parent:
return window
xid = int(window.winId())
d = display.Display()
w = drawable.Window(d.display, xid, 0)
# Honor XEmbed spec
atom = d.get_atom('_XEMBED_INFO')
w.change_property(atom, atom, 32, [0, 1])
w.reparent(parent, 0, 0)
w.map()
d.sync()
return window
# forward events to an X11 window id
try:
from Xlib.protocol import event
from Xlib import display, X
from Xlib.xobject import drawable
except:
print('Problem importing xlib - Is python3-xlib installed?')
class XEmbedForwarding():
# nothimg to ignore at this time (use qt.key definitions)
ignore = []
def __init__(self, window, forward):
if not forward:
return
try:
forward = int(forward, 0)
except:
return
d = display.Display()
self.fw = drawable.Window(d.display, forward, 0)
self.window = window
window.keyPressTrap = self.catch_keypress
window.keyReleaseTrap = self.catch_keyrelease
def catch_keypress(self, e):
#print(e.key())
self.forward(e, e.nativeScanCode(),True)
def catch_keyrelease(self, e):
self.forward(e, e.nativeScanCode(),False)
def build_event(self, e, keycode, g, type=None):
if type:
klass = event.KeyPress
elif type == False:
klass = event.KeyRelease
else:
return
time_lie = 264209133 # can't get XWIN event time from qtvcp events
kw = dict(window=self.fw, # window id to forward to
detail=keycode, # keysys code
state=0, # shift/cntrl/ etc modifier state anded together
child=X.NONE, # no child window
root=g._data['root'],
root_x=g._data['x'],
root_y=g._data['y'],
event_x=0, event_y=0,
same_screen=1) # not from our screen
return klass(time=time_lie, **kw)
def forward(self, e, keycode,type):
if e in self.ignore:
return
g = self.fw.get_geometry()
fe = self.build_event(e, keycode, g,type)
if not fe: return
self.fw.send_event(fe)
class X11ClientMessage():
def __init__(self, receiver_id):
self.d = display.Display()
self.fw = drawable.Window(self.d.display, receiver_id, 0)
self.receiver_id = receiver_id
def send_client_message(self, message="Visible\0\0\0\0\0\0\0\0\0\0\0\0\0", mtype='Gladevcp'):
print('X11 message sent')
mess_type = self.d.intern_atom(mtype)
# TODO add check of message for 20 characters
cm_event = event.ClientMessage(
window=self.receiver_id,
client_type=mess_type,
data=(8, message))
self.d.send_event(self.receiver_id, cm_event)

26
lib/python/qtvcp/logger.py Executable file
View File

@@ -0,0 +1,26 @@
#!/usr/bin/env python3
# QTVcp Logging Module
# Provides a consistent and easy to use logging facility. Log messages printed
# to the terminal will be colorized for easy identification of log level.
#
# Copyright (c) 2017 Kurt Jacobson
#
# 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.
# this has been moved to python/lib/common
# in the future we might be able to remove this file
# but it could break customizations out in the user world
# might be better just just leave this 'springboard' here
from common.logger import *

View File

@@ -0,0 +1,3 @@
# Empty package file for widgets provided with Qt Quarterly 26.
# Widgets are provided in a package to avoid problems if modules with
# generic names are installed in Python's site-packages directory.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,53 @@
#!/usr/bin/env python3
from qtpy import QtGui
from qtpy.QtDesigner import QPyDesignerCustomWidgetPlugin
from qtvcp.widgets.bar import HalBar
from qtvcp.widgets.qtvcp_icons import Icon
ICON = Icon()
####################################
# DRO
####################################
class HalBarPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(HalBarPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, formEditor):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return HalBar(parent)
def name(self):
return "HalBar"
def group(self):
return "Linuxcnc - HAL"
def icon(self):
return QtGui.QIcon(QtGui.QPixmap(ICON.get_path('halbar_label')))
def toolTip(self):
return "HAL Bar Widget"
def whatsThis(self):
return ""
def isContainer(self):
return False
def domXml(self):
return '<widget class="HalBar" name="hal_bar" />\n'
def includeFile(self):
return "qtvcp.widgets.bar"

View File

@@ -0,0 +1,52 @@
#!/usr/bin/env python3
from qtpy import QtGui
from qtpy.QtDesigner import QPyDesignerCustomWidgetPlugin
from qtvcp.widgets.basic_probe import BasicProbe
from qtvcp.widgets.qtvcp_icons import Icon
ICON = Icon()
####################################
# BasicProbe
####################################
class BasicProbePlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(BasicProbePlugin, self).__init__(parent)
self.initialized = False
def initialize(self, formEditor):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return BasicProbe(parent)
def name(self):
return "BasicProbe"
def group(self):
return "Linuxcnc - Widgets"
def icon(self):
return QtGui.QIcon(QtGui.QPixmap(ICON.get_path('basicprobe')))
def toolTip(self):
return "Probe Screen Widget"
def whatsThis(self):
return ""
def isContainer(self):
return False
def domXml(self):
return '<widget class="BasicProbe" name="basicprobe" />\n'
def includeFile(self):
return "qtvcp.widgets.basic_probe"

View File

@@ -0,0 +1,55 @@
#!/usr/bin/env python3
from qtpy.QtGui import QIcon, QPixmap
from qtpy.QtDesigner import QPyDesignerCustomWidgetPlugin
from qtvcp.widgets.camview_widget import CamView
from qtvcp.widgets.qtvcp_icons import Icon
ICON = Icon()
class CamViewPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(CamViewPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, core):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return CamView(parent)
def name(self):
return "CamView"
def group(self):
return "Linuxcnc - HAL"
def icon(self):
return QIcon(QPixmap(ICON.get_path('camview')))
def toolTip(self):
return ""
def whatsThis(self):
return ""
def isContainer(self):
return False
# Returns an XML description of a custom widget instance that describes
# default values for its properties. Each custom widget created by this
# plugin will be configured using this description.
def domXml(self):
return '<widget class="CamView" name="camview" />\n'
def includeFile(self):
return "qtvcp.widgets.camview_widget"

View File

@@ -0,0 +1,97 @@
#!/usr/bin/env python3
from qtpy import QtGui
from qtpy.QtDesigner import QPyDesignerCustomWidgetPlugin
from qtvcp.widgets.container_widgets import StateEnableGridLayout
from qtvcp.widgets.container_widgets import JointEnableWidget
from qtvcp.widgets.qtvcp_icons import Icon
ICON = Icon()
####################################
# Linuxcnc State Enable GridLayout
####################################
class StateEnableGridLayoutPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(StateEnableGridLayoutPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, formEditor):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return StateEnableGridLayout(parent)
def name(self):
return "StateEnableGridLayout"
def group(self):
return "Linuxcnc - Controller"
def icon(self):
return QtGui.QIcon(QtGui.QPixmap(ICON.get_path('state_enable_gridlayout')))
def toolTip(self):
return "Linuxcnc State enable/disable GridLayout widget"
def whatsThis(self):
return ""
def isContainer(self):
return True
def domXml(self):
return '<widget class="StateEnableGridLayout" name="state_enable_gridLayout" />\n'
def includeFile(self):
return "qtvcp.widgets.container_widgets"
####################################
# Linuxcnc State Enable GridLayout
####################################
class JointEnableWidgetPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(JointEnableWidgetPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, formEditor):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return JointEnableWidget(parent)
def name(self):
return "JointEnableWidget"
def group(self):
return "Linuxcnc - Controller"
def icon(self):
return QtGui.QIcon(QtGui.QPixmap(ICON.get_path('jointenablewidget')))
def toolTip(self):
return "Linuxcnc Joint Availability enable/disable widget"
def whatsThis(self):
return ""
def isContainer(self):
return True
def domXml(self):
return '<widget class="JointEnableWidget" name="jointenablewidget" />\n'
def includeFile(self):
return "qtvcp.widgets.container_widgets"

View File

@@ -0,0 +1,52 @@
#!/usr/bin/env python3
from qtpy import QtGui
from qtpy.QtDesigner import QPyDesignerCustomWidgetPlugin
from qtvcp.widgets.detach_tabs import DetachTabWidget
from qtvcp.widgets.qtvcp_icons import Icon
ICON = Icon()
####################################
# Linuxcnc State Enable GridLayout
####################################
class DetachTabWidgetPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(DetachTabWidgetPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, formEditor):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return DetachTabWidget(parent)
def name(self):
return "DetachTabWidget"
def group(self):
return "Linuxcnc - HAL"
def icon(self):
return QtGui.QIcon(QtGui.QPixmap(ICON.get_path('detachtabwidget')))
def toolTip(self):
return "Tans can be detached from main widget"
def whatsThis(self):
return ""
def isContainer(self):
return True
def domXml(self):
return '<widget class="DetachTabWidget" name="dtabwidget" />\n'
def includeFile(self):
return "qtvcp.widgets.detach_tabs"

View File

@@ -0,0 +1,499 @@
#!/usr/bin/env python3
from qtpy.QtGui import QIcon, QPixmap
from qtpy.QtDesigner import QPyDesignerCustomWidgetPlugin
from qtvcp.widgets.dialog_widget import *
from qtvcp.widgets.qtvcp_icons import Icon
ICON = Icon()
class DialogPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(DialogPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, core):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return LcncDialog(parent)
def name(self):
return "LcncDialog"
def group(self):
return "Linuxcnc - Dialogs"
def icon(self):
return QIcon(QPixmap(ICON.get_path('lcncdialog')))
def toolTip(self):
return "Basic Message Dialog"
def whatsThis(self):
return ""
def isContainer(self):
return False
# Returns an XML description of a custom widget instance that describes
# default values for its properties. Each custom widget created by this
# plugin will be configured using this description.
def domXml(self):
return '<widget class="LcncDialog" name="lcncdialog" />\n'
def includeFile(self):
return "qtvcp.widgets.dialog_widget"
###############################################################################
# manual Tool Change Dialog
###############################################################################
class ToolDialogPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(ToolDialogPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, core):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return ToolDialog(parent)
def name(self):
return "ToolDialog"
def group(self):
return "Linuxcnc - Dialogs"
def icon(self):
return QIcon(QPixmap(ICON.get_path('tooldialog')))
def toolTip(self):
return "Manual Tool Change Prompt Widgets"
def whatsThis(self):
return ""
def isContainer(self):
return False
# Returns an XML description of a custom widget instance that describes
# default values for its properties. Each custom widget created by this
# plugin will be configured using this description.
def domXml(self):
return '<widget class="ToolDialog" name="tooldialog" />\n'
def includeFile(self):
return "qtvcp.widgets.dialog_widget"
###############################################################################
# File Dialog
###############################################################################
class FileDialogPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(FileDialogPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, core):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return FileDialog(parent)
def name(self):
return "FileDialog"
def group(self):
return "Linuxcnc - Dialogs"
def icon(self):
return QIcon(QPixmap(ICON.get_path('iledialog')))
def toolTip(self):
return "Gcode File Selection Dialog"
def whatsThis(self):
return ""
def isContainer(self):
return False
# Returns an XML description of a custom widget instance that describes
# default values for its properties. Each custom widget created by this
# plugin will be configured using this description.
def domXml(self):
return '<widget class="FileDialog" name="filedialog" />\n'
def includeFile(self):
return "qtvcp.widgets.dialog_widget"
###############################################################################
# Cam Dialog
###############################################################################
class CamViewDialogPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(CamViewDialogPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, core):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return CamViewDialog(parent)
def name(self):
return "CamViewDialog"
def group(self):
return "Linuxcnc - Dialogs"
def icon(self):
return QIcon(QPixmap(ICON.get_path('camviewdialog')))
def toolTip(self):
return "Web Cam View alignment Dialog"
def whatsThis(self):
return ""
def isContainer(self):
return False
# Returns an XML description of a custom widget instance that describes
# default values for its properties. Each custom widget created by this
# plugin will be configured using this description.
def domXml(self):
return '<widget class="CamViewDialog" name="camviewdialog" />\n'
def includeFile(self):
return "qtvcp.widgets.dialog_widget"
###############################################################################
# MacroTab Dialog
###############################################################################
class MacroTabDialogPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(MacroTabDialogPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, core):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return MacroTabDialog(parent)
def name(self):
return "MacroTabDialog"
def group(self):
return "Linuxcnc - Dialogs"
def icon(self):
return QIcon(QPixmap(ICON.get_path('macrotabdialog')))
def toolTip(self):
return "Macro program Selection Dialog"
def whatsThis(self):
return "Uses it to select short convenience subroutines"
def isContainer(self):
return False
# Returns an XML description of a custom widget instance that describes
# default values for its properties. Each custom widget created by this
# plugin will be configured using this description.
def domXml(self):
return '<widget class="MacroTabDialog" name="_macrotabdialog" />\n'
def includeFile(self):
return "qtvcp.widgets.dialog_widget"
###############################################################################
# OriginOffset Dialog
###############################################################################
class OriginOffsetDialogPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(OriginOffsetDialogPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, core):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return OriginOffsetDialog(parent)
def name(self):
return "OriginOffsetDialog"
def group(self):
return "Linuxcnc - Dialogs"
def icon(self):
return QIcon(QPixmap(ICON.get_path('originoffsetdialog')))
def toolTip(self):
return "Origin Offset Editing Dialog"
def whatsThis(self):
return ""
def isContainer(self):
return False
# Returns an XML description of a custom widget instance that describes
# default values for its properties. Each custom widget created by this
# plugin will be configured using this description.
def domXml(self):
return '<widget class="OriginOffsetDialog" name="originoffsetdialog" />\n'
def includeFile(self):
return "qtvcp.widgets.dialog_widget"
###############################################################################
# ToolChooser Dialog
###############################################################################
class ToolChooserDialogPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(ToolChooserDialogPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, core):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return ToolChooserDialog(parent)
def name(self):
return "ToolChooserDialog"
def group(self):
return "Linuxcnc - Dialogs"
def icon(self):
return QIcon(QPixmap(ICON.get_path('Toolchooserdialog')))
def toolTip(self):
return "Tool Chooser Dialog"
def whatsThis(self):
return ""
def isContainer(self):
return False
def domXml(self):
return '<widget class="ToolChooserDialog" name="toolchooserdialog" />\n'
def includeFile(self):
return "qtvcp.widgets.dialog_widget"
###############################################################################
# ToolOffset Dialog
###############################################################################
class ToolOffsetDialogPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(ToolOffsetDialogPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, core):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return ToolOffsetDialog(parent)
def name(self):
return "ToolOffsetDialog"
def group(self):
return "Linuxcnc - Dialogs"
def icon(self):
return QIcon(QPixmap(ICON.get_path('Tooloffsetdialog')))
def toolTip(self):
return "Tool Offset Editing Dialog"
def whatsThis(self):
return ""
def isContainer(self):
return False
# Returns an XML description of a custom widget instance that describes
# default values for its properties. Each custom widget created by this
# plugin will be configured using this description.
def domXml(self):
return '<widget class="ToolOffsetDialog" name="tooloffsetdialog" />\n'
def includeFile(self):
return "qtvcp.widgets.dialog_widget"
###############################################################################
# VersaProbe Dialog
###############################################################################
class VersaProbeDialogPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(VersaProbeDialogPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, core):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return VersaProbeDialog(parent)
def name(self):
return "VersaProbeDialog"
def group(self):
return "Linuxcnc - Dialogs"
def icon(self):
return QIcon(QPixmap(ICON.get_path('versaprobedialog')))
def toolTip(self):
return "Probe Dialog Widget"
def whatsThis(self):
return ""
def isContainer(self):
return False
# Returns an XML description of a custom widget instance that describes
# default values for its properties. Each custom widget created by this
# plugin will be configured using this description.
def domXml(self):
return '<widget class="VersaProbeDialog" name="versaprobedialog" />\n'
def includeFile(self):
return "qtvcp.widgets.dialog_widget"
###############################################################################
# Entry Dialog
###############################################################################
class EntryDialogPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(EntryDialogPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, core):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return EntryDialog(parent)
def name(self):
return "EntryDialog"
def group(self):
return "Linuxcnc - Dialogs"
def icon(self):
return QIcon(QPixmap(ICON.get_path('entrydialog')))
def toolTip(self):
return "Basic Entry Dialog"
def whatsThis(self):
return ""
def isContainer(self):
return False
# Returns an XML description of a custom widget instance that describes
# default values for its properties. Each custom widget created by this
# plugin will be configured using this description.
def domXml(self):
return '<widget class="EntryDialog" name="entrydialog" />\n'
def includeFile(self):
return "qtvcp.widgets.dialog_widget"

View File

@@ -0,0 +1,52 @@
#!/usr/bin/env python3
from qtpy import QtGui
from qtpy.QtDesigner import QPyDesignerCustomWidgetPlugin
from qtvcp.widgets.gcode_graphics import GCodeGraphics
from qtvcp.widgets.qtvcp_icons import Icon
ICON = Icon()
####################################
# GCodeGraphics
####################################
class GCodeGraphicsPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(GCodeGraphicsPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, formEditor):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return GCodeGraphics(parent)
def name(self):
return "GCodeGraphics"
def group(self):
return "Linuxcnc - Controller"
def icon(self):
return QtGui.QIcon(QtGui.QPixmap(ICON.get_path('gcodegraphics')))
def toolTip(self):
return "Graphics5 widget"
def whatsThis(self):
return ""
def isContainer(self):
return True
def domXml(self):
return '<widget class="GCodeGraphics" name="gcodegraphics" />\n'
def includeFile(self):
return "qtvcp.widgets.gcode_graphics"

View File

@@ -0,0 +1,52 @@
#!/usr/bin/env python3
from qtpy.QtGui import QIcon, QPixmap
from qtpy.QtDesigner import QPyDesignerCustomWidgetPlugin
from qtvcp.widgets.hal_label import HALLabel
from qtvcp.widgets.qtvcp_icons import Icon
ICON = Icon()
####################################
# Label Display
####################################
class HALLabelPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(HALLabelPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, formEditor):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return HALLabel(parent)
def name(self):
return "HALLabel"
def group(self):
return "Linuxcnc - HAL"
def icon(self):
return QIcon(QPixmap(ICON.get_path('hallabel')))
def toolTip(self):
return "HAL Pin Display widget"
def whatsThis(self):
return ""
def isContainer(self):
return False
def domXml(self):
return '<widget class="HALLabel" name="hallabel" />\n'
def includeFile(self):
return "qtvcp.widgets.hal_label"

View File

@@ -0,0 +1,55 @@
#!/usr/bin/env python3
from qtpy.QtGui import QIcon, QPixmap
from qtpy.QtDesigner import QPyDesignerCustomWidgetPlugin
from qtvcp.widgets.jog_increments import JogIncrements
from qtvcp.widgets.qtvcp_icons import Icon
ICON = Icon()
class JogIncrementsPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(JogIncrementsPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, core):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return JogIncrements(parent)
def name(self):
return "JogIncrements"
def group(self):
return "Linuxcnc - HAL"
def icon(self):
return QIcon(QPixmap(ICON.get_path('jogincrements')))
def toolTip(self):
return ""
def whatsThis(self):
return ""
def isContainer(self):
return False
# Returns an XML description of a custom widget instance that describes
# default values for its properties. Each custom widget created by this
# plugin will be configured using this description.
def domXml(self):
return '<widget class="JogIncrements" name="jogincrements" />\n'
def includeFile(self):
return "qtvcp.widgets.jog_increments"

View File

@@ -0,0 +1,94 @@
#!/usr/bin/env python3
from qtpy.QtGui import QIcon, QPixmap
from qtpy.QtDesigner import QPyDesignerCustomWidgetPlugin
from qtvcp.widgets.joypad import JoyPad, HALPad
from qtvcp.widgets.qtvcp_icons import Icon
ICON = Icon()
####################################
# HAL Joypad widget
####################################
class JoyPadPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(JoyPadPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, formEditor):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return JoyPad(parent)
def name(self):
return "JoyPad"
def group(self):
return "Linuxcnc - Widgets"
def icon(self):
return QIcon(QPixmap(ICON.get_path('JoyPad')))
def toolTip(self):
return "JoyPad Selection Widget"
def whatsThis(self):
return ""
def isContainer(self):
return False
def domXml(self):
return '<widget class="JoyPad" name="joypad" />\n'
def includeFile(self):
return "qtvcp.widgets.joypad"
####################################
# HAL Joypad widget
####################################
class HALPadPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(HALPadPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, formEditor):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return HALPad(parent)
def name(self):
return "HALPad"
def group(self):
return "Linuxcnc - HAL"
def icon(self):
return QIcon(QPixmap(ICON.get_path('HALPad')))
def toolTip(self):
return "HAL JoyPad Selection Widget"
def whatsThis(self):
return ""
def isContainer(self):
return False
def domXml(self):
return '<widget class="HALPad" name="halpad" />\n'
def includeFile(self):
return "qtvcp.widgets.joypad"

View File

@@ -0,0 +1,55 @@
#!/usr/bin/env python3
from qtpy.QtGui import QIcon, QPixmap
from qtpy.QtDesigner import QPyDesignerCustomWidgetPlugin
from qtvcp.widgets.led_widget import LED
from qtvcp.widgets.qtvcp_icons import Icon
ICON = Icon()
class LEDPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(LEDPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, core):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return LED(parent)
def name(self):
return "LED"
def group(self):
return "Linuxcnc - HAL"
def icon(self):
return QIcon(QPixmap(ICON.get_path('led')))
def toolTip(self):
return ""
def whatsThis(self):
return ""
def isContainer(self):
return False
# Returns an XML description of a custom widget instance that describes
# default values for its properties. Each custom widget created by this
# plugin will be configured using this description.
def domXml(self):
return '<widget class="LED" name="led" />\n'
def includeFile(self):
return "qtvcp.widgets.led_widget"

View File

@@ -0,0 +1,52 @@
#!/usr/bin/env python3
from qtpy.QtGui import QIcon, QPixmap
from qtpy.QtDesigner import QPyDesignerCustomWidgetPlugin
from qtvcp.widgets.nurbs_editor import NurbsEditor
from qtvcp.widgets.qtvcp_icons import Icon
ICON = Icon()
####################################
# HAL NurbsEditor widget
####################################
class NurbsEditorPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(NurbsEditorPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, formEditor):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return NurbsEditor(parent)
def name(self):
return "NurbsEditor"
def group(self):
return "Linuxcnc - Widgets"
def icon(self):
return QIcon(QPixmap(ICON.get_path('NurbsEditor')))
def toolTip(self):
return "Nurbs Gcode Editor Widget"
def whatsThis(self):
return ""
def isContainer(self):
return False
def domXml(self):
return '<widget class="NurbsEditor" name="nurbseditor" />\n'
def includeFile(self):
return "qtvcp.widgets.nurbseditor"

View File

@@ -0,0 +1,55 @@
#!/usr/bin/env python3
from qtpy.QtGui import QIcon, QPixmap
from qtpy.QtDesigner import QPyDesignerCustomWidgetPlugin
from qtvcp.widgets.overlay_widget import FocusOverlay
from qtvcp.widgets.qtvcp_icons import Icon
ICON = Icon()
class FocusOverlayPlugin(QPyDesignerCustomWidgetPlugin):
def __init__(self, parent=None):
super(FocusOverlayPlugin, self).__init__(parent)
self.initialized = False
def initialize(self, core):
if self.initialized:
return
self.initialized = True
def isInitialized(self):
return self.initialized
def createWidget(self, parent):
return FocusOverlay(parent)
def name(self):
return "FocusOverlay"
def group(self):
return "Linuxcnc - HAL"
def icon(self):
return QIcon(QPixmap(ICON.get_path('focusoverlay')))
def toolTip(self):
return ""
def whatsThis(self):
return ""
def isContainer(self):
return True
# Returns an XML description of a custom widget instance that describes
# default values for its properties. Each custom widget created by this
# plugin will be configured using this description.
def domXml(self):
return '<widget class="FocusOverlay" name="focusoverlay" />\n'
def includeFile(self):
return "qtvcp.widgets.overlay_widget"

Some files were not shown because too many files have changed in this diff Show More