-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathCommandsGUI.py
2064 lines (1486 loc) · 79.2 KB
/
CommandsGUI.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This software was designed by Alexander Thiel
Github handle: https://github.com/apockill
Email: [email protected]
The software was designed originaly for use with a robot arm, particularly uArm (Made by uFactory, ufactory.cc)
It is completely open source, so feel free to take it and use it as a base for your own projects.
If you make any cool additions, feel free to share!
License:
This file is part of uArmCreatorStudio.
uArmCreatorStudio is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
uArmCreatorStudio 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 uArmCreatorStudio. If not, see <http://www.gnu.org/licenses/>.
"""
import ast # To check if a statement is python parsible, for evals
import re # For variable santization
import Paths
import webbrowser # For opening the user manual PDF
from os.path import basename
from PyQt5 import QtGui, QtCore, QtWidgets
from CameraGUI import CameraSelector
from CommonGUI import ScriptWidget
from Logic.Global import printf, ensurePathExists
__author__ = "Alexander Thiel"
# This should only be used once, in CommandList.addCommand
class CommandWidget(QtWidgets.QWidget):
def __init__(self, parent, onDeleteFunction):
super(CommandWidget, self).__init__(parent)
# Set up Globals
self.indent = 0
self.margins = None # Is set after initUI creates it's first layout
# Set up UI Globals
self.title = QtWidgets.QLabel()
self.description = QtWidgets.QLabel()
self.icon = QtWidgets.QLabel()
self.deleteBtn = QtWidgets.QPushButton()
self.initUI()
self.margins = self.layout().getContentsMargins() # Has to be after initUI()
self.setIndent(0)
# Connect the delete button with a function in the CommandList widget that will delete selected commands
self.deleteBtn.clicked.connect(onDeleteFunction)
def initUI(self):
# Create the delete button
self.deleteBtn.setFlat(True)
self.deleteBtn.setIcon(QtGui.QIcon(Paths.delete))
self.deleteBtn.setVisible(False)
bold = QtGui.QFont()
bold.setBold(True)
self.title.setFont(bold)
midLayout = QtWidgets.QVBoxLayout()
midLayout.setSpacing(1)
midLayout.addWidget(self.title)
midLayout.addWidget(self.description)
mainHLayout = QtWidgets.QHBoxLayout()
mainHLayout.addWidget(self.icon)
mainHLayout.addLayout(midLayout, QtCore.Qt.AlignLeft)
mainHLayout.addWidget(self.deleteBtn)
self.setLayout(mainHLayout)
def setFocused(self, isFocused):
# Determines whether or not the delete button is visible. Should only be visible when widget is clicked
if isFocused:
self.deleteBtn.setVisible(True)
else:
self.deleteBtn.setVisible(False)
def setIndent(self, indent):
if self.indent == indent: return # If no indent change has been detected, ignore.
self.indent = indent
if indent >= 0:
# Indent the margin on the left, to push the block of code and simulate an 'indent'
self.layout().setContentsMargins(self.margins[0] + 25 * indent,
self.margins[1],
self.margins[2],
self.margins[3])
else:
# Reset the margins to the default setting
self.layout().setContentsMargins(self.margins[0],
self.margins[1],
self.margins[2],
self.margins[3])
# The following are accessed only by Command.dressWidget()
def setTitle(self, text):
self.title.setText(text)
def setDescription(self, text):
self.description.setText(text)
def setIcon(self, icon):
self.icon.setPixmap(QtGui.QPixmap(icon))
def setTip(self, text):
self.setToolTip(text)
class CommandMenuWidget(QtWidgets.QTabWidget):
def __init__(self, parent):
super(CommandMenuWidget, self).__init__(parent)
self.initUI()
def initUI(self):
self.setStyleSheet("QTabBar::tab{width:23px; height:90;}")
self.addTab(self.generateBasicTab(), "Basic")
self.addTab(self.generateVisionTab(), "Vision")
self.addTab(self.generateLogicTab(), "Logic")
self.addTab(self.generateFunctionsTab(), "Functions")
self.setTabPosition(QtWidgets.QTabWidget.East)
self.setFixedWidth(85)
# Put Commands into the menu in these functions
def generateBasicTab(self):
tabWidget, add = self.generateTabWidget()
add(MoveXYZCommand)
add(MoveWristCommand)
add(MotionRecordingCommand)
add(SpeedCommand)
add(AttachCommand)
add(DetachCommand)
add(GripCommand)
add(DropCommand)
add(WaitCommand)
add(BuzzerCommand)
return tabWidget
def generateVisionTab(self):
tabWidget, add = self.generateTabWidget()
add(MoveRelativeToObjectCommand)
add(MoveWristRelativeToObjectCommand)
add(PickupObjectCommand)
add(TestObjectSeenCommand)
add(TestObjectLocationCommand)
add(TestObjectAngleCommand)
return tabWidget
def generateLogicTab(self):
tabWidget, add = self.generateTabWidget()
add(SetVariableCommand)
add(TestVariableCommand)
add(LoopCommand)
add(ElseCommand)
add(StartBlockCommand)
add(EndBlockCommand)
add(EndEventCommand)
add(EndTaskCommand)
return tabWidget
def generateFunctionsTab(self):
tabWidget, add = self.generateTabWidget()
add(ScriptCommand)
add(RunTaskCommand)
add(RunFunctionCommand)
return tabWidget
# Other
def generateButton(self, commandType):
"""
Creates a button with the icon of a command, that can be clicked and dragged onto a CommandList
"""
newButton = self.DraggableButton(str(commandType.__name__), self)
newButton.setIcon(QtGui.QIcon(commandType.icon))
newButton.setIconSize(QtCore.QSize(32, 32))
newButton.setToolTip(commandType.tooltip)
newButton.setFixedHeight(40)
newButton.setFixedWidth(40)
newButton.customContextMenuRequested.connect(lambda: self.addCommandFunc(commandType))
return newButton
def generateTabWidget(self):
"""
Creates a tab widget, and an "add" function that can be used to add widgets to the main layout of the tab.
This simplifies a lot, I promise.
:return:
"""
tabWidget = QtWidgets.QWidget()
vBox = QtWidgets.QVBoxLayout()
vBox.setAlignment(QtCore.Qt.AlignTop)
tabWidget.setLayout(vBox)
add = lambda btnType: vBox.addWidget(self.generateButton(btnType))
return tabWidget, add
# Special button that can be dragged and dropped, with information about the Type of command
class DraggableButton(QtWidgets.QPushButton):
def __init__(self, dragData, parent):
super().__init__(parent)
self.dragData = dragData # The information that will be transfered upon drag
self.mouse_down = False # Has a left-click happened yet?
self.mouse_posn = QtCore.QPoint() # If so, this is where...
self.mouse_time = QtCore.QTime() # ... and this is when
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.mouse_down = True # we are left-clicked-upon
self.mouse_posn = event.pos() # here and...
self.mouse_time.start() # ...now
event.ignore()
super().mousePressEvent(event) # pass it on up
def mouseMoveEvent(self, event):
if self.mouse_down:
# Mouse left-clicked and is now moving. Is this the start of a
# drag? Note time since the click and approximate distance moved
# since the click and test against the app's standard.
t = self.mouse_time.elapsed()
d = (event.pos() - self.mouse_posn).manhattanLength()
if t >= QtWidgets.QApplication.startDragTime() or d >= QtWidgets.QApplication.startDragDistance():
# Yes, a proper drag is indicated. Commence dragging.
self.dragEvent(QtCore.Qt.CopyAction | QtCore.Qt.MoveAction)
event.accept()
return
# Move does not (yet) constitute a drag, ignore it.
event.ignore()
super().mouseMoveEvent(event)
def dragEvent(self, actions):
# Taken straight from Qt documentation
# Create the QDrag object
dragster = QtGui.QDrag(self)
# Make a scaled pixmap of our widget to put under the cursor.
thumb = self.grab() # .scaledToHeight(32)
dragster.setPixmap(thumb)
dragster.setHotSpot(QtCore.QPoint(thumb.width() / 2, thumb.height() / 2))
# Create some data to be dragged and load it in the dragster.
md = QtCore.QMimeData()
md.setText(self.dragData)
dragster.setMimeData(md)
# Initiate the drag, which really is a form of modal dialog.
# Result is supposed to be the action performed at the drop.
act = dragster.exec_(actions)
defact = dragster.defaultAction()
return
class CommandGUI:
tooltip = ''
icon = ''
title = ''
defaultTextBoxWidth = 150
def __init__(self, parameters):
self.description = ""
self.parameters = parameters # For commands with no parameters, this should stay empty
def openWindow(self): # Open window
# If this object has no window object, then skip this process and return true (ei, StartBlockCommand)
if self.parameters is None: return True
##### Create the base window #####
prompt = QtWidgets.QDialog()
# Create the apply/cancel buttons, connect them, and format them
prompt.applyBtn = QtWidgets.QPushButton('Apply')
cancelBtn = QtWidgets.QPushButton('Cancel')
helpBtn = QtWidgets.QPushButton('User Manual')
prompt.applyBtn.setMinimumWidth(90)
cancelBtn.setMinimumWidth(90)
helpBtn.setMinimumWidth(90)
prompt.applyBtn.clicked.connect(prompt.accept)
cancelBtn.clicked.connect(prompt.reject)
helpBtn.clicked.connect(lambda: webbrowser.open_new(Paths.user_manual))
prompt.applyBtn.setDefault(True)
# Create a content box for the command to fill out parameters and GUI elements
prompt.content = QtWidgets.QVBoxLayout()
prompt.content.setContentsMargins(20, 10, 20, 10)
prompt.content.setAlignment(QtCore.Qt.AlignTop)
contentGroupBox = QtWidgets.QGroupBox("Parameters")
contentGroupBox.setLayout(prompt.content)
# Now that the window is 'dressed', add "Cancel" and "Apply" buttons
buttonRow = QtWidgets.QHBoxLayout()
buttonRow.addWidget(cancelBtn)
buttonRow.addWidget(helpBtn)
buttonRow.addStretch(1)
buttonRow.addWidget(prompt.applyBtn)
# Create the main vertical layout, add everything to it
prompt.mainVLayout = QtWidgets.QVBoxLayout()
prompt.mainVLayout.addWidget(contentGroupBox)
# Set the main layout and general window parameters
prompt.setMinimumWidth(350)
prompt.setMinimumHeight(350)
prompt.setLayout(prompt.mainVLayout)
prompt.setWindowTitle(self.title)
prompt.setWindowIcon(QtGui.QIcon(self.icon))
prompt.setWhatsThis(self.tooltip) # This makes the "Question Mark" button on the window show the tooltip msg
# Dress the base window (this is where the child actually puts the content into the widget)
prompt = self.dressWindow(prompt) # Calls a child function that should have this function
prompt.mainVLayout.addLayout(buttonRow) # Add button after, so hints appear above buttons
# Run the info window and prevent other windows from being clicked while open:
accepted = prompt.exec_()
# Make sure QT properly handles the memory after this function ends
prompt.close()
prompt.deleteLater()
# Get information that the user input
if accepted:
# Get information that the user input
self._extractPromptInfo(prompt)
# Update self.description for the widget to be dressed with after, by CommandList
self._updateDescription()
printf("GUI| New Command Parameters: ", self.parameters)
else:
printf("GUI| User Canceled Prompt")
return accepted
def dressWidget(self, newWidget):
self._updateDescription()
newWidget.setIcon(self.icon)
newWidget.setTitle(self.title)
newWidget.setTip(self.tooltip)
newWidget.setDescription(self.description)
return newWidget
def getSaveData(self):
commandSave = { 'type': self.__class__.__name__,
'parameters': self.parameters}
return commandSave
# Empty functions so that subclasses without them don't cause errors
def _updateDescription(self):
# This is called in openWindow() and will update the decription to match the parameters
pass
# Helper functions for general Command children purposes
def _sanitizeEval(self, inputTextbox, fallback):
"""
Checks if the eval statement is python-parsible. If it is not, it will return the "fallback" value.
"""
# Makes sure that the statement is parseable by python
inputCode = inputTextbox.text()
inputCode = inputCode.replace('^', '**')
try:
ast.parse(inputCode)
except SyntaxError:
return fallback
return inputCode
def _sanitizeVariable(self, inputTextbox, fallback):
# Sanitize input from the user
possibleVariable = str(inputTextbox.text())
# Remove invalid characters
possibleVariable = re.sub('[^0-9a-zA-Z_]', '', possibleVariable)
# Remove leading characters until we find a letter or underscore
possibleVariable = re.sub('^[^a-zA-Z_]+', '', possibleVariable)
# If the variable has been changed, then it was not valid, so return the "fallback" instead.
if not possibleVariable == inputTextbox.text():
return fallback
return possibleVariable
# The following are helper functions for modifying the prompt window in a consistent way
def _addRow(self, prompt, *args, alignRight=True, resizeBox=True):
# If any argument is of the following type, then set the width to self.defaultTextBoxWidth
setWidthOnTypes = [QtWidgets.QLineEdit, QtWidgets.QComboBox, QtWidgets.QPushButton, QtWidgets.QSlider]
row = QtWidgets.QHBoxLayout()
# Push objects together, otherwise keep it centered
if alignRight: row.addStretch(1)
for widget in args:
# Set the width if it is a typ
if type(widget) in setWidthOnTypes and resizeBox:
widget.setFixedWidth(self.defaultTextBoxWidth)
# Creates and adds a row to prompt.content, with proper formatting
row.addWidget(widget)
prompt.content.addLayout(row)
def _addSpacer(self, prompt):
"""
Add a certain amount of pixels of spacing between two rows in the prompt window
"""
height = 20
column = QtWidgets.QVBoxLayout()
column.addSpacing(height)
prompt.content.addLayout(column)
def _addHint(self, prompt, hintText):
"""
Add some text (usually at the bottom of the prompt) that tells the user something to help them out
HintText is bolded by default, and always appears in the same spot.
"""
prompt.hintLbl = QtWidgets.QLabel(hintText)
prompt.hintLbl.setWordWrap(True)
# Make the hint bold
bold = QtGui.QFont()
bold.setBold(True)
prompt.hintLbl.setFont(bold)
# Create a row for the hint
hintRow = QtWidgets.QHBoxLayout()
hintRow.addWidget(prompt.hintLbl)
# Add it to the prompt
prompt.content.addLayout(hintRow)
def _addObjectHint(self, prompt, numResources):
"""
This is a hint that goes onto any command that asks the user to choose from a vision object. It tells them
that they can create objects in the Resource Manager
"""
# If there are no objects, place a nice label to let the user know
if numResources == 0:
hintText = "You have not created any trackable objects yet." + \
" Try adding new objects in the Resource Manager!"
self._addHint(prompt, hintText)
elif numResources == 1:
hintText = "It looks like you've only created one object." + \
" Feel free to add new objects in the Resource Manager!"
self._addHint(prompt, hintText)
def _addRecordingHint(self, prompt, numResources):
"""
This is a hint that goes onto any command that uses motion recordings, to warn the user if they have not
created any motion recordings
"""
if numResources == 0:
hintText = "You have not created any Movement Recordings yet. " + \
"Try creating new recordings in the Resource Manager!"
self._addHint(prompt, hintText)
def _addFunctionHint(self, prompt, numResources):
if numResources == 0:
hintText = "You have not created any Functions yet. " + \
"Try creating new functions in the Resource Manager!"
self._addHint(prompt, hintText)
########## COMMANDS ##########
"""
Commands must have:
- A class, here in CommandsGUI.py
- A logic implimentation under Commands.py with a run() function
- The logic implimentation MUST have the same name as the GUI implimentation
- Be added to the CommandMenuWidget.initUI() function in order for the user to add it to their programs
- Variables
- tooltip
- icon
- title (Except for certain functions, such as StartBlockCommand)
- Functions
- init(env, parameters=None) function
- Must calls super(NAME, self).__init__(parent)
- If the command has a description, it must have a updateDescription() method
- If the command has a window, it must have the following methods:
- dressWindow(prompt)
- extractPromptInfo(prompt)
Special Cases:
-StartBlockCommand and EndBlockCommand are used directly in ControlPanelGUI.py to indent code blocks correctly
-ElseCommand is used directly in the Interpreter for processing code
-Test commands should be entered in ControlPanelGUI.CommandList.dropEvent() so that when it is dropped, a
StartBlockCommand and EndBlockCommand is placed after it, for the users convenience
----------------------------------------COMMAND TEMPLATE-------------------------------------------
class NameCommand(CommandGUI):
title = "Example Title"
tooltip = "This tool does X Y and Z"
icon = Paths.some_icon
def __init__(self, env, parameters=None):
super(NameCommand, self).__init__(parameters)
# If parameters do not exist, then set up the default parameters
if self.parameters is None:
# Anything done with env should be done here. Try not to save env as a class variable whenever possible
self.parameters = {}
def dressWindow(self, prompt):
# Do some GUI code setup
# Put all the objects into horizontal layouts called Rows
self._addRow(prompt, some GUI label, some GUI object) # Add rows using self._addRow to keep consistency
return prompt
def _extractPromptInfo(self, prompt):
newParameters = {} # Get the parameters from the 'prompt' GUI elements. Put numbers through self.sanitizeFloat
self.parameters.update(newParameters)
return self.parameters
def _updateDescription(self):
self.description = "" # Some string that uses your parameters to describe the object.
-----------------------------------------------------------------------------------------------------
"""
# BASIC CONTROL COMMANDS
class MoveXYZCommand(CommandGUI):
title = "Move XYZ"
tooltip = "Set the robots position.\n"\
"If you do not want to set one of the robots axis, simply leave it empty. For example, put y and z \n"\
"empty and x to 5 will set the robots x position to 5 while keeping the current Y and Z the same."
icon = Paths.command_xyz
def __init__(self, env, parameters=None):
super(MoveXYZCommand, self).__init__(parameters)
self.getCoordinates = env.getRobot().getCoords
if self.parameters is None:
# If no parameters were given, it's a new command. Thus, get the robots current position and fill it in.
# This helps with workflow so you can create MoveXYZ commands and move the robot around as you work with it
currentXYZ = self.getCoordinates()
self.parameters = {'x': round(currentXYZ[0], 1),
'y': round(currentXYZ[1], 1),
'z': round(currentXYZ[2], 1),
'relative': False}
def dressWindow(self, prompt):
# Prompt is a QDialog type, this is simply a function to dress it up with the appropriate interface
# Then it's returned, and the Command.openView() function will open the window and perform appropriate actions
def setCoordinates(xEdt, yEdt, zEdt):
x, y, z = self.getCoordinates()
xEdt.setText(str(round(x, 1)))
yEdt.setText(str(round(y, 1)))
zEdt.setText(str(round(z, 1)))
# Input: the base window with the cancel and apply buttons, and the layouts set up and connected
getCurrBtn = QtWidgets.QPushButton("Get Position")
prompt.xEdit = QtWidgets.QLineEdit() # Rotation textbox
prompt.yEdit = QtWidgets.QLineEdit() # Stretch textbox
prompt.zEdit = QtWidgets.QLineEdit() # Height textbox
prompt.ovrCheck = QtWidgets.QCheckBox() # "override" CheckBox
prompt.rltCheck = QtWidgets.QCheckBox() # "relative" CheckBox
getCurrBtn.clicked.connect(lambda: setCoordinates(prompt.xEdit, prompt.yEdit, prompt.zEdit))
# Set up all the labels for the inputs
xLabel = QtWidgets.QLabel('X ')
yLabel = QtWidgets.QLabel('Y ')
zLabel = QtWidgets.QLabel('Z ')
rltCheck = QtWidgets.QLabel('Relative ')
# Fill the textboxes with the default parameters
prompt.xEdit.setText(str(self.parameters['x']))
prompt.yEdit.setText(str(self.parameters['y']))
prompt.zEdit.setText(str(self.parameters['z']))
prompt.rltCheck.setChecked(self.parameters['relative'])
self._addRow(prompt, getCurrBtn)
self._addRow(prompt, xLabel, prompt.xEdit)
self._addRow(prompt, yLabel, prompt.yEdit)
self._addRow(prompt, zLabel, prompt.zEdit)
self._addRow(prompt, rltCheck, prompt.rltCheck)
return prompt
def _extractPromptInfo(self, prompt):
# Update the parameters and the description
newParameters = {'x': self._sanitizeEval(prompt.xEdit, self.parameters["x"]),
'y': self._sanitizeEval(prompt.yEdit, self.parameters["y"]),
'z': self._sanitizeEval(prompt.zEdit, self.parameters["z"]),
'relative': prompt.rltCheck.isChecked()}
self.parameters.update(newParameters)
return self.parameters
def _updateDescription(self):
# Update the description, for the dressWidget() and the openView() prompt
self.description = 'XYZ( ' + str(self.parameters['x']) + \
', ' + str(self.parameters['y']) + \
', ' + str(self.parameters['z']) + ')'
if self.parameters['relative']: self.description += ' Relative'
class MoveWristCommand(CommandGUI):
title = "Set Wrist Angle"
tooltip = "This command sets the angle of the robots 4th axis, the wrist."
icon = Paths.command_move_wrist
def __init__(self, env, parameters=None):
super(MoveWristCommand, self).__init__(parameters)
self.getWristAngle = lambda: env.getRobot().getAngles()[3]
if self.parameters is None:
currentWrist = self.getWristAngle()
self.parameters = {"angle": str(currentWrist),
"relative": False}
def dressWindow(self, prompt):
def setCurrentAngle(edit):
angle = self.getWristAngle()
edit.setText(str(round(angle, 1)))
# Create what the user will be interacting with
prompt.wristEdit = QtWidgets.QLineEdit()
prompt.rltCheck = QtWidgets.QCheckBox() # "relative" CheckBox
currentAngleBtn = QtWidgets.QPushButton("Get Angle")
currentAngleBtn.clicked.connect(lambda: setCurrentAngle(prompt.wristEdit))
# Create the labels for the interactive stuff
wristLabel = QtWidgets.QLabel('Angle ')
rltLabel = QtWidgets.QLabel('Relative ')
# Set up everything so it matches the current parameters
prompt.wristEdit.setText( self.parameters["angle"])
prompt.rltCheck.setChecked(self.parameters["relative"])
self._addRow(prompt, currentAngleBtn)
self._addRow(prompt, wristLabel, prompt.wristEdit)
self._addRow(prompt, rltLabel, prompt.rltCheck)
return prompt
def _extractPromptInfo(self, prompt):
newParameters = {"angle": self._sanitizeEval(prompt.wristEdit, self.parameters["angle"]),
"relative": prompt.rltCheck.isChecked()}
self.parameters.update(newParameters)
return self.parameters
def _updateDescription(self):
self.description = "Set the wrist position to " + self.parameters["angle"] + " degrees"
if self.parameters['relative']: self.description += ' Relative'
class MotionRecordingCommand(CommandGUI):
title = "Play Movement Recording"
tooltip = "This will play back a 'Movement recording' at a playback speed of your choosing. To create robot\n" + \
"movement recordings, simply click on 'Resources' on the toolbar and add a new recording."
icon = Paths.command_play_path
def __init__(self, env, parameters=None):
super(MotionRecordingCommand, self).__init__(parameters)
objManager = env.getObjectManager()
self.getObjectList = lambda: objManager.getObjectNameList(typeFilter=objManager.MOTIONPATH)
if self.parameters is None:
self.parameters = {"objectID": "",
"reversed": False,
"speed": "1.0"}
def dressWindow(self, prompt):
# Choose a recording
choiceLbl = QtWidgets.QLabel("Choose a Recording ")
prompt.recChoices = QtWidgets.QComboBox()
prompt.recChoices.addItem(self.parameters["objectID"])
recList = self.getObjectList()
for objectID in recList: prompt.recChoices.addItem(objectID)
self._addRow(prompt, choiceLbl, prompt.recChoices)
# PlaybackSpeed
speedLbl = QtWidgets.QLabel("Playback Speed ")
prompt.speedEdit = QtWidgets.QLineEdit()
prompt.speedEdit.setText(self.parameters["speed"])
self._addRow(prompt, speedLbl, prompt.speedEdit)
# Reversed?
reversedLbl = QtWidgets.QLabel("Play in reverse?")
prompt.reverseCheck = QtWidgets.QCheckBox()
prompt.reverseCheck.setChecked(self.parameters["reversed"])
self._addRow(prompt, reversedLbl, prompt.reverseCheck)
self._addRecordingHint(prompt, len(recList))
return prompt
def _extractPromptInfo(self, prompt):
newParameters = {"objectID": str(prompt.recChoices.currentText()),
"reversed": prompt.reverseCheck.isChecked(),
"speed": self._sanitizeEval(prompt.speedEdit, self.parameters["speed"])}
self.parameters.update(newParameters)
return self.parameters
def _updateDescription(self):
self.description = "Play movement recording " + self.parameters["objectID"] \
+ " Speed x" + str(self.parameters["speed"])
if self.parameters["reversed"]: self.description += " reversed"
class SpeedCommand(CommandGUI):
title = "Set Speed"
tooltip = "This tool sets the speed of the robot for any move commands that are done after this. \n" \
"For example, if you set the speed to 20, then do two Move XYZ commands, the robot will move to \n" \
"those locations with a speed of 20 cm/s. The default robot speed is 10 cm/s. "
icon = Paths.command_speed
def __init__(self, env, parameters=None):
super(SpeedCommand, self).__init__(parameters)
if self.parameters is None:
# Some code to set up default parameters
self.parameters = {"speed": str(10)}
def dressWindow(self, prompt):
prompt.speedEdit = QtWidgets.QLineEdit()
# Set up all the labels for the inputs
speedLabel = QtWidgets.QLabel('Speed (cm/s) ')
# Fill the textboxes with the default parameters
prompt.speedEdit.setText(str(self.parameters['speed']))
self._addRow(prompt, speedLabel, prompt.speedEdit)
return prompt
def _extractPromptInfo(self, prompt):
newParameters = {'speed': self._sanitizeEval(prompt.speedEdit, self.parameters['speed'])}
self.parameters.update(newParameters)
return self.parameters
def _updateDescription(self):
self.description = 'Set robot speed to ' + str(self.parameters['speed']) + " cm/s"
class DetachCommand(CommandGUI):
title = "Detach Servos"
tooltip = "Disengage the specified servos on the robot"
icon = Paths.command_detach
def __init__(self, env, parameters=None):
super(DetachCommand, self).__init__(parameters)
if self.parameters is None:
self.parameters = {'servo0': True,
'servo1': True,
'servo2': True,
'servo3': True}
def dressWindow(self, prompt):
# Do some GUI code setup
# Put all the objects into horizontal layouts called Rows
prompt.srvo1Box = QtWidgets.QCheckBox() # Rotation textbox
prompt.srvo2Box = QtWidgets.QCheckBox() # Stretch textbox
prompt.srvo3Box = QtWidgets.QCheckBox() # Height textbox
prompt.srvo4Box = QtWidgets.QCheckBox() # "relative" CheckBox
# Set up all the labels for the inputs
label1 = QtWidgets.QLabel('Base Servo ')
label2 = QtWidgets.QLabel('Stretch Servo ')
label3 = QtWidgets.QLabel('Height Servo ')
label4 = QtWidgets.QLabel('Wrist Servo ')
# Fill the textboxes with the default parameters
prompt.srvo1Box.setChecked(self.parameters['servo0'])
prompt.srvo2Box.setChecked(self.parameters['servo1'])
prompt.srvo3Box.setChecked(self.parameters['servo2'])
prompt.srvo4Box.setChecked(self.parameters['servo3'])
self._addRow(prompt, label1, prompt.srvo1Box)
self._addRow(prompt, label2, prompt.srvo2Box)
self._addRow(prompt, label3, prompt.srvo3Box)
self._addRow(prompt, label4, prompt.srvo4Box)
return prompt
def _extractPromptInfo(self, prompt):
newParameters = {'servo0': prompt.srvo1Box.isChecked(),
'servo1': prompt.srvo2Box.isChecked(),
'servo2': prompt.srvo3Box.isChecked(),
'servo3': prompt.srvo4Box.isChecked()}
self.parameters.update(newParameters)
return self.parameters
def _updateDescription(self):
descriptionBuild = "Servos"
if self.parameters["servo0"]: descriptionBuild += " Base"
if self.parameters["servo1"]: descriptionBuild += " Stretch"
if self.parameters["servo2"]: descriptionBuild += " Height"
if self.parameters["servo3"]: descriptionBuild += " Wrist"
self.description = descriptionBuild
class AttachCommand(CommandGUI):
"""
A command for attaching the servos of the robot
"""
title = "Attach Servos"
tooltip = "Re-engage servos on the robot. This will 'stiffen' the servos, and they will resist movement."
icon = Paths.command_attach
def __init__(self, env, parameters=None):
super(AttachCommand, self).__init__(parameters)
if self.parameters is None:
self.parameters = {'servo0': True,
'servo1': True,
'servo2': True,
'servo3': True}
def dressWindow(self, prompt):
# Do some GUI code setup
# Put all the objects into horizontal layouts called Rows
prompt.srvo1Box = QtWidgets.QCheckBox() # Rotation textbox
prompt.srvo2Box = QtWidgets.QCheckBox() # Stretch textbox
prompt.srvo3Box = QtWidgets.QCheckBox() # Height textbox
prompt.srvo4Box = QtWidgets.QCheckBox() # "relative" CheckBox
# Set up all the labels for the inputs
label1 = QtWidgets.QLabel('Base Servo ')
label2 = QtWidgets.QLabel('Stretch Servo ')
label3 = QtWidgets.QLabel('Height Servo ')
label4 = QtWidgets.QLabel('Wrist Servo ')
# Fill the textboxes with the default parameters
prompt.srvo1Box.setChecked(self.parameters['servo0'])
prompt.srvo2Box.setChecked(self.parameters['servo1'])
prompt.srvo3Box.setChecked(self.parameters['servo2'])
prompt.srvo4Box.setChecked(self.parameters['servo3'])
self._addRow(prompt, label1, prompt.srvo1Box)
self._addRow(prompt, label2, prompt.srvo2Box)
self._addRow(prompt, label3, prompt.srvo3Box)
self._addRow(prompt, label4, prompt.srvo4Box)
return prompt
def _extractPromptInfo(self, prompt):
newParameters = {'servo0': prompt.srvo1Box.isChecked(),
'servo1': prompt.srvo2Box.isChecked(),
'servo2': prompt.srvo3Box.isChecked(),
'servo3': prompt.srvo4Box.isChecked()}
self.parameters.update(newParameters)
return self.parameters
def _updateDescription(self):
descriptionBuild = "Servos"
if self.parameters["servo0"]: descriptionBuild += " Base"
if self.parameters["servo1"]: descriptionBuild += " Stretch"
if self.parameters["servo2"]: descriptionBuild += " Height"
if self.parameters["servo3"]: descriptionBuild += " Wrist"
self.description = descriptionBuild
class GripCommand(CommandGUI):
title = "Activate Gripper"
tooltip = "Activates the robots gripper"
icon = Paths.command_grip
def __init__(self, env, parameters=None):
super(GripCommand, self).__init__(parameters)
class WaitCommand(CommandGUI):
title = "Wait"
tooltip = "This command will wait for a certain amount of time. Time is measured in seconds."
icon = Paths.command_wait
def __init__(self, env, parameters=None):
super(WaitCommand, self).__init__(parameters)
if self.parameters is None:
self.parameters = {'time': 0.5}
pass
def dressWindow(self, prompt):
prompt.timeEdit = QtWidgets.QLineEdit()
# Set up all the labels for the inputs
timeLabel = QtWidgets.QLabel('Number of seconds ')
# Fill the textboxes with the default parameters
prompt.timeEdit.setText(str(self.parameters['time']))
self._addRow(prompt, timeLabel, prompt.timeEdit)
return prompt
def _extractPromptInfo(self, prompt):
newParameters = {'time': self._sanitizeEval(prompt.timeEdit, self.parameters['time'])}
self.parameters.update(newParameters)
return self.parameters
def _updateDescription(self):
self.description = str(self.parameters['time']) + " seconds"
class DropCommand(CommandGUI):
title = "Deactivate Gripper"
tooltip = "Deactivates the robots gripper"
icon = Paths.command_drop