def get_day_layout(self, day_text): day_label = QLabel(day_text) day_label.setFixedWidth(120) day_label.setFixedHeight(50) day_label.setFont(self.day_font) day_label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) gen_day_button = QPushButton("Plan day") gen_day_button.setFont(self.general_font) gen_day_button.font().setBold(False) use_day_check = QCheckBox("Use: ") use_day_check.setLayoutDirection(QtCore.Qt.RightToLeft) use_day_check.setChecked(True) use_day_check.setFont(self.general_font) day_layout = QHBoxLayout() day_layout.addWidget(day_label) day_layout.addWidget(use_day_check) info_layout = QVBoxLayout() info_layout.addLayout(day_layout) info_layout.addWidget(gen_day_button) day_text_edit = QTextEdit() day_text_edit.setFont(self.general_font) #Create, fill and return the day layout day_layout = QHBoxLayout() day_layout.addLayout(info_layout) day_layout.addWidget(day_text_edit) return day_layout
class main(QWidget): def __init__(self, parent=None): super(main, self).__init__(parent) self.setup() # connections, widgets, layouts, etc. self.blksize = 2**20 # 1 MB; must be divisible by 16 self.ext = '.enc' # extension is appended to encrypted files self.path = '' self.encrypted = [] # to highlight done files in list self.decrypted = [] self.clipboard = QApplication.clipboard() self.timeout = None # to clear message label, see setMessage # this program was just an excuse to play with QprogressBar if not hash(os.urandom(11)) % 11: QTimer().singleShot(50, self.windDown) # various random hints hints = [ 'Freshly encrypted files can be renamed in the table!', 'Clipboard is always cleared on program close!', 'Keys can contain emoji if you <em>really</em> want: \U0001f4e6', 'Keys can contain emoji if you <em>really</em> want: \U0001F511', 'This isn\'t a tip, I just wanted to say hello!', 'Keys can be anywhere from 8 to 4096 characters long!', 'This program was just an excuse to play with the progress bars!', 'Select \'Party\' in the hash button for progress bar fun!', ('Did you know you can donate one or all of your vital organs to ' 'the Aperture Science Self-Esteem Fund for Girls? It\'s true!'), ('It\'s been {:,} days since Half-Life 2: Episode ' 'Two'.format(int((time.time() - 1191988800) / 86400))), 'I\'m version {}!'.format(VERSION), 'I\'m version {}.whatever!'.format(VERSION.split('.')[0]), ('Brought to you by me, I\'m <a href="https://orthallelous.word' 'press.com/">Orthallelous!</a>'), #'Brought to you by me, I\'m Htom Sirveaux!', 'I wonder if there\'s beer on the sun', 'Raspberry World: For all your raspberry needs. Off the beltline', #'I\'ve plummented to my death and I can\'t get up', '<em>NOT</em> compatible with the older version!', ('Hello there, fellow space travellers! Until somebody gives me ' 'some new lines in KAS, that is all I can say. - Bentusi Exchange' ) ] if not hash(os.urandom(9)) % 4: self.extraLabel.setText(random.choice(hints)) def genKey(self): "generate a random key" n = self.keySizeSB.value() char = string.printable.rstrip() #map(chr, range(256)) while len(char) < n: char += char key = ''.join(random.sample(char, n)) self.keyInput.setText(key) def showKey(self, state=None): "hide/show key characters" if state is None: state = bool(self.showKeyCB.checkState()) else: state = bool(state) if state: self.keyInput.setEchoMode(QLineEdit.Normal) else: self.keyInput.setEchoMode(QLineEdit.PasswordEchoOnEdit) def getFolder(self): "open file dialog and fill file table" path = QFileDialog(directory=self.path).getExistingDirectory() if not path: return self.path = str(path) self.populateTable(self.path) self.encrypted, self.decrypted = [], [] return def resizeEvent(self, event): self.showFolder(self.path) # update how the folder is shown def splitterChanged(self, pos): self.showFolder(self.path) # likewise def showFolder(self, path): "displays current path, truncating as needed" if not path: return ell, sl = '\u2026', os.path.sep # ellipsis, slash chars lfg, rfg = Qt.ElideLeft, Qt.ElideRight lst, wdh = os.path.basename(path), self.folderLabel.width() path = path.replace(os.path.altsep or '\\', sl) self.folderLabel.setToolTip(path) # truncate folder location fnt = QFontMetrics(self.folderLabel.font()) txt = str(fnt.elidedText(path, lfg, wdh)) if len(txt) <= 1: # label is way too short self.folderLabel.setText('\u22ee' if txt != sl else txt) return # but when would this happen? # truncate some more (don't show part of a folder name) if len(txt) < len(path) and txt[1] != sl: txt = ell + sl + txt.split(sl, 1)[-1] # don't truncate remaining folder name from the left if txt[2:] != lst and len(txt[2:]) < len(lst) + 2: txt = str(fnt.elidedText(ell + sl + lst, rfg, wdh)) # you'd think len(txt) < len(lst) would work, but no; you'd be wrong self.folderLabel.setText(txt) def populateTable(self, path): "fill file table with file names" self.showFolder(path) names = [] for n in os.listdir(path): if os.path.isdir(os.path.join(path, n)): continue # folder names.append(n) self.folderTable.clearContents() self.folderTable.setRowCount(len(names)) self.folderTable.setColumnCount(1) if not names: # no files in this folder, inform user self.setMessage('This folder has no files') return self.folderTable.blockSignals(True) selEnab = Qt.ItemIsSelectable | Qt.ItemIsEnabled for i, n in enumerate(names): item = QTableWidgetItem() item.setText(n) item.setToolTip(n) item.setFlags(selEnab) # color code encrypted/decrypted files if n in self.encrypted: item.setTextColor(QColor(211, 70, 0)) # allowed encrypted filenames to be changed item.setFlags(selEnab | Qt.ItemIsEditable) if n in self.decrypted: item.setForeground(QColor(0, 170, 255)) self.folderTable.setItem(i, 0, item) if len(names) > 5: self.setMessage('{:,} files'.format(len(names)), 7) self.folderTable.blockSignals(False) return def editFileName(self, item): "change file name" new, old = str(item.text()), str(item.toolTip()) result = QMessageBox.question( self, 'Renaming?', ("<p align='center'>Do you wish to rename<br>" + '<span style="color:#d34600;">{}</span>'.format(old) + "<br>to<br>" + '<span style="color:#ef4b00;">{}</span>'.format(new) + '<br>?</p>')) self.folderTable.blockSignals(True) if any(i in new for i in '/?<>:*|"^'): self.setMessage('Invalid character in name', 7) item.setText(old) elif result == QMessageBox.Yes: oold = os.path.join(self.path, old) try: os.rename(oold, os.path.join(self.path, new)) self.encrypted.remove(old) self.encrypted.append(new) item.setToolTip(new) except Exception as err: self.setMessage(str(err), 9) item.setText(old) item.setToolTip(old) self.encrypted.remove(new) self.encrypted.append(old) else: item.setText(old) self.folderTable.blockSignals(False) def setMessage(self, message, secs=4, col=None): "show a message for a few seconds - col must be rgb triplet tuple" if self.timeout: # https://stackoverflow.com/a/21081371 self.timeout.stop() self.timeout.deleteLater() if col is None: color = 'rgb(255, 170, 127)' else: try: color = 'rgb({}, {}, {})'.format(*col) except: color = 'rgb(255, 170, 127)' self.messageLabel.setStyleSheet('background-color: {};'.format(color)) self.messageLabel.setText(message) self.messageLabel.setToolTip(message) self.timeout = QTimer() self.timeout.timeout.connect(self.clearMessage) self.timeout.setSingleShot(True) self.timeout.start(secs * 1000) def clearMessage(self): self.messageLabel.setStyleSheet('') self.messageLabel.setToolTip('') self.messageLabel.setText('') def getName(self): "return file name of selected" items = self.folderTable.selectedItems() names = [str(i.text()) for i in items] if names: return names[0] # only the first selected file else: return '' def showKeyLen(self, string): "displays a tooltip showing length of key" s = len(string) note = '{:,} character{}'.format(s, '' if s == 1 else 's') tip = QToolTip pos = self.genKeyButton.mapToGlobal(QPoint(0, 0)) if s < self.minKeyLen: note = '<span style="color:#c80000;">{}</span>'.format(note) else: note = '<span style="color:#258f22;">{}</span>'.format(note) tip.showText(pos, note) def lock(self, flag=True): "locks buttons if True" stuff = [ self.openButton, self.encryptButton, self.decryptButton, self.genKeyButton, self.hashButton, self.showKeyCB, self.copyButton, self.keyInput, self.keySizeSB, self.folderTable, ] for i in stuff: i.blockSignals(flag) i.setEnabled(not flag) return def _lerp(self, v1, v2, numPts=10): "linearly interpolate from v1 to v2\nFrom Orthallelous" if len(v1) != len(v2): raise ValueError("different dimensions") D, V, n = [], [], abs(numPts) for i, u in enumerate(v1): D.append(v2[i] - u) for i in range(n + 1): vn = [] for j, u in enumerate(v1): vn.append(u + D[j] / float(n + 2) * i) V.append(tuple(vn)) return V def weeeeeee(self): "party time" self.lock() self.setMessage('Party time!', 2.5) a, b, c = self.encryptPbar, self.decryptPbar, self.hashPbar process, sleep = app.processEvents, time.sleep am, bm, cm = a.minimum(), b.minimum(), c.minimum() ax, bx, cx = a.maximum(), b.maximum(), c.maximum() a.reset() b.reset() c.reset() loops = self._lerp((am, bm, cm), (ax, bx, cx), 100) ivops = loops[::-1] # up and up! for i in range(3): for j, k, l in loops: a.setValue(int(j)) b.setValue(int(k)) c.setValue(int(l)) process() sleep(0.01) a.setValue(ax) b.setValue(bx) c.setValue(cx) sleep(0.25) a.setValue(am) b.setValue(bm) c.setValue(cm) # snake! self.setMessage('Snake time!') self.messageLabel.setStyleSheet('background-color: rgb(127,170,255);') for i in range(2): for j, k, l in loops: a.setValue(int(j)) process() sleep(0.002) process() a.setInvertedAppearance(True) process() for j, k, l in ivops: a.setValue(int(j)) process() sleep(0.002) for j, k, l in loops: b.setValue(int(k)) process() sleep(0.002) process() b.setInvertedAppearance(False) process() for j, k, l in ivops: b.setValue(int(k)) process() sleep(0.002) for j, k, l in loops: c.setValue(int(l)) process() sleep(0.002) process() c.setInvertedAppearance(True) process() for j, k, l in ivops: c.setValue(int(l)) process() sleep(0.002) process() b.setInvertedAppearance(True) process() for j, k, l in loops: b.setValue(int(k)) process() sleep(0.002) process() b.setInvertedAppearance(False) process() for j, k, l in ivops: b.setValue(int(k)) process() sleep(0.002) process() a.setInvertedAppearance(False) b.setInvertedAppearance(True) c.setInvertedAppearance(False) for j, k, l in loops: a.setValue(int(j)) process() sleep(0.002) process() a.setInvertedAppearance(True) process() for j, k, l in ivops: a.setValue(int(j)) process() sleep(0.002) # bars sleep(0.5) self.setMessage('Bars!') process() self.messageLabel.setStyleSheet('background-color: rgb(127,255,170);') for i in range(2): a.setValue(ax) time.sleep(0.65) a.setValue(am) sleep(0.25) process() b.setValue(bx) time.sleep(0.65) b.setValue(bm) sleep(0.25) process() c.setValue(cx) time.sleep(0.65) c.setValue(cm) sleep(0.25) process() b.setValue(bx) time.sleep(0.65) b.setValue(bm) sleep(0.25) process() # okay, enough process() a.setValue(ax) b.setValue(bx) c.setValue(cx) #a.setValue(am); b.setValue(bm); c.setValue(cm) a.setInvertedAppearance(False) b.setInvertedAppearance(True) c.setInvertedAppearance(False) self.lock(False) return def windDown(self, note=None): "silly deload on load" if note is None: note = 'Loading...' self.lock() self.setMessage(note) self.messageLabel.setStyleSheet('background-color: rgb(9, 190, 130);') a, b, c = self.encryptPbar, self.decryptPbar, self.hashPbar am, bm, cm = a.minimum(), b.minimum(), c.minimum() ax, bx, cx = a.maximum(), b.maximum(), c.maximum() a.reset() b.reset() c.reset() loops = self._lerp((ax, bx, cx), (am, bm, cm), 100) for j, k, l in loops: a.setValue(int(j)) b.setValue(int(k)) c.setValue(int(l)) app.processEvents() time.sleep(0.02) a.reset() b.reset() c.reset() self.lock(False) self.clearMessage() def genHash(self, action): "generate hash of selected file and display it" name, t0 = self.getName(), time.perf_counter() # mark what hash was used in the drop-down menu for i in self.hashButton.menu().actions(): if i == action: i.setIconVisibleInMenu(True) else: i.setIconVisibleInMenu(False) if str(action.text()) == 'Party': self.weeeeeee() self.windDown('Winding down...') return if not name: self.setMessage('No file selected') return if not os.path.exists(os.path.join(self.path, name)): self.setMessage('File does not exist') return self.lock() hsh = self.hashFile(os.path.join(self.path, name), getattr(hashlib, str(action.text()))) self.lock(False) #hsh = str(action.text()) + ': ' + hsh self.hashLabel.setText(hsh) self.hashLabel.setToolTip(hsh) self.extraLabel.setText( str(action.text()) + ' hash took ' + self.secs_fmt(time.perf_counter() - t0)) def setCancel(self): "cancel operation" self._requestStop = True def showCancelButton(self, state=False): "show/hide cancel button" self.cancelButton.blockSignals(not state) self.cancelButton.setEnabled(state) if state: self.cancelButton.show() self.keyInput.hide() self.genKeyButton.hide() self.keySizeSB.hide() else: self.cancelButton.hide() self.keyInput.show() self.genKeyButton.show() self.keySizeSB.show() def hashFile(self, fn, hasher): "returns the hash value of a file" hsh, blksize = hasher(), self.blksize fsz, csz = os.path.getsize(fn), 0.0 self.hashPbar.reset() self.showCancelButton(True) prog, title = '(# {:.02%}) {}', self.windowTitle() with open(fn, 'rb') as f: while 1: blk = f.read(blksize) if not blk: break hsh.update(blk) csz += blksize self.hashPbar.setValue(int(round(csz * 100.0 / fsz))) app.processEvents() self.setWindowTitle(prog.format(csz / fsz, title)) if self._requestStop: break self.hashPbar.setValue(self.hashPbar.maximum()) self.setWindowTitle(title) self.showCancelButton(False) if self._requestStop: self.setMessage('Hashing canceled!') self.hashPbar.setValue(self.hashPbar.minimum()) self._requestStop = False return return hsh.hexdigest() def hashKey(self, key, salt=b''): "hashes a key for encrypting/decrypting file" salt = salt.encode() if type(salt) != bytes else salt key = key.encode() if type(key) != bytes else key p = app.processEvents self.setMessage('Key Hashing...', col=(226, 182, 249)) p() key = hashlib.pbkdf2_hmac('sha512', key, salt, 444401) p() self.clearMessage() p() return hashlib.sha3_256(key).digest() # AES requires a 32 char key def encrypt(self): "encrypt selected file with key" name, t0 = self.getName(), time.perf_counter() if not name: self.setMessage('No file selected') return if not os.path.exists(os.path.join(self.path, name)): self.setMessage('File does not exist') return key = str(self.keyInput.text()) if len(key) < self.minKeyLen: self.setMessage(('Key must be at least ' '{} characters long').format(self.minKeyLen)) return self.lock() gn = self.encryptFile(key, os.path.join(self.path, name)) if not gn: self.lock(False) return self.encrypted.append(os.path.basename(gn)) self.lock(False) self.populateTable(self.path) # repopulate folder list bn, tt = os.path.basename(gn), time.perf_counter() - t0 self.setMessage('Encrypted, saved "{}"'.format(bn, 13)) self.extraLabel.setText('Encrypting took ' + self.secs_fmt(tt)) def encryptFile(self, key, fn): "encrypts a file using AES (MODE_GCM)" chars = ''.join(map(chr, range(256))).encode() chk = AES.block_size sample = random.sample iv = bytes(sample(chars, chk * 2)) salt = bytes(sample(chars * 2, 256)) vault = AES.new(self.hashKey(key, salt), AES.MODE_GCM, iv) fsz = os.path.getsize(fn) del key blksize = self.blksize gn = fn + self.ext fne = os.path.basename(fn).encode() fnz = len(fne) if len(fne) % chk: fne += bytes(sample(chars, chk - len(fne) % chk)) csz = 0.0 # current processed value self.encryptPbar.reset() prog, title = '({:.02%}) {}', self.windowTitle() self.showCancelButton(True) with open(fn, 'rb') as src, open(gn, 'wb') as dst: dst.write(bytes([0] * 16)) # spacer for MAC written at end dst.write(iv) dst.write(salt) # store iv, salt # is it safe to store MAC, iv, salt plain right in file? # can't really store them encrypted, # or elsewhere in this model of single file encryption? # can't have another file for the file to lug around # store file size, file name length dst.write(vault.encrypt(struct.pack('<2Q', fsz, fnz))) dst.write(vault.encrypt(fne)) # store filename while 1: dat = src.read(blksize) if not dat: break elif len(dat) % chk: # add padding fil = chk - len(dat) % chk dat += bytes(sample(chars, fil)) dst.write(vault.encrypt(dat)) csz += blksize # show progress self.encryptPbar.setValue(int(round(csz * 100.0 / fsz))) self.setWindowTitle(prog.format(csz / fsz, title)) app.processEvents() if self._requestStop: break if not self._requestStop: stuf = random.randrange(23) # pack in more stuffing fing = b''.join(bytes(sample(chars, 16)) for i in range(stuf)) dst.write(vault.encrypt(fing)) # and for annoyance dst.seek(0) dst.write(vault.digest()) # write MAC self.hashLabel.setText('MAC: ' + vault.hexdigest()) self.encryptPbar.setValue(self.encryptPbar.maximum()) self.setWindowTitle(title) self.showCancelButton(False) if self._requestStop: self.setMessage('Encryption canceled!') self.encryptPbar.setValue(self.encryptPbar.minimum()) self._requestStop = False os.remove(gn) return return gn def decrypt(self): "encrypt selected file with key" name, t0 = self.getName(), time.perf_counter() if not name: self.setMessage('No file selected') return if not os.path.exists(os.path.join(self.path, name)): self.setMessage('File does not exist') return key = str(self.keyInput.text()) if len(key) < self.minKeyLen: self.setMessage(('Key must be at least ' '{} characters long').format(self.minKeyLen)) return self.lock() gn = self.decryptFile(key, os.path.join(self.path, name)) if not gn: self.lock(False) return self.decrypted.append(os.path.basename(gn)) self.lock(False) self.populateTable(self.path) # repopulate folder list bn, tt = os.path.basename(gn), time.perf_counter() - t0 self.setMessage('Decrypted, saved "{}"'.format(bn, 13)) self.extraLabel.setText('Decrypting took ' + self.secs_fmt(tt)) def decryptFile(self, key, fn): "decrypts a file using AES (MODE_GCM)" blksize = self.blksize gn = hashlib.md5(os.path.basename(fn).encode()).hexdigest() gn = os.path.join(self.path, gn) # temporary name if os.path.exists(gn): self.setMessage('file already exists') return self.decryptPbar.reset() csz = 0.0 # current processed value chk, fnsz = AES.block_size, os.path.getsize(fn) prog, title = '({:.02%}) {}', self.windowTitle() try: with open(fn, 'rb') as src, open(gn, 'wb') as dst: # extract iv, salt MAC = src.read(16) iv = src.read(AES.block_size * 2) salt = src.read(256) vault = AES.new(self.hashKey(key, salt), AES.MODE_GCM, iv) self.showCancelButton(True) # extract file size, file name length sizes = src.read(struct.calcsize('<2Q')) fsz, fnz = struct.unpack('<2Q', vault.decrypt(sizes)) # extract filename; round up fnz to nearest chk rnz = fnz if not fnz % chk else fnz + chk - fnz % chk rfn = vault.decrypt(src.read(rnz))[:fnz].decode() self.setMessage('Found "{}"'.format(rfn), 13, (255, 211, 127)) while 1: dat = src.read(blksize) if not dat: break dst.write(vault.decrypt(dat)) csz += blksize # show progress self.decryptPbar.setValue(int(round(csz * 100.0 / fnsz))) self.setWindowTitle(prog.format(1 - (csz / fnsz), title)) app.processEvents() if self._requestStop: break if not self._requestStop: dst.truncate(fsz) # remove padding if not self._requestStop: vault.verify(MAC) self.hashLabel.setText('') except (ValueError, KeyError) as err: os.remove(gn) self.setMessage('Invalid decryption!') self.setWindowTitle(title) self.showCancelButton(False) return except Exception as err: os.remove(gn) self.setMessage('Invalid key or file!') self.setWindowTitle(title) self.showCancelButton(False) return self.decryptPbar.setValue(self.decryptPbar.maximum()) self.setWindowTitle(title) self.showCancelButton(False) if self._requestStop: self.setMessage('Decryption canceled!') self.decryptPbar.setValue(self.decryptPbar.minimum()) self._requestStop = False os.remove(gn) return # restore original file name name, ext = os.path.splitext(rfn) count = 1 fn = os.path.join(self.path, name + ext) while os.path.exists(fn): fn = os.path.join(self.path, name + '_{}'.format(count) + ext) count += 1 os.rename(gn, fn) # restore original name return fn # saved name def copyKeyHash(self, action): "copies either the key or the hash to clipboard" act = str(action.text()).lower() if 'key' in act: txt = str(self.keyInput.text()) elif 'hash' in act: txt = str(self.hashLabel.text()) else: self.setMessage('Invalid copy selection') return if not txt: self.setMessage('Empty text; Nothing to copy') return if 'key' in act: self.setMessage('Key copied to clipboard') elif 'hash' in act: self.setMessage('Hash copied to clipboard') else: self.setMessage('Invalid copy selection') return self.clipboard.clear() self.clipboard.setText(txt) def secs_fmt(self, s): "6357 -> '1h 45m 57s'" Y, D, H, M = 31556952, 86400, 3600, 60 y = int(s // Y) s -= y * Y d = int(s // D) s -= d * D h = int(s // H) s -= h * H m = int(s // M) s -= m * M r = (str(int(s)) if int(s) == s else str(round(s, 3))) + 's' if m: r = str(m) + 'm ' + r if h: r = str(h) + 'h ' + r if d: r = str(d) + 'd ' + r if y: r = str(y) + 'y ' + r return r.strip() def closeEvent(self, event): self.clipboard.clear() def setup(self): "constructs the gui" Fixed = QSizePolicy() MinimumExpanding = QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.minKeyLen = 8 self.maxKeyLen = 4096 self.splitter = QSplitter(self) self.splitter.setOrientation(Qt.Horizontal) self.splitter.splitterMoved.connect(self.splitterChanged) # left column self.leftColumn = QWidget() self.vl01 = QVBoxLayout() # left column - first item (0; horizonal layout 0) self.hl00 = QHBoxLayout() self.hl00.setSpacing(5) self.openButton = QPushButton('&Open') self.openButton.setToolTip('Open folder') self.openButton.setMinimumSize(60, 20) self.openButton.setMaximumSize(60, 20) self.openButton.setSizePolicy(Fixed) self.openButton.clicked.connect(self.getFolder) #ico = self.style().standardIcon(QStyle.SP_DirIcon) #self.openButton.setIcon(ico) self.folderLabel = QLabel() self.folderLabel.setMinimumSize(135, 20) self.folderLabel.setMaximumSize(16777215, 20) self.folderLabel.setSizePolicy(MinimumExpanding) self.hl00.insertWidget(0, self.openButton) self.hl00.insertWidget(1, self.folderLabel) # left column - second item (1) self.folderTable = QTableWidget() self.folderTable.setMinimumSize(200, 32) self.folderTable.horizontalHeader().setVisible(False) self.folderTable.horizontalHeader().setStretchLastSection(True) self.folderTable.verticalHeader().setVisible(False) self.folderTable.verticalHeader().setDefaultSectionSize(15) self.folderTable.itemChanged.connect(self.editFileName) # left column - third item (2) self.extraLabel = QLabel() self.extraLabel.setMinimumSize(200, 20) self.extraLabel.setMaximumSize(16777215, 20) self.extraLabel.setSizePolicy(MinimumExpanding) self.extraLabel.setTextInteractionFlags(Qt.LinksAccessibleByMouse) # finalize left column self.vl01.insertLayout(0, self.hl00) self.vl01.insertWidget(1, self.folderTable) self.vl01.insertWidget(2, self.extraLabel) self.leftColumn.setLayout(self.vl01) # right column self.rightColumn = QWidget() self.vl02 = QVBoxLayout() # right column - first item (0) self.messageLabel = QLabel() self.messageLabel.setMinimumSize(290, 20) self.messageLabel.setMaximumSize(16777215, 20) self.messageLabel.setSizePolicy(MinimumExpanding) self.messageLabel.setAlignment(Qt.AlignCenter) # right column - second item (2; horizontal layout 1) self.hl01 = QHBoxLayout() self.hl01.setSpacing(5) self.encryptButton = QPushButton('&Encrypt') #\U0001F512 self.encryptButton.setToolTip('Encrypt selected file') self.encryptButton.setMinimumSize(60, 20) self.encryptButton.setMaximumSize(60, 20) self.encryptButton.setSizePolicy(Fixed) self.encryptButton.clicked.connect(self.encrypt) self.encryptPbar = QProgressBar() self.encryptPbar.setMinimumSize(225, 20) self.encryptPbar.setMaximumSize(16777215, 20) self.encryptPbar.setSizePolicy(MinimumExpanding) self.encryptPbar.setTextVisible(False) palette = self.encryptPbar.palette() # color of progress bar color = QColor(211, 70, 0) palette.setColor(QPalette.Highlight, color) self.encryptPbar.setPalette(palette) self.hl01.insertWidget(0, self.encryptButton) self.hl01.insertWidget(1, self.encryptPbar) # right column - third item (3; horizontal layout 2) self.hl02 = QHBoxLayout() self.hl02.setSpacing(5) self.cancelButton = QPushButton('C&ANCEL') self.cancelButton.setToolTip('Cancels current operation') self.cancelButton.setMinimumSize(70, 24) self.cancelButton.setMaximumSize(70, 24) self.cancelButton.setSizePolicy(Fixed) self.cancelButton.clicked.connect(self.setCancel) font = self.cancelButton.font() font.setBold(True) self.cancelButton.setFont(font) self.cancelButton.blockSignals(True) self.cancelButton.setEnabled(False) self.cancelButton.hide() self._requestStop = False self.keyInput = QLineEdit() self.keyInput.setMinimumSize(225, 20) self.keyInput.setMaximumSize(16777215, 20) self.keyInput.setSizePolicy(MinimumExpanding) self.keyInput.setPlaceholderText('key') self.keyInput.setMaxLength(self.maxKeyLen) self.keyInput.setAlignment(Qt.AlignCenter) self.keyInput.textEdited.connect(self.showKeyLen) self.genKeyButton = QPushButton('&Gen Key') #\U0001F511 self.genKeyButton.setToolTip('Generate a random key') self.genKeyButton.setMinimumSize(60, 20) self.genKeyButton.setMaximumSize(60, 20) self.genKeyButton.setSizePolicy(Fixed) self.genKeyButton.clicked.connect(self.genKey) self.keySizeSB = QSpinBox() self.keySizeSB.setToolTip('Length of key to generate') self.keySizeSB.setRange(32, 1024) self.keySizeSB.setMinimumSize(40, 20) self.keySizeSB.setMaximumSize(40, 20) self.keySizeSB.setSizePolicy(Fixed) self.keySizeSB.setAlignment(Qt.AlignCenter) self.keySizeSB.setButtonSymbols(QSpinBox.NoButtons) self.keySizeSB.setWrapping(True) self.hl02.insertWidget(0, self.cancelButton) self.hl02.insertWidget(1, self.keyInput) self.hl02.insertWidget(2, self.genKeyButton) self.hl02.insertWidget(3, self.keySizeSB) # right column - fourth item (4; horizontal layout 3) self.hl03 = QHBoxLayout() self.hl03.setSpacing(5) self.decryptButton = QPushButton('&Decrypt') #\U0001F513 self.decryptButton.setToolTip('Decrypt selected file') self.decryptButton.setMinimumSize(60, 20) self.decryptButton.setMaximumSize(60, 20) self.decryptButton.setSizePolicy(Fixed) self.decryptButton.clicked.connect(self.decrypt) self.decryptPbar = QProgressBar() self.decryptPbar.setMinimumSize(225, 20) self.decryptPbar.setMaximumSize(16777215, 20) self.decryptPbar.setSizePolicy(MinimumExpanding) self.decryptPbar.setTextVisible(False) self.decryptPbar.setInvertedAppearance(True) palette = self.decryptPbar.palette() # color of progress bar color = QColor(0, 170, 255) palette.setColor(QPalette.Highlight, color) self.decryptPbar.setPalette(palette) self.hl03.insertWidget(0, self.decryptButton) self.hl03.insertWidget(1, self.decryptPbar) # right column - fifth item (7; horizontal layout 4) self.hl04 = QHBoxLayout() self.hl04.setSpacing(5) self.showKeyCB = QCheckBox('&Show Key') self.showKeyCB.setToolTip('Show/Hide key value') self.showKeyCB.setMinimumSize(75, 20) self.showKeyCB.setMaximumSize(75, 20) self.showKeyCB.setSizePolicy(Fixed) self.showKeyCB.clicked.connect(self.showKey) self.showKeyCB.setChecked(True) self.hashPbar = QProgressBar() self.hashPbar.setMinimumSize(150, 20) self.hashPbar.setMaximumSize(16777215, 20) self.hashPbar.setSizePolicy(MinimumExpanding) self.hashPbar.setTextVisible(False) palette = self.hashPbar.palette() # color of progress bar color = QColor(31, 120, 73) palette.setColor(QPalette.Highlight, color) self.hashPbar.setPalette(palette) self.hashButton = QPushButton('&Hash') self.hashButton.setToolTip('Determine file hash') self.hashButton.setMinimumSize(60, 20) self.hashButton.setMaximumSize(60, 20) self.hashButton.setSizePolicy(Fixed) menu = QMenu(self.hashButton) ico = self.style().standardIcon(QStyle.SP_DialogYesButton) for alg in sorted( filter(lambda x: 'shake' not in x, hashlib.algorithms_guaranteed), key=lambda n: (len(n), sorted(hashlib.algorithms_guaranteed).index(n))): menu.addAction( ico, alg ) # drop shake algs as their .hexdigest requires an argument - the rest don't menu.addAction(ico, 'Party') for i in menu.actions(): i.setIconVisibleInMenu(False) self.hashButton.setMenu(menu) menu.triggered.connect(self.genHash) self.hl04.insertWidget(0, self.showKeyCB) self.hl04.insertWidget(1, self.hashPbar) self.hl04.insertWidget(2, self.hashButton) # right column - sixth item (8; horizontal layout 5) self.hl05 = QHBoxLayout() self.hl05.setSpacing(5) self.copyButton = QPushButton('&Copy') #\U0001F4CB self.copyButton.setToolTip('Copy key or hash to clipboard') self.copyButton.setMinimumSize(60, 20) self.copyButton.setMaximumSize(60, 20) self.copyButton.setSizePolicy(Fixed) menu2 = QMenu(self.copyButton) menu2.addAction('Copy Key') menu2.addAction('Copy Hash') self.copyButton.setMenu(menu2) menu2.triggered.connect(self.copyKeyHash) self.hashLabel = QLabel() self.hashLabel.setMinimumSize(225, 20) self.hashLabel.setMaximumSize(16777215, 20) self.hashLabel.setSizePolicy(MinimumExpanding) self.hashLabel.setTextFormat(Qt.PlainText) self.hashLabel.setAlignment(Qt.AlignCenter) self.hashLabel.setTextInteractionFlags(Qt.TextSelectableByMouse) self.hl05.insertWidget(0, self.copyButton) self.hl05.insertWidget(1, self.hashLabel) # finalize right column self.vl02.insertWidget(0, self.messageLabel) self.vl02.insertSpacerItem(1, QSpacerItem(0, 0)) self.vl02.insertLayout(2, self.hl01) self.vl02.insertLayout(3, self.hl02) self.vl02.insertLayout(4, self.hl03) self.vl02.insertSpacerItem(5, QSpacerItem(0, 0)) self.vl02.insertWidget(6, QFrame()) self.vl02.insertLayout(7, self.hl04) self.vl02.insertLayout(8, self.hl05) self.rightColumn.setLayout(self.vl02) # finalize main window self.splitter.insertWidget(0, self.leftColumn) self.splitter.insertWidget(1, self.rightColumn) layout = QHBoxLayout(self) layout.addWidget(self.splitter) self.setLayout(layout) self.setWindowTitle('Simple File Encryptor/Decryptor') self.resize(self.sizeHint())
def search_result_popup(self, query, search_results): if 'search' in self.tabs: self.tabs['search'].textbox.clear_text() if query is None or query is '': Log.instance().warning("Please enter a non-empty search query.") return if len(search_results) == 0: Log.instance().warning( "No search results found for search: \"{query}\"".format( query=query)) return if 'search' in self.tabs and self.tabs['search'].popup is None: self.tabs['search'].textbox.clear_text() # Load popup .ui file self.tabs['search'].popup = UIObject( self.load_ui_file(SEARCH_RESULTS_POPUP_UI)) self.tabs['search'].popup.parent.setAttribute(Qt.WA_DeleteOnClose) # Format title title = self.tabs['search'].popup.get_widget(QLabel, 'title') title.setText(title.text().format( query=query)) # already set to {query} in QtDesigner # Get button area button_area = self.tabs['search'].popup.get_widget( QVBoxLayout, 'button_area') for i in range(len(search_results)): # Create a button out of each search_result button = QPushButton( text=self.controller.get_track_name(search_results[i])) button_font = button.font() button_font.setPointSize(12) button.setFont(button_font) # Connect each button to downloading the song # NOTE: Partial used instead of lambda because they save the current value to excude the func (lambda would use the last i value cause its incremented) button.clicked.connect( partial(self.controller.download_track_by_id, search_results[i].id)) button.clicked.connect(partial(button.setEnabled, False)) button_area.addWidget(button) # Handle closing the dialog self.tabs['search'].popup.parent.destroyed.connect( self.reset_search_dialog) # Show popup self.tabs['search'].popup.parent.show() else: if 'search' not in self.tabs: Log.instance().warning( "Cannot display search results dialog when search module is not enabled!" ) elif self.tabs['search'].popup is not None: Log.instance().warning( "Search results dialog already displayed. Please close the previous dialog before searching again." )
class Window(QWidget): def __init__(self, app, parent=None): print("Window init") super().__init__(parent) # self.win_event_filter = WinEventFilter("window") # self.installNativeEventFilter(self.win_event_filter) self.app = app self.window_size = QtCore.QSize(400, 250) self.window_size_offset = QtCore.QSize(0, 150) self.window_position = QtCore.QPoint(0, 0) self.window_position_offset = QtCore.QPoint(0, 0) # self.setWindowFlags( # QtCore.Qt.Window | # QtCore.Qt.CustomizeWindowHint | # QtCore.Qt.WindowTitleHint | # QtCore.Qt.WindowCloseButtonHint | # QtCore.Qt.WindowStaysOnTopHint # ) self.setWindowFlags(self.windowFlags() | QtCore.Qt.FramelessWindowHint) self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint) self.setWindowFlags( QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.Tool) # hlayout = QHBoxLayout() # hlayout.setMargin(0) # hlayout.setContentsMargins(0, 0, 0, 0) # hlayout.setSpacing(0) # buttonslayout = QVBoxLayout() self.labels = [] self.menuButton = QPushButton(u"\U00002261") self.menuLabel = QLabel("Menu") myFontBold = self.menuLabel.font() myFontBold.setBold(True) # buttons myFont = self.menuButton.font() myFont2 = self.menuButton.font() if (myFont.pointSize() > 0): myFont.setPointSizeF(1.25 * myFont.pointSizeF()) myFont2.setPointSizeF(1.4 * myFont.pointSizeF()) else: myFont.setPixelSize(1.25 * myFont.pixelSize()) myFont2.setPixelSize(1.4 * myFont.pixelSize()) self.menuLabel.setFont(myFontBold) width = self.menuButton.fontMetrics().boundingRect("OO").width() + 7 height = width # okButton.height() self.menuButton.setFont(myFont2) self.menuButton.setMaximumWidth(width) self.menuButton.setMinimumWidth(width) self.menuButton.setFlat(True) self.menuButton.clicked.connect(self.menuPressed) mainButton = QPushButton(u"\U0000239A") mainLabel = QLabel("Main") width = mainButton.fontMetrics().boundingRect("OO").width() + 7 height = width # okButton.height() mainButton.setFont(myFont2) mainButton.setMaximumWidth(width) mainButton.setMinimumWidth(width) mainButton.clicked.connect(self.main) mainButton.setFlat(True) setupButton = QPushButton(u"\U0001F527") setupLabel = QLabel("Setup") setupButton.setFont(myFont) setupButton.setFlat(True) setupButton.setMaximumWidth(width) setupButton.setMinimumWidth(width) setupButton.clicked.connect(self.setup) identifyButton = QPushButton(u"\U00002755") identifyLabel = QLabel("Identify") identifyButton.setFont(myFont) identifyButton.setFlat(True) identifyButton.setMaximumWidth(width) identifyButton.setMinimumWidth(width) identifyButton.clicked.connect(self.identify) self.refreshButton = QPushButton(u"\U000021BB") self.refreshLabel = QLabel("Detect") self.refreshButton.setFont(myFont) self.refreshButton.setFlat(True) self.refreshButton.setMaximumWidth(width) self.refreshButton.setMinimumWidth(width) self.refreshButton.clicked.connect(self.refreshPressed) aboutButton = QPushButton(u"\U00002754") aboutLabel = QLabel("About") aboutButton.setFont(myFont) aboutButton.setFlat(True) aboutButton.setMaximumWidth(width) aboutButton.setMinimumWidth(width) aboutButton.clicked.connect(self.about) # closeButton = QPushButton(u"\U00002573") closeButton = QPushButton(u"\U000026CC") closeLabel = QLabel("Close") closeButton.setFont(myFont) closeButton.setFlat(True) closeButton.setMaximumWidth(width) closeButton.setMinimumWidth(width) closeButton.clicked.connect(self.close_) buttongrid = QGridLayout() buttongrid.addWidget(self.menuButton, 0, 0) buttongrid.addWidget(mainButton, 1, 0) buttongrid.addWidget(setupButton, 2, 0) buttongrid.addWidget(self.refreshButton, 3, 0) buttongrid.addWidget(identifyButton, 4, 0) buttongrid.addWidget(aboutButton, 6, 0) buttongrid.addWidget(closeButton, 7, 0) buttongrid.addWidget(self.menuLabel, 0, 1) buttongrid.addWidget(mainLabel, 1, 1) buttongrid.addWidget(setupLabel, 2, 1) buttongrid.addWidget(self.refreshLabel, 3, 1) buttongrid.addWidget(identifyLabel, 4, 1) buttongrid.addWidget(aboutLabel, 6, 1) buttongrid.addWidget(closeLabel, 7, 1) self.labels.append(self.menuLabel) self.labels.append(mainLabel) self.labels.append(setupLabel) self.labels.append(self.refreshLabel) self.labels.append(identifyLabel) self.labels.append(aboutLabel) self.labels.append(closeLabel) self.menuLabel .mousePressEvent = self.menuLabelPressed mainLabel .mousePressEvent = self.mainLabel setupLabel.mousePressEvent = self.setupLabel self.refreshLabel.mousePressEvent = self.refreshLabelPressed identifyLabel.mousePressEvent = self.identifyLabel aboutLabel.mousePressEvent = self.aboutLabel closeLabel.mousePressEvent = self.closeLabel buttongrid.setRowStretch(0, 0) buttongrid.setRowStretch(1, 0) buttongrid.setRowStretch(2, 0) buttongrid.setRowStretch(3, 0) buttongrid.setRowStretch(4, 0) buttongrid.setRowStretch(5, 1) buttongrid.setRowStretch(6, 0) buttongrid.setRowStretch(7, 0) self.labels_set_visible(False) self.layout = QHBoxLayout() # buttonslayout.addWidget(mainButton) # buttonslayout.addWidget(setupButton) # buttonslayout.addStretch(1) # buttonslayout.addWidget(aboutButton) # hlayout.addLayout(buttonslayout) # hlayout.addLayout(buttongrid) # grid.addLayout(hlayout, 1, 1) buttongrid.setSpacing(0) self.layout.addLayout(buttongrid) self.body_layout = QVBoxLayout() self.body_layout.setContentsMargins(0, 0, 0, 1) self.body_layout.setSpacing(0) self.title_layout = QHBoxLayout() self.title_layout.setContentsMargins(0, 0, 0, 0) self.title_layout.setSpacing(0) self.titleLabel = QLabel("Monitor Control") self.titleLabel.setWordWrap(True) self.titleLabel.setSizeIncrement(10, 10) myFont = self.titleLabel.font() myFont.setBold(True) self.titleLabel.setFont(myFont) width = self.titleLabel.fontMetrics().boundingRect("OO").width() + 7 height = width # okButton.height() self.titleLabel.mousePressEvent = self.mainLabel self.backButton = QPushButton(u"\U00002190", self) myFont = self.backButton.font() myFont.setBold(True) self.backButton.setFont(myFont) self.backButton.setMaximumWidth(width) self.backButton.setMinimumWidth(width) self.backButton.setFlat(True) self.backButton.clicked.connect(self.main) self.titleLabel.setMinimumHeight(self.backButton.height()) self.title_layout.addWidget(self.backButton, 0, QtCore.Qt.AlignVCenter) self.title_layout.addSpacing(20) self.title_layout.addWidget(self.titleLabel, 1, QtCore.Qt.AlignVCenter) # self.backButton.setAlignment(Qt.AlignTop) self.title_layout.setAlignment(QtCore.Qt.AlignTop) self.body_layout.addLayout(self.title_layout) self.main_frame = QtWidgets.QFrame(self) self.main_layout = QVBoxLayout() self.feature_brightness = FeatureWidget( self.main_frame, "Brightness", self.app.brightness) self.feature_contrast = FeatureWidget( self.main_frame, "Contrast", self.app.contrast) self.main_layout.addWidget(self.feature_brightness) self.main_layout.addWidget(self.feature_contrast) self.main_layout.addStretch(1) self.main_frame.setLayout(self.main_layout) self.main_frame.hide() self.body_layout.addWidget(self.main_frame, 1) self.setup_frame = QtWidgets.QFrame(self) leftButton = QPushButton("<", self.setup_frame) width = leftButton.fontMetrics().boundingRect("<").width() + 7 leftButton.setFlat(True) leftButton.setMaximumWidth(width) leftButton.setMinimumWidth(width) leftButton.setSizePolicy(QtWidgets.QSizePolicy( QSizePolicy.Fixed, QSizePolicy.Expanding)) self.setup_layout = QHBoxLayout() self.setup_layout.addWidget(leftButton) self.feature_setup_widget = FeatureSetupWidget( self.app, self.setup_frame) # hlayout.addWidget(self.feature_setup_widget, 1) self.feature_setup_widget.setSizePolicy( QSizePolicy.Expanding, QSizePolicy.Expanding) rightButton = QPushButton(">", self.setup_frame) rightButton.setFlat(True) rightButton.setMaximumWidth(width) rightButton.setMinimumWidth(width) rightButton.setSizePolicy(QtWidgets.QSizePolicy( QSizePolicy.Fixed, QSizePolicy.Expanding)) self.setup_layout.addWidget(self.feature_setup_widget, 1) self.setup_layout.addWidget(rightButton) self.setup_layout.setContentsMargins(0, 0, 0, 0) self.setup_layout.setSpacing(0) leftButton.clicked.connect(self.feature_setup_widget.previous) rightButton.clicked.connect(self.feature_setup_widget.next) self.setup_frame.setLayout(self.setup_layout) # self.layout.setContentsMargins(0, 0, 0, 0) self.layout.setSpacing(10) self.body_layout.addWidget(self.setup_frame, 1) self.layout.addLayout(self.body_layout, 1) self.about_frame = QtWidgets.QFrame(self) self.about_layout = QVBoxLayout() self.aboutLabel1 = QLabel("About", self.about_frame) self.aboutLabel1.setWordWrap(True) myFont = self.aboutLabel1.font() myFont.setBold(True) self.aboutLabel1.setFont(myFont) about = "©️ ™️ Juno\n\nMonitor Control synchronizes your monitor hardware properties like brightness and contrast.\nThese properties can be changed by the software sliders, or monitor buttons. These changes are monitored and read, and subsequently set to the other monitors using a calibration. This will ensure an input change has the same result on all monitors.\n" self.aboutLabel2 = QLabel("{}".format(about), self.about_frame) self.aboutLabel2.setAlignment( QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop) self.aboutLabel2.setWordWrap(True) self.about_layout.addWidget(self.aboutLabel1) self.about_layout.addWidget(self.aboutLabel2, 1) self.about_frame.setLayout(self.about_layout) self.about_frame.hide() self.body_layout.addWidget(self.about_frame, 1) # self.layout.setSizeConstraint(QtGui.QLayout.setFixedSize) self.setLayout(self.layout) self.setWindowIcon(QtGui.QIcon('artifacts/icon.png')) # set the title self.setWindowTitle("Monitors Control") self.main() self.setFixedSize(400, 250) def labels_set_visible(self, visible): for label in self.labels: if (self.refreshLabel == label) and visible: self.refreshLabel.setVisible(self.refreshButton.isVisible()) else: label.setVisible(visible) def refresh_visible(self, visible): if (visible): self.refreshButton.setVisible(visible) self.refreshLabel.setVisible(self.menuLabel.isVisible()) else: self.refreshLabel.setVisible(visible) self.refreshButton.setVisible(visible) def focusOutEvent(self, event): print('Lost focus') def menuLabelPressed(self, event): self.menuPressed() def menuPressed(self): print("Menu") self.labels_set_visible(not self.labels[0].isVisible()) def aboutLabel(self, event): self.about() def about(self): print("About") self.setupUpdate() self.setMinimumSize(200, 130) # self.feature_setup_widget.hide() self.setup_frame.hide() self.main_frame.hide() self.refresh_visible(False) self.backButton.show() self.about_frame.show() self.move(self.window_position) self.setFixedSize(self.window_size) def closeLabel(self, event): self.close_() def close_(self): print("Close {}".format(len(self.app.identifyWindows))) self.setupUpdate() if (len(self.app.identifyWindows) == 0): self.hide() def setupLabel(self, event): self.setup() def setup(self): print("Setup") self.move(self.window_position + self.window_position_offset) self.setFixedSize(self.window_size + self.window_size_offset) self.app.monitors._calibrations.loadYaml() self.feature_setup_widget.init() self.backButton.show() self.main_frame.hide() self.about_frame.hide() self.refresh_visible(True) self.setup_frame.show() self.setMinimumSize(200, 130) def setupUpdate(self): if (self.setup_frame.isVisible()): self.app.monitors._calibrations.saveYaml() def mainLabel(self, event): self.main() def main(self): print("Main") self.setMinimumSize(200, 130) self.setupUpdate() self.refresh_visible(False) self.backButton.hide() # self.feature_setup_widget.hide() self.setup_frame.hide() self.about_frame.hide() self.main_frame.hide() self.move(self.window_position) self.setFixedSize(self.window_size) self.main_frame.show() def identifyLabel(self, event): self.identify() def identify(self): print("Identify") self.app.identify() def refreshLabelPressed(self, event): self.refreshPressed() def refreshPressed(self): QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) print("detect") self.feature_setup_widget.clear() self.app.detect() self.setup() self.feature_setup_widget.set_infos(self.app.monitors) self.feature_setup_widget.init() self.app.list_monitors() QApplication.restoreOverrideCursor() def position_show(self): print("position_show") self.app.position_next_to_tray() self.main() self.show() # self.requestActivate() # QtCore.Qt.ActiveWindowFocusReason self.activateWindow() self.setFocus(QtCore.Qt.PopupFocusReason) def contrast(self, value): # from gui self.app.contrast(value) def brightness(self, value): # from gui self.app.brightness(value) def set_contrast(self, value): # to gui self.feature_contrast.set_value(value) self.feature_setup_widget.set_contrast(value) def set_brightness(self, value): # to gui self.feature_brightness.set_value(value) self.feature_setup_widget.set_brightness(value) def show(self): # to gui value = self.app.monitors.get_contrast() if (value is not None): self.set_contrast(value) value = self.app.monitors.get_brightness() if (value is not None): self.set_brightness(value) self.feature_setup_widget.set_infos(self.app.monitors) super().show()