-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_window.py
567 lines (501 loc) · 23.4 KB
/
main_window.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
import os
import PyQt6
import os.path
from PyQt6.QtCore import QSize, Qt, QRect
from PyQt6.QtGui import QAction, QIcon, QTextCursor
from PyQt6.QtWidgets import (
QMainWindow,
QSlider,
QMenu,
QToolBar, QStatusBar, QFileDialog, QWidget, QHBoxLayout, QTextEdit, QVBoxLayout, QLineEdit, QLabel, QPushButton,
QMessageBox
)
import niiloader
from line_plot import lineList, returnSaveLines
from niiloader import *
from ImageDisplay import *
from settingsWindow import *
from line_plot import *
from matplotlib.backends.qt_compat import QtWidgets
from matplotlib.backends.backend_qtagg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.backend_bases import NavigationToolbar2 as backendNavToolbar
import nibabel as nib
import numpy as np
# Setting a base directory for when generating a pyinstaller file
basedir = os.path.dirname(__file__)
# Creating a class that holds everything regarding the MainWindow and toolbars / menu items
class MainWindow(QMainWindow):
# used later on to hold returned info from file operations
savefile_direct = ""
importfile_direct = ""
# Constructor to create the MainWindow and call required items
def __init__(self):
# Calling the constructor of the parent class.
super().__init__()
# self.Stat_Panel()
self.edit_menu = None
self.file_menu = None
self.settings_window_been_open = False
self.settings_window = None # No external window yet.
# Setting buttons, icons and triggers on press for all buttons used.
self.Panel = None
self.text_edit = None
self.textbox = QTextEdit()
self.imageDisp = None
self.Panel = QTextEdit()
self.default_slice_number = 0
self.toolbar = None
self.slider_widget = QSlider()
self.edit_icon = QAction(QIcon(os.path.join(basedir, "iconFiles", "editIcon.png")), "Draw", self)
self.edit_icon.triggered.connect(self.edit_button_click)
self.hand_icon = QAction(QIcon(os.path.join(basedir, "iconFiles", "handIcon.png")), "Pan", self)
self.hand_icon.triggered.connect(self.hand_button_click)
self.undo_icon = QAction(QIcon(os.path.join(basedir, "iconFiles", "undo.png")), "Undo", self)
self.undo_icon.triggered.connect(self.undo)
self.redo_icon = QAction(QIcon(os.path.join(basedir, "iconFiles", "redo.png")), "Redo", self)
self.redo_icon.triggered.connect(self.redo)
self.save_icon = QAction(QIcon(os.path.join(basedir, "iconFiles", "save.png")), "Save", self)
self.save_icon.triggered.connect(self.saveButtonClick)
self.import_icon = QAction(QIcon(os.path.join(basedir, "iconFiles", "folder.png")), "Import", self)
self.import_icon.triggered.connect(self.importButtonClick)
self.comment_icon = QAction(QIcon(os.path.join(basedir, "iconFiles", "content.png")), "Comment Box/Panel", self)
self.comment_icon.triggered.connect(self.textBoxHideButton)
self.settings_icon = QAction(QIcon(os.path.join(basedir, "iconFiles", "setting.png")), "Settings", self)
self.settings_icon.triggered.connect(self.settingsClick)
# TODO - assign these to the desired functions
self.cursor_icon = QAction(QIcon(os.path.join(basedir, "iconFiles", "cursor.png")), "Cursor", self)
self.cursor_icon.triggered.connect(self.cursorClick)
self.trash_icon = QAction(QIcon(os.path.join(basedir, "iconFiles", "trash.png")), "Remove line", self)
self.trash_icon.triggered.connect(self.trashClick)
self.trash_all = QAction(QIcon(os.path.join(basedir, "iconFiles", "trash_all.png")), "Remove all lines", self)
self.trash_all.triggered.connect(self.trashAllClick)
# status tip
self.status_tip()
# creating toolbar items
self.left_toolbar = QToolBar()
self.right_toolbar = QToolBar()
self.image_data = None
# setting window title and min size (used to prevent UI being hidden from user)
self.setWindowTitle("Widgets App")
width = 1280
height = 720
self.setMinimumSize(width, height)
self.totalAxialSlice = 0
# This is calling the left_tool_bar function which is then populating the left toolbar with the buttons
self.left_tool_bar()
self.top_main_menu()
# Below used to either enable or disable the status bar that we have set things such as Pan Button or Edit
# button to
self.setStatusBar(QStatusBar(self))
# Call createImageDisplay to create Widget with QVboxLayout which has the navigationToolBar and
# ImageDisplay widgets.
self.createImageDisplay()
self.initUI()
# TODO - Temp while we assign the functions - REMOVE WHEN THE REAL FUNCTIONS HAVE BEEN ASSIGNED ABOVE
# possible to just map the function in the below functions if multiple lines are needed to call the assigned functions :)
def cursorClick(self):
print("Cursor Clicked")
self.imageDisp.cursor()
def trashClick(self):
print("Trash Clicked")
self.imageDisp.deleteOne()
def trashAllClick(self):
print("Trash All Clicked")
self.imageDisp.deleteAll()
def initUI(self):
# Add your widgets and layouts here
# Connect the closeEvent signal to the closeEvent handler
self.closeEvent = self.closeEventHandler
def closeEventHandler(self, event):
# Show a message box to confirm exit
reply = QMessageBox.question(
self, "Confirm Exit",
"Are you sure you want to exit without saving?",
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
QMessageBox.StandardButton.No
)
# If the user confirms exit, accept the close event and exit
if reply == QMessageBox.StandardButton.Yes:
event.accept()
# If the user cancels exit, ignore the close event
else:
self.saveButtonClick()
event.ignore()
# Function - self - create a right toolbar and call the slider function to add a function to this
def right_tool_bar(self):
self.right_toolbar.setIconSize(QSize(24, 24))
self.addToolBar(PyQt6.QtCore.Qt.ToolBarArea.RightToolBarArea, self.right_toolbar)
# add the slider to the toolbar
self.right_toolbar.addWidget(self.slider())
# Function - self - create the right toolbar and add pan and edit buttons
# These will call the edit_button_click and hand_button_click functions that can be added upon later
def left_tool_bar(self):
# This is creating a left toolbar that is then added to the main window. The icon size is then set to 24x24.
# Considering increasing the icon size as it's a bit small (for macOS user's a white and black icon set might
# be better for night mode)
self.left_toolbar.setIconSize(QSize(24, 24))
self.addToolBar(PyQt6.QtCore.Qt.ToolBarArea.LeftToolBarArea, self.left_toolbar)
# Creating 2 buttons, Hand and edit with their respective icons. We need to use filepath for any respective
# file paths such as icons as it will not be portable when creating .exe files
self.left_toolbar.addAction(self.hand_icon)
# Creating the second button
self.left_toolbar.addAction(self.edit_icon)
# Creating the comment button
self.left_toolbar.addAction(self.comment_icon)
# self.left_toolbar.addAction(self.cursor_icon)
self.left_toolbar.addAction(self.trash_icon)
# Ensuring that only 1 button (edit or pan) is selected at one time
self.hand_icon.toggled.connect(self.edit_icon.setDisabled)
self.edit_icon.toggled.connect(self.hand_icon.setDisabled)
self.comment_icon.toggled.connect(self.comment_icon.setDisabled)
self.left_toolbar.setDisabled(True)
def slider(self, minimum=0):
# Creating a slider widget, it is then set to have a range of 1 to 200. This is now set to the central widget
# for testing but will be moved into a toolbar on the right in the future
self.slider_widget.setRange(minimum, self.totalAxialSlice - 1)
self.slider_widget.setSingleStep(1)
# this thing here occurs on click and scroll - use this one for everything.
self.slider_widget.valueChanged.connect(self.slider_value_change)
# This thing here occurs on click - kept here if we need it in the future
# slider_widget.sliderMoved.connect(self.slider_position)
return self.slider_widget
def top_main_menu(self):
menu = self.menuBar()
self.file_menu = menu.addMenu("&File")
self.edit_menu = menu.addMenu("&Edit")
self.file_menu.addAction(self.save_icon)
self.file_menu.addAction(self.import_icon)
self.file_menu.addAction(self.settings_icon)
self.edit_menu.addAction(self.undo_icon)
self.edit_menu.addAction(self.redo_icon)
self.edit_menu.addAction(self.edit_icon)
self.edit_menu.addAction(self.hand_icon)
self.edit_menu.addAction(self.cursor_icon)
self.edit_menu.addAction(self.trash_icon)
self.edit_menu.addAction(self.trash_all)
self.edit_menu.addAction(self.comment_icon)
self.edit_menu.setDisabled(True)
# Function - self - to get a file name
def getFileName(self):
file_filter = 'NIFTI Images (*.nii *.nii.gz *.hdr)'
response = QFileDialog.getOpenFileName(
parent=self,
caption='Select a file',
directory=os.getcwd(),
filter=file_filter,
initialFilter='NIFTI Images (*.nii *.nii.gz *.hdr)'
)
return response
# Function - self - to get multiple file names
def getFileNames(self):
file_filter = 'NIFTI Images (*.nii *.nii.gz *.hdr)'
response = QFileDialog.getOpenFileNames(
parent=self,
caption='Select file(s)',
directory=os.getcwd(),
filter=file_filter,
initialFilter='NIFTI Images (*.nii *.nii.gz *.hdr)'
)
return response
# Function - self - to get a name and place to save a file
def getSaveFileName(self):
file_filter = 'NIFTI Images (*.nii *.nii.gz *.hdr) ;; All Files (*)'
response = QFileDialog.getSaveFileName(
parent=self,
caption='Select a data file',
# TODO - make sure that this is the data type that we want to return (nii, nii.gz or what?)
directory='Data File.nii',
filter=file_filter,
initialFilter='NIFTI Images (*.nii *.nii.gz *.hdr)'
)
return response
def saveButtonClick(self):
savefile_direct = self.getSaveFileName()
# print("save button pressed!")
# returns: ('/Users/alexanderelwell/Documents/GtiHub/MIDAS/Data File.nii',
# 'NIFTI Images (*.nii *.nii.gz *.hdr)')
# print(savefile_direct)
# Check that a file has been selected and stored in tuple index 0
# if it is empty, cancel or nothing has been selected, pass to avoid crash
if savefile_direct[0] == "":
pass
else:
# print(self.image_data)
self.saveFile(savefile_direct[0], self.image_data)
# Save the file to the specified location
def saveFile(self, filename, data):
# add a check to see if the file already exists and if it does, ask the user if they want to overwrite it
if (os.path.exists(filename)):
print("File already exists")
else:
print("File does not exist")
# add a check to see if the file is a nifti file and if it is not, add the appropriate extension
if (filename.endswith('.nii') or filename.endswith('.nii.gz') or filename.endswith('.hdr')):
print("File is a nifti file")
else:
filename.join('.nii')
print("File is not a nifti file")
# print(self.savefile_direct)
nii = nib.load(self.importfile_direct[0])
data = nii.get_fdata()
header = nii.header
SaveLines = line_plot.returnSaveLines()
# print(SaveLines)
if len(SaveLines) == 2:
print("One line to save")
x = str(SaveLines[0][0]*100)
print("x: " + x)
y = str(SaveLines[0][1]*100)
print("y: " + y)
slice = str(self.slider().value())
slice_update = str(slice).zfill(4)
print("slice = " + slice_update)
x2 = str(SaveLines[1][0]*100)
print("x2: " + x2)
y2 = str(SaveLines[1][1]*100)
print("y2: " + y2)
else:
print("Two lines to save")
x = str(SaveLines[-2][0]*100)
print("x: " + x)
y = str(SaveLines[-2][1]*100)
print("y: " + y)
slice = str(self.slider().value())
slice_update = str(slice).zfill(4)
print("slice = " + slice_update)
x2 = str(SaveLines[-1][0]*100)
print("x2: " + x2)
y2 = str(SaveLines[-1][1]*100)
print("y2: " + y2)
x3 = str(SaveLines[-4][0]*100)
print("x3: " + x3)
y3 = str(SaveLines[-4][1]*100)
print("y3: " + y3)
x4 = str(SaveLines[-3][0]*100)
print("x4: " + x4)
y4 = str(SaveLines[-3][1]*100)
print("y4: " + y4)
if (SaveLines != []):
# print("data type = " + x[0:5] + y[0:5] + "db_name " + x2[0:5] + y2[0:5] + "extents " + slice_update)
# line 1 data
header['data_type'] = x[0:5] + y[0:5]
header['extents'] = slice_update
header['db_name'] = x2[0:5] + y2[0:5]
# line 2
header['aux_file'] = x3[0:5] + y3[0:5] + x4[0:5] + y4[0:5]
# header['aux_file'] = np.concatenate((header.get_data_shape(), [2], new_data_line))
new_nii = nib.Nifti1Image(data, None, header=header)
nib.save(new_nii, filename)
# new_dim = np.concatenate((header.get_data_shape(), [2], new_data_line))
def importLines(self):
nii = nib.load(self.importfile_direct[0])
data = nii.get_fdata()
header = nii.header
if header['data_type'] != b'':
if header['extents'] != b'':
if header['db_name'] != b'':
stringHead = str(header['data_type'])
print(stringHead)
x = float(stringHead[2:7]) / 100
print("x: ", x)
y = float(stringHead[7:12]) / 100
print("y: ", y)
slice = int(header['extents'])
print("slice: ", slice)
stringDbName = str(header['db_name'])
x2 = float(stringDbName[2:7]) / 100
print("x2: ", x2)
y2 = float(stringDbName[7:12]) / 100
print("y2: ", y2)
# move to the slice created on
self.slider().setValue(int(slice))
line_plot.importLines(x, y, slice, x2, y2)
stringAuxFile = str(header['aux_file'])
x3 = float(stringAuxFile[2:7]) / 100
print("x3: ", x3)
y3 = float(stringAuxFile[7:12]) / 100
print("y3: ", y3)
x4 = float(stringAuxFile[12:17]) / 100
print("x4: ", x4)
y4 = float(stringAuxFile[17:22]) / 100
print("y4: ", y4)
line_plot.importLines(x3, y3, slice, x4, y4)
else:
print("No lines to import")
def importButtonClick(self):
settings = SettingsWindow()
settings.hide()
default_slice = settings.default_slice_number
self.importfile_direct = self.getFileName()
print("import button pressed!", self.importfile_direct)
# Check that a file has been selected and stored in tuple index 0
# if it is empty, cancel or nothing has been selected, pass to avoid crash
if self.importfile_direct[0] == "":
pass
else:
niiloader.loadFullFile(self.importfile_direct[0])
self.image_data = loadFile(self.importfile_direct[0])
# Display Image
self.DisplayImageSlice(default_slice)
self.totalAxialSlice = niiloader.totalAxialSlice(self.importfile_direct[0])
self.right_tool_bar()
self.left_toolbar.setEnabled(True)
self.edit_menu.setEnabled(True)
self.comment_box()
result = returnSaveLines()
# call the Stat_Panel method to update the status panel with the x and y coordinates
self.Stat_Panel()
# hack - this is a hack to get the comment and stat panel to show up correctly
self.resize(1285, 725)
self.slider_widget.setValue(default_slice)
self.importLines()
def DisplayImageSlice(self, i):
self.imageDisp.displayImage(self.image_data[:, :, i])
# createImageDisplay method creates a QVboxlayout, Then Creates instance of ImageDisplay class.
# Set the width height and resolution Then add the Navigationtoolbar and ImageDisplay Widgets to the layout.
# Create a new widget and set its layout to the layout we created.
def createImageDisplay(self):
self.layout = QtWidgets.QVBoxLayout()
self.imageDisp = ImageDisplay(self, width=20, height=20, dpi=300)
# layout.addWidget(NavigationToolbar(self.imageDisp))
self.layout.addWidget(self.imageDisp)
widget = QWidget()
widget.setLayout(self.layout)
self.setCentralWidget(widget)
@staticmethod
def color_map_setting():
# TODO - hold all of the color map as a dropdown maybe? Or just hold the data
pass
def edit_button_click(self):
# make sure that this will first disable the pan/hand button
print("Edit button pressed!")
self.imageDisp.edit()
def hand_button_click(self):
# make sure that this will first disable the edit button
print("hand button clicked!")
# TODO - make sure that this will first disable the drawing button
self.imageDisp.panZoom()
# this can be paired with the left click to get the location to pan the item to!
def mouseMoveEvent(self, e):
print("mouse moved", e.pos())
def comment_box(self):
# Bijoy Bakar - textbox
layout = QVBoxLayout()
# self.setLayout(layout)
self.textbox = QTextEdit(self)
if not self.importfile_direct:
self.textbox.setPlaceholderText("Enter text here")
else:
self.textbox.setText(loadText(self.importfile_direct[0]))
# print textbox data
self.textbox.textChanged.connect(self.on_text_box_change)
self.textbox.move(1050, 7)
self.textbox.setUndoRedoEnabled(True)
self.textbox.textChanged.connect(self.limit_text)
layout.addWidget(self.textbox)
def limit_text(self):
text = self.textbox.toPlainText()
words = text.split()
if len(words) > 80:
self.textbox.setPlainText(" ".join(words[:80]))
self.textbox.setReadOnly(True)
else:
self.textbox.setReadOnly(False)
def on_text_box_change(self):
niiloader.saveText(self.importfile_direct[0], self.textbox.toPlainText())
print(self.textbox.toPlainText())
def update_stat_panel(self):
lines = returnSaveLines()
x_coords = [str(x) for x in lines[::2]]
y_coords = [str(y) for y in lines[1::2]]
x_coords = [x[1:6] for x in x_coords]
y_coords = [y[1:6] for y in y_coords]
text = f"X-Coordinates: {', '.join(x_coords)}\n\nY-Coordinates: {', '.join(y_coords)}"
self.Panel.setText(text)
# self.Panel.setText("Diameter: \n\nX-Coordinates: \n\nY-Coordinates: ")
self.Panel.setReadOnly(True)
def textBoxHideButton(self):
if self.textbox.isHidden():
self.textbox.show()
self.Panel.show()
self.update_stat_panel()
else:
self.textbox.hide()
self.Panel.hide()
def resizeEvent(self, event):
# Comment Box
self.textbox.resize(int(event.size().width() / 5), int(event.size().height() / 5))
x = event.size().width() - self.textbox.geometry().width() - 13
self.textbox.move(x, 11)
# Stat Panel
self.Panel.resize(int(event.size().width() / 5), int(event.size().height() / 6.5))
x = event.size().width() - self.Panel.geometry().width() - 13
y = self.textbox.geometry().y() + self.textbox.geometry().height()
self.Panel.move(x, y)
def mousePressEvent(self, e):
print("mouse pressed")
# will be used to free the mouse from the pan or select tools
def mouseReleaseEvent(self, e):
print("Mose released")
def mouseDoubleClickEvent(self, e):
print("mouse double clicked")
def slider_value_change(self, i):
print("slider value changed" + str(self.settings_window_been_open))
if self.settings_window_been_open:
self.settings_window_closed()
self.settings_window_been_open = False
self.DisplayImageSlice(i)
@staticmethod
def undo():
print("undo")
@staticmethod
def redo():
print("redo")
def exit(self):
self.close()
sys.exit()
# bijoy
def status_tip(self):
self.hand_icon.setStatusTip("Pan Button")
self.edit_icon.setStatusTip("Edit Button")
self.slider_widget.setStatusTip("Slider")
self.comment_icon.setStatusTip("Comment Box/Panel")
self.save_icon.setStatusTip("Save")
self.import_icon.setStatusTip("Import")
self.redo_icon.setStatusTip("Redo")
self.undo_icon.setStatusTip("Undo")
def Stat_Panel(self):
layout = QVBoxLayout()
self.Panel = QTextEdit(self)
lines = returnSaveLines()
print("save lines is - main_window.py - line 516", lines)
x_coords = [str(x) for x in lines[::2]]
y_coords = [str(y) for y in lines[1::2]]
text = f"Diameter: \n\nX-Coordinates: {', '.join(x_coords)}\n\nY-Coordinates: {', '.join(y_coords)}"
print("text is - main_window.py - line 520", text)
self.Panel.setText(text)
#self.Panel.setText("Diameter: \n\nX-Coordinates: \n\nY-Coordinates: ")
self.Panel.setReadOnly(True)
layout.addWidget(self.Panel)
# settings window
# Setting to None to prevent more than one settings window from opening at a time - prevents settings JSON being
# written to multiple times
def settingsClick(self):
self.settings_window = SettingsWindow()
self.settings_window.show()
# on window close run a function...
self.settings_window_been_open = True
def settings_window_closed(self):
# reload the image to apply the settings
if self.totalAxialSlice == 0:
print("no image open")
pass
else:
print("image open")
self.layout.removeWidget(self.imageDisp)
self.imageDisp = ImageDisplay(self, width=20, height=20, dpi=300)
self.layout.addWidget(self.imageDisp)
# File handling was heavily inspired by the following source:
# https://learndataanalysis.org/source-code-how-to-use-qfiledialog-to-select-files-in-pyqt6/ icon attribution: <a
# href="https://www.flaticon.com/free-icons/right-arrow" title="right arrow icons">Right arrow icons created by
# nahumam - Flaticon</a>