def downloadFile(self, url, archivo_destino): url = QUrl(url) fileName = archivo_destino directorio_usuario_para_pilas = os.path.dirname(archivo_destino) if not os.path.exists(directorio_usuario_para_pilas): os.mkdir(directorio_usuario_para_pilas) if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information(self, 'Error', 'Lo siento, no se puede descargar el archivo desde %s: %s.' % (self.url, self.outFile.errorString())) self.outFile = None return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '/' self.httpGetId = self.http.get(path, self.outFile)
def downloadFile(self, url_to_download, fout): " get the file from remote url to local folder " url = QUrl(url_to_download) fileInfo = QFileInfo(url.path()) fileName = path.join(fout, str(fileInfo.fileName())) if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information( self, "ERROR", "Cant save the file %s: %s." % (fileName, self.outFile.errorString()) ) self.outFile = None return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False tpath = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if tpath: tpath = str(tpath) else: tpath = sep # Download the file. print(" INFO: Blender Download Started ! ") self.httpGetId = self.http.get(tpath, self.outFile)
def downloadFile(self, url_to_download, download_location): url = QUrl(url_to_download) fileInfo = QFileInfo(url.path()) #fileName = fileInfo.fileName() fileName = download_location + fileInfo.fileName() self.file_name = fileName print("Filename = " + fileName) if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information(self, 'Error', 'Unable to save the file %s: %s.' % (fileName, self.outFile.errorString())) self.outFile = None return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '/' # Download the file. self.httpGetId = self.http.get(path, self.outFile) return fileName
def downloadFile(self): url = QUrl(self.url_to_download) fileName = QFileDialog.getSaveFileName(self, "Enregistrer la liste des dossiers", self.nameFile, "conf") if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information(self, 'Erreur','Impossible d\'enregistrer le fichier %s: %s.' % (fileName, self.outFile.errorString())) self.outFile = None return #Création que la connexion HTTPS mode = QHttp.ConnectionModeHttps port = 0 self.http.setHost(url.host(), mode, port) self.requeteHTTPannule = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '/' #Concaténation des paramètres à l'URL path = path+("?") for item in url.queryItems(): path = path + item[0] + "=" + item[1] + "&" self.http.setUser(self.login, self.password) self.httpGetId = self.http.get(path, self.outFile)
def queryProxy(self, query): """ Public method to determine a proxy for a given query. @param query reference to the query object (QNetworkProxyQuery) @return list of proxies in order of preference (list of QNetworkProxy) """ if query.queryType() == QNetworkProxyQuery.UrlRequest and \ query.protocolTag() in ["http", "https", "ftp"] and \ Preferences.getUI("UseProxy"): if Preferences.getUI("UseSystemProxy"): proxyList = QNetworkProxyFactory.systemProxyForQuery(query) if sys.platform not in ["darwin", "nt"] and \ len(proxyList) == 1 and \ proxyList[0].type() == QNetworkProxy.NoProxy: # try it the Python way # scan the environment for variables named <scheme>_proxy # scan over whole environment to make this case insensitive for name, value in os.environ.items(): name = name.lower() if value and name[-6:] == '_proxy' and \ name[:-6] == query.protocolTag().toLower(): url = QUrl(value) if url.scheme() in ["http", "https"]: proxyType = QNetworkProxy.HttpProxy else: proxyType = QNetworkProxy.FtpCachingProxy proxy = QNetworkProxy(proxyType, url.host(), url.port(), url.userName(), url.password()) proxyList = [proxy] break if proxyList: proxyList[0].setUser(Preferences.getUI("ProxyUser")) proxyList[0].setPassword(Preferences.getUI("ProxyPassword")) return proxyList else: return [QNetworkProxy(QNetworkProxy.NoProxy)] else: host = Preferences.getUI("ProxyHost") if not host: QMessageBox.critical(None, self.trUtf8("Proxy Configuration Error"), self.trUtf8("""Proxy usage was activated""" """ but no proxy host configured.""")) return [QNetworkProxy(QNetworkProxy.DefaultProxy)] else: pProxyType = Preferences.getUI("ProxyType") if pProxyType == 0: proxyType = QNetworkProxy.HttpProxy elif pProxyType == 1: proxyType = QNetworkProxy.HttpCachingProxy elif pProxyType == 2: proxyType = QNetworkProxy.Socks5Proxy proxy = QNetworkProxy(proxyType, host, Preferences.getUI("ProxyPort"), Preferences.getUI("ProxyUser"), Preferences.getUI("ProxyPassword")) return [proxy, QNetworkProxy(QNetworkProxy.DefaultProxy)] else: return [QNetworkProxy(QNetworkProxy.NoProxy)]
class DownloadFtp(Download): def __init__(self, file_share, local_path, date): Download.__init__(self, file_share, local_path, date) self.ftp = QFtp(self) self.ftp.dataTransferProgress.connect(self.update_progress) self.ftp.done.connect(self.download_finished) self.ftp.stateChanged.connect(self.state_changed) self.url = QUrl(self._file_share.url) self.out_file = QFile(self.local_path) self.read_bytes = self.out_file.size() def start_download(self): self.ftp.connectToHost(self.url.host(), self.url.port(21)) self.ftp.login() if self.out_file.open(QIODevice.WriteOnly): self.ftp.get(self.url.path(), self.out_file) def stop(self): self.ftp def state_changed(self, state): if state == 1 or state == 2: self._state = 1 def download_finished(self, _): print "finished !" def update_progress(self, read_bytes, total_bytes): self.read_bytes = read_bytes
def downloadFile(self): url = QUrl(self.downloadUrl) fileInfo = QFileInfo(url.path()) #fileName = fileInfo.fileName() fileName = self.targetDirectory + fileInfo.fileName() if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information(self, 'Error', 'Unable to save the file %s: %s.' % (fileName, self.outFile.errorString())) self.outFile = None return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False print url path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '/' # Right at the end we append the query string that is lost, the original author did not include this unfortunately. parsedUrl = urlparse(self.downloadUrl) if not parsedUrl.query == '': # fix this mess, otherwise leave it alone path = path + "?" + parsedUrl.query print path # Download the file. self.httpGetId = self.http.get(path, self.outFile)
def getObservationsUrl (self): try: url = QUrl(self.operationsMetadata['GetObservation'].methods['Post']) #Para servidores mal configurados if url.host() == 'localhost': url.setHost (self.url.host()) url.setPort (self.url.port()) return url return url except: return QUrl()
def getObservationsUrl(self): try: url = QUrl( self.operationsMetadata['GetObservation'].methods['Post']) #Para servidores mal configurados if url.host() == 'localhost': url.setHost(self.url.host()) url.setPort(self.url.port()) return url return url except: return QUrl()
def set_proxy(proxy): proxy_url = QUrl(proxy) if unicode(proxy_url.scheme()).startswith('http'): protocol = QNetworkProxy.HttpProxy else: protocol = QNetworkProxy.Socks5Proxy QNetworkProxy.setApplicationProxy( QNetworkProxy( protocol, proxy_url.host(), proxy_url.port(), proxy_url.userName(), proxy_url.password()))
class CoverArtImage: support_types = False # consider all images as front if types aren't supported by provider is_front = True def __init__(self, url=None, types=[u'front'], comment=''): if url is not None: self.parse_url(url) else: self.url = None self.types = types self.comment = comment def parse_url(self, url): self.url = QUrl(url) self.host = str(self.url.host()) self.port = self.url.port(80) self.path = str(self.url.encodedPath()) if self.url.hasQuery(): self.path += '?' + str(self.url.encodedQuery()) def is_front_image(self): # CAA has a flag for "front" image, use it in priority if self.is_front: return True # no caa front flag, use type instead return u'front' in self.types def __repr__(self): p = [] if self.url is not None: p.append("url=%r" % self.url.toString()) p.append("types=%r" % self.types) if self.comment: p.append("comment=%r" % self.comment) return "%s(%s)" % (self.__class__.__name__, ", ".join(p)) def __unicode__(self): p = [u'Image'] if self.url is not None: p.append(u"from %s" % self.url.toString()) p.append(u"of type %s" % u','.join(self.types)) if self.comment: p.append(u"and comment '%s'" % self.comment) return u' '.join(p) def __str__(self): return unicode(self).encode('utf-8')
def cmis_base_url(): """ Constructs the base URL from the CMIS Atom service end point. :return: Returns the base URL of the CMIS server or an empty string if the URL cannot be constructed or if the CMIS service has not been defined. :rtype: str """ atom_pub_url = cmis_atom_pub_url() if not atom_pub_url: return '' url = QUrl(atom_pub_url) if not url.isValid(): return '' if url.port() == -1: port = '' else: port = ':{0}'.format(url.port()) return '{0}://{1}{2}'.format(url.scheme(), url.host(), port)
def downloadFile(self): url = QUrl(self.url_text.text()) if self.txt_location.text() == "": QDir.setCurrent("$HOME/Downloads") else: QDir.setCurrent(self.loc) self.statusbar.showMessage("Downloading") fileInfo = QFileInfo(url.path()) fileName = fileInfo.fileName() if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information( self, 'Error', 'Unable to save the file %s: %s.' % (fileName, self.outFile.errorString())) self.outFile = None return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '$HOME/Downloads' # Download the file. self.httpGetId = self.http.get(path, self.outFile)
def downloadFile(self): url = QUrl(self.url_text.text()) if self.txt_location.text()=="": QDir.setCurrent("$HOME/Downloads") else: QDir.setCurrent(self.loc) self.statusbar.showMessage("Downloading") fileInfo = QFileInfo(url.path()) fileName = fileInfo.fileName() if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information(self, 'Error', 'Unable to save the file %s: %s.' % (fileName, self.outFile.errorString())) self.outFile = None return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '$HOME/Downloads' # Download the file. self.httpGetId = self.http.get(path, self.outFile)
class CoverArtImage: # Indicate if types are provided by the source, ie. CAA or certain file # formats may have types associated with cover art, but some other sources # don't provide such information support_types = False # `is_front` has to be explicitly set, it is used to handle CAA is_front # indicator is_front = None sourceprefix = "URL" def __init__(self, url=None, types=[], comment='', data=None): if url is not None: self.parse_url(url) else: self.url = None self.types = types self.comment = comment self.datahash = None # thumbnail is used to link to another CoverArtImage, ie. for PDFs self.thumbnail = None self.can_be_saved_to_tags = True self.can_be_saved_to_disk = True self.can_be_saved_to_metadata = True if data is not None: self.set_data(data) def parse_url(self, url): self.url = QUrl(url) self.host = str(self.url.host()) self.port = self.url.port(80) self.path = str(self.url.encodedPath()) if self.url.hasQuery(): self.path += '?' + str(self.url.encodedQuery()) @property def source(self): if self.url is not None: return u"%s: %s" % (self.sourceprefix, self.url.toString()) else: return u"%s" % self.sourceprefix def is_front_image(self): """Indicates if image is considered as a 'front' image. It depends on few things: - if `is_front` was set, it is used over anything else - if `types` was set, search for 'front' in it - if `support_types` is False, default to True for any image - if `support_types` is True, default to False for any image """ if not self.can_be_saved_to_metadata: # ignore thumbnails return False if self.is_front is not None: return self.is_front if u'front' in self.types: return True return (self.support_types is False) def imageinfo_as_string(self): if self.datahash is None: return "" return "w=%d h=%d mime=%s ext=%s datalen=%d file=%s" % (self.width, self.height, self.mimetype, self.extension, self.datalength, self.tempfile_filename) def __repr__(self): p = [] if self.url is not None: p.append("url=%r" % self.url.toString()) if self.types: p.append("types=%r" % self.types) if self.is_front is not None: p.append("is_front=%r" % self.is_front) if self.comment: p.append("comment=%r" % self.comment) return "%s(%s)" % (self.__class__.__name__, ", ".join(p)) def __unicode__(self): p = [u'Image'] if self.url is not None: p.append(u"from %s" % self.url.toString()) if self.types: p.append(u"of type %s" % u','.join(self.types)) if self.comment: p.append(u"and comment '%s'" % self.comment) return u' '.join(p) def __str__(self): return unicode(self).encode('utf-8') def set_data(self, data): """Store image data in a file, if data already exists in such file it will be re-used and no file write occurs """ if self.datahash: self.datahash.delete_file() self.datahash = None try: (self.width, self.height, self.mimetype, self.extension, self.datalength) = imageinfo.identify(data) except imageinfo.IdentificationError as e: raise CoverArtImageIdentificationError(e) try: self.datahash = DataHash(data, suffix=self.extension) except (OSError, IOError) as e: raise CoverArtImageIOError(e) @property def maintype(self): """Returns one type only, even for images having more than one type set. This is mostly used when saving cover art to tags because most formats don't support multiple types for one image. Images coming from CAA can have multiple types (ie. 'front, booklet'). """ if self.is_front_image() or not self.types or u'front' in self.types: return u'front' # TODO: do something better than randomly using the first in the list return self.types[0] def _make_image_filename(self, filename, dirname, metadata): filename = ScriptParser().eval(filename, metadata) if config.setting["ascii_filenames"]: if isinstance(filename, unicode): filename = unaccent(filename) filename = replace_non_ascii(filename) if not filename: filename = "cover" if not os.path.isabs(filename): filename = os.path.join(dirname, filename) # replace incompatible characters if config.setting["windows_compatibility"] or sys.platform == "win32": filename = replace_win32_incompat(filename) # remove null characters filename = filename.replace("\x00", "") return encode_filename(filename) def save(self, dirname, metadata, counters): """Saves this image. :dirname: The name of the directory that contains the audio file :metadata: A metadata object :counters: A dictionary mapping filenames to the amount of how many images with that filename were already saved in `dirname`. """ if not self.can_be_saved_to_disk: return if (config.setting["caa_image_type_as_filename"] and not self.is_front_image()): filename = self.maintype log.debug("Make cover filename from types: %r -> %r", self.types, filename) else: filename = config.setting["cover_image_filename"] log.debug("Using default cover image filename %r", filename) filename = self._make_image_filename(filename, dirname, metadata) overwrite = config.setting["save_images_overwrite"] ext = self.extension image_filename = self._next_filename(filename, counters) while os.path.exists(image_filename + ext) and not overwrite: if not self._is_write_needed(image_filename + ext): break image_filename = self._next_filename(filename, counters) else: new_filename = image_filename + ext # Even if overwrite is enabled we don't need to write the same # image multiple times if not self._is_write_needed(new_filename): return log.debug("Saving cover image to %r", new_filename) try: new_dirname = os.path.dirname(new_filename) if not os.path.isdir(new_dirname): os.makedirs(new_dirname) shutil.copyfile(self.tempfile_filename, new_filename) except (OSError, IOError) as e: raise CoverArtImageIOError(e) def _next_filename(self, filename, counters): if counters[filename]: new_filename = "%s (%d)" % (filename, counters[filename]) else: new_filename = filename counters[filename] += 1 return new_filename def _is_write_needed(self, filename): if (os.path.exists(filename) and os.path.getsize(filename) == self.datalength): log.debug("Identical file size, not saving %r", filename) return False return True @property def data(self): """Reads the data from the temporary file created for this image. May raise CoverArtImageIOError """ try: return self.datahash.data except (OSError, IOError) as e: raise CoverArtImageIOError(e) @property def tempfile_filename(self): return self.datahash.filename def types_as_string(self, translate=True, separator=', '): if self.types: types = self.types elif self.is_front_image(): types = [u'front'] else: types = [u'-'] if translate: types = [translate_caa_type(type) for type in types] return separator.join(types)
class FTP_Handler( QFtp ): # ======================================================================= def __init__( self, parent=None ): # ------------------------------------------------------------------- QFtp.__init__( self, parent ); # ------------------------------------------------------------------- self.PARENT = parent; self.DEBUG = False; self.LOG_TAG = str(self.__class__.__name__).upper(); # ------------------------------------------------------------------- self.stateChanged.connect( self.ON_STATE_CHANGED ); self.listInfo.connect( self.ON_LIST_INFO_AVAILABLE ); self.commandFinished.connect( self.ON_COMMAND_FINISHED ); self.commandStarted.connect( self.ON_COMMAND_STARTED ); self.readyRead.connect( self.ON_READY_READ ); self.done.connect( self.ON_DONE ); self.dataTransferProgress.connect( self.ON_DATA_TRANSFER_PROGRESS ); self.rawCommandReply.connect( self.ON_RAW_COMMAND_REPLY ); # ------------------------------------------------------------------- self.HOST = ""; self.PATH = ""; self.USER = ""; self.PWD = ""; self.PORT = 21; # ------------------------------------------------------------------- self.FILE_INFO_LIST = []; self.LOGIN_SUCCESS = False; self.ALLOW_TO_RUN = True; self.LAST_ERROR = QFtp.NoError; self.NEW_URL = ""; self.SHOW_HIDDEN_FILES = False; self.SHOW_FILES_FIRST = False; self.PRINT_CONN_INFO = False; # ------------------------------------------------------------------- self.REQ_UIDS = { "connect" : 0, "login" : 0, "cd" : 0, "list" : 0, } # ------------------------------------------------------------------- self.PARENT.SPLASH.STATUS( self.LOG_TAG+": [INIT]" ); # ------------------------------------------------------------------- # ======================================================================= def MK_CONNECT( self, _url, _user="******", _pwd="", _port=21 ): # ------------------------------------------------------------------- try: req = urllib2.Request( _url, headers=self.PARENT.WEB_PAGE.HEADERS ); resp = urllib2.urlopen( req ); t = resp.headers["content-type"]; self.PARENT.DOWNLOAD_MANAGER.REQUEST( _url, False ); return; except Exception as _err: pass; # ------------------------------------------------------------------- try: # ----------------------------------------------------------- # Name, isFile, date, size, owner for _f_info in self.FILE_INFO_LIST: if _url.split("/")[-1] == _f_info[0] and _f_info[1]: self.PARENT.DOWNLOAD_MANAGER.REQUEST( "ftp://"+self.HOST+self.PATH+_f_info[0], False ); return; # ----------------------------------------------------------- self.FILE_INFO_LIST = []; self.Q_URL = QUrl( _url ); self.USER = str(_user); self.PWD = str(_pwd); self.PORT = int(_port); self.HOST = self.HOST if str(self.Q_URL.host()) == "" else str(self.Q_URL.host()); self.PATH = "/" if str(self.Q_URL.path()) == "" else str(self.Q_URL.path()); # ----------------------------------------------------------- if self.PRINT_CONN_INFO: print(" --------------------------------------------------------- " ); print("USER: ["+self.USER+"]" ); print("PWD: ["+self.PWD+"]" ); print("PORT: ["+str(self.PORT)+"]" ); print("HOST: ["+self.HOST+"]" ); print("PATH: ["+self.PATH+"]" ); print(" --------------------------------------------------------- " ); # ----------------------------------------------------------- self.CONNECT(); except Exception as _err: self.LOCAL_ERROR_LOG( "MK_CONNECT[1]: "+str(_err) ); # ------------------------------------------------------------------- # ======================================================================= def CONNECT( self ): # ------------------------------------------------------------------- try: self.REQ_UIDS["connect"] = self.connectToHost( self.HOST, self.PORT ); self.REQ_UIDS["login"] = self.login( self.USER, self.PWD ); except Exception as _err: self.LOCAL_ERROR_LOG( "CONNECT: "+str(_err) ); # ------------------------------------------------------------------- # ======================================================================= def ON_COMMAND_FINISHED( self, _response, _bool ): # ------------------------------------------------------------------- try: if _response == self.REQ_UIDS["connect"]: print("Connected.") elif _response == self.REQ_UIDS["login"]: if self.state() == QFtp.LoggedIn: print(" LoggedIn: 200"); self.LOGIN_SUCCESS = True; print(" cd: ["+self.PATH+"]"); self.REQ_UIDS["cd"] = self.cd( self.PATH ); else: print(" NOT-LoggedIn: 500"); elif _response == self.REQ_UIDS["cd"]: self.REQ_UIDS["list"] = self.list(); elif _response == self.REQ_UIDS["list"]: self.CREATE_TREE( self.PATH ); self.close(); except Exception as _err: self.LOCAL_ERROR_LOG( "ON_COMMAND_FINISHED: "+str(_err) ); # ------------------------------------------------------------------- # ======================================================================= def CREATE_TREE( self, _ADDR ): # ------------------------------------------------------------------- try: LEVEL_UP = ""; if _ADDR == "/": LEVEL_UP = "/"; else: dirs = _ADDR.split("/"); for i in xrange(0, len(dirs)-2): LEVEL_UP += dirs[i]+"/"; except Exception as _err: self.LOCAL_ERROR_LOG( str(_err), "CREATE_TREE:0" ); return False; # ----------------------------------------------------------------- try: # GENERATE HTML-BASED-FILE-EXPLORER _HTML = ""; _HR_ = '<div class="_hr_div"></div>'+"\n"; with open( self.PARENT.DATA_DIR+"css/file_browser.css", 'r' ) as FS: for _l in FS: _HTML += _l; _HTML += _HR_; _HTML += ' ["<a class="_nav_path" href="ftp://'+self.HOST+LEVEL_UP+'">level up</a>"] => '; # ----------------------------------------------------------------- _ADDR = _ADDR.replace("//","/"); QUICK_NAV_PATH = ""; QUICK_NAV_NAME = '["'; QUICK_NAV_DATA = _ADDR.split( "/" ); for quick_nav in QUICK_NAV_DATA: QUICK_NAV_PATH += quick_nav.strip()+"/"; QUICK_NAV_NAME += '<a class="_nav_path" href="ftp://'+self.HOST+QUICK_NAV_PATH+'">'+quick_nav.strip()+"</a>/"; _HTML += (QUICK_NAV_NAME[ 0: len(QUICK_NAV_NAME)-1 ])+'"]'; _HTML += _HR_; except Exception as _err: self.LOCAL_ERROR_LOG( str(_err), "CREATE_TREE:1" ); return False; # ----------------------------------------------------------------- try: _F = []; # files _D = []; # directoris host_path = 'ftp://'+self.HOST+self.PATH; # Name, isFile, date, size, owner for _f_info in self.FILE_INFO_LIST: try: mod_date = "["+strftime("%d-%b-%Y %H:%M:%S", localtime( _f_info[2] ))+"]"; except: print( ":::::::::::::::: "+str(_f_info[2]) ); mod_date = "[out of range]"; if _f_info[1]: _sizeByte = _f_info[3]; _sizeKByte = float(_sizeByte/1024); _sizeMByte = float(_sizeKByte/1024); if _sizeMByte > 0.99999: _size = "{0:.2f} Mb".format( _sizeMByte ); elif _sizeKByte > 0.99999: _size = "{0:.2f} KiB".format( _sizeKByte ); else: _size = str(_sizeByte)+" Byte"; _f = '<div class="_line">'; if _f_info[0:1] == ".": _f += '<div class="_long_name"><a class="_file_hidden" href="'+host_path+_f_info[0]+'"> '+_f_info[0]+'</a></div>'; else: _f += '<div class="_long_name"><a class="_file" href="'+host_path+_f_info[0]+'"> '+_f_info[0]+'</a></div>'; _f += '<span class="_size">'+_size+'</span>'; _f += '<span class="_mod_date">'+mod_date+'</span>'; _f += '<span class="_descr_F">(F)</span>'; _f += '</div>\n'; _F.append( _f ); else: _d = '<div class="_line">'; if _f_info[0:1] == ".": _d += '<div class="_long_name"><a class="_dir_hidden" href="'+host_path+_f_info[0]+'/"> '+_f_info[0]+'/</a></div>'; else: #print(host_path, _f_info[0], [self.HOST,self.PATH]) _d += '<div class="_long_name"><a class="_dir" href="'+host_path+_f_info[0]+'/"> '+_f_info[0]+'/</a></div>'; _d += '<span class="_size">...</span>'; _d += '<span class="_mod_date">'+mod_date+'</span>'; _d += '<span class="_descr_D">(D)</span>'; _d += '</div>\n'; _D.append( _d ); except Exception as _err: self.LOCAL_ERROR_LOG( str(_err), "CREATE_TREE:2" ); return False; # ------------------------------------------------------------------------- for _d in _D: _HTML += _d; for _f in _F: _HTML += _f; """ try: if self.SHOW_FILES_FIRST: #if _file_first: for _f in _F: _HTML += _f; for _d in _D: _HTML += _d; else: for _d in _D: _HTML += _d; for _f in _F: _HTML += _f; except Exception as _err: self.LOCAL_ERROR_LOG( str(_err), "CREATE_TREE:3" ); return False; """ # ------------------------------------------------------------------------- try: new_name = self.PARENT.TMP_DIR+str(int(time()))+".html"; FS = open(new_name, "w"); FS.write( _HTML+_HR_ ); FS.close(); self.NEW_URL = new_name; except Exception as _err: self.LOCAL_ERROR_LOG( str(_err), "CREATE_TREE:4" ); return False; # ------------------------------------------------------------------- try: self.PARENT.WEB_VIEW.load( QUrl(self.NEW_URL) ); except Exception as _err: self.LOCAL_ERROR_LOG( str(_err), "CREATE_TREE:5" ); return False; # ------------------------------------------------------------------- return True; # ------------------------------------------------------------------- # ======================================================================= def ON_LIST_INFO_AVAILABLE( self, _QUrlInfo ): # ------------------------------------------------------------------- try: _f_info = QUrlInfo( _QUrlInfo ); self.FILE_INFO_LIST.append([ str(_f_info.name()), bool( _f_info.isFile() ), long( _f_info.lastModified().toMSecsSinceEpoch()/1000 ), int(_f_info.size()), str(_f_info.owner()) ]); except Exception as _err: self.LOCAL_ERROR_LOG( "LIST_INFO: "+str(_err) ); # ------------------------------------------------------------------- # ======================================================================= def ON_STATE_CHANGED ( self, _state ): # ------------------------------------------------------------------- try: if _state == QFtp.Unconnected: # 0 - There is no connection to the host. if self.DEBUG: print("DocFTPHandler: [QFtp.Unconnected]"); self.close(); elif _state == QFtp.HostLookup: # 1 - A host name lookup is in progress. if self.DEBUG: print("DocFTPHandler: [QFtp.HostLookup]"); elif _state == QFtp.Connecting: # 2 - An attempt to connect to the host is in progress. if self.DEBUG: print("DocFTPHandler: [QFtp.Connecting]"); elif _state == QFtp.Connected: # 3 - Connection to the host has been achieved. if self.DEBUG: print("DocFTPHandler: [QFtp.Connected]"); elif _state == QFtp.LoggedIn: # 4 - Connection and user login have been achieved. if self.DEBUG: print("DocFTPHandler: [QFtp.LoggedIn]"); elif _state == QFtp.Closing: # 5 - The connection is closing down, but it is not yet closed. (The state will be Unconnected when the connection is closed.) if self.DEBUG: print("DocFTPHandler: [QFtp.Closing]"); self.close(); else: print("DocFTPHandler: [QFtp.STATE: 'Unknown'"); except Exception as _err: self.LOCAL_ERROR_LOG( "ON_STATE_CHANGED: "+str(_err) ); # ------------------------------------------------------------------- # ======================================================================= def ON_DATA_TRANSFER_PROGRESS( self, _qint64_A, _qint64_B ): # ------------------------------------------------------------------- try: pass; #print(" ON_DATA_TRANSFER_PROGRESS: ["+str(_qint64_A)+", "+str(_qint64_B)+"]" ); except Exception as _err: self.LOCAL_ERROR_LOG( "ON_DATA_TRANSFER_PROGRESS: "+str(_err) ); # ------------------------------------------------------------------- # ======================================================================= def ON_RAW_COMMAND_REPLY ( self, _int, _str ): # ------------------------------------------------------------------- try: pass; #print(" ON_RAW_COMMAND_REPLY: ["+str(_int)+", "+str(_str)+"]" ); except Exception as _err: self.LOCAL_ERROR_LOG( "ON_RAW_COMMAND_REPLY: "+str(_err) ); # ------------------------------------------------------------------- # ======================================================================= def ON_DONE( self, _bool ): # ------------------------------------------------------------------- try: pass; except Exception as _err: self.LOCAL_ERROR_LOG( "ON_DONE: "+str(_err) ); # ------------------------------------------------------------------- # ======================================================================= def ON_READY_READ( self ): # ------------------------------------------------------------------- try: pass; except Exception as _err: self.LOCAL_ERROR_LOG( "ON_READY_READ: "+str(_err) ); # ------------------------------------------------------------------- # ======================================================================= def ON_COMMAND_STARTED ( self, _int ): # ------------------------------------------------------------------- try: pass; except Exception as _err: self.LOCAL_ERROR_LOG( "ON_COMMAND_STARTED: "+str(_err) ); # ------------------------------------------------------------------- # ======================================================================= def LOCAL_INFO_LOG( self, _msg, METHOD=None ): # ------------------------------------------------------------------- if METHOD is None: self.PARENT.LOCAL_INFO_LOG( "['"+self.LOG_TAG+"']: ["+_msg+"]" ); else: self.PARENT.LOCAL_INFO_LOG( "['"+self.LOG_TAG+"."+METHOD+"']: ["+_msg+"]" ); # ------------------------------------------------------------------- # ======================================================================= def LOCAL_ERROR_LOG( self, _msg, METHOD=None ): # ------------------------------------------------------------------- if self.DEBUG or self.PARENT.DEBUG_GLOBAL: self.PARENT.DEBUGGER.DEBUG(); # ------------------------------------------------------------------- if METHOD is None: self.PARENT.LOCAL_ERROR_LOG( "['"+self.LOG_TAG+"']: ["+_msg+"]" ); else: self.PARENT.LOCAL_ERROR_LOG( "['"+self.LOG_TAG+"."+METHOD+"']: ["+_msg+"]" ); # ------------------------------------------------------------------- # ======================================================================= def LOCAL_WARNING_LOG( self, _msg, METHOD=None ): # ------------------------------------------------------------------- #if self.DEBUG or self.PARENT.DEBUG_GLOBAL: self.PARENT.DEBUGGER.DEBUG(); # ------------------------------------------------------------------- if METHOD is None: self.PARENT.LOCAL_WARNING_LOG( "['"+self.LOG_TAG+"']: ["+_msg+"]" ); else: self.PARENT.LOCAL_WARNING_LOG( "['"+self.LOG_TAG+"."+METHOD+"']: ["+_msg+"]" );
class DownloadFtp(Download): progressModified = pyqtSignal(object) stateChanged = pyqtSignal(object) downloadFinished = pyqtSignal(object) speedModified = pyqtSignal(object) def __init__(self, file_share, local_path, date, state): Download.__init__(self, file_share, local_path, date, state) self.ftp = QFtp(self) # Signaux self.ftp.dataTransferProgress.connect(self.update_progress) self.ftp.done.connect(self.download_finished) self.ftp.stateChanged.connect(self.state_changed) # Ouverture de fichiers self.url = QUrl(self._file_share.url) self.out_file = QFile(self.local_path) # Vars self.read_bytes = self.out_file.size() # Timer self.timer = QTimer() self.timer.start(500) self.timer.timeout.connect(self.update_speed) def start_download(self): self.ftp.connectToHost(self.url.host(), self.url.port(21)) self.ftp.login() if self.out_file.open(QIODevice.WriteOnly): self.ftp.get(self.url.path(), self.out_file) def stop(self): self._state = 5 self.ftp.abort() self.timer.stop() self.ftp.close() def state_changed(self, state): if state == 1 or state == 2: self._state = 1 elif state == 3 or state == 4: self._state = 3 self.stateChanged.emit(self) def download_finished(self, _): print "finished !" if self.read_bytes != self.file_share.size: self._state = 7 self._speed = 0 self.timer.stop() self.ftp.abort() self.ftp.close() self._state = 4 self.stateChanged.emit(self) self.ftp.done.disconnect(self.download_finished) self.ftp.stateChanged.disconnect(self.state_changed) self.ftp.dataTransferProgress.disconnect(self.update_progress) self.downloadFinished.emit(self) def update_speed(self): delta = time.time() - self._last_time self._speed = float(self.read_bytes - self._last_size) / delta self.last_time = time.time() self.last_size = self.read_bytes self.speedModified.emit(self) def update_progress(self, read_bytes, total_bytes): self.read_bytes = read_bytes self.progressModified.emit(self)
def initialize(self, *args, **kwargs): " Init Main Class " super(Main, self).initialize(*args, **kwargs) self.completer, self.dirs = QCompleter(self), QDirModel(self) self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot) self.completer.setModel(self.dirs) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.completer.setCompletionMode(QCompleter.PopupCompletion) self.desktop, self.project, menu = '', '', QMenu('Vagrant') menu.addAction('UP', lambda: self.vagrant_c('up')) menu.addAction('HALT', lambda: self.vagrant_c('halt')) menu.addAction('RELOAD', lambda: self.vagrant_c('reload')) menu.addAction('STATUS', lambda: self.vagrant_c('status')) menu.addAction('SUSPEND', lambda: self.vagrant_c('suspend')) menu.addAction('RESUME', lambda: self.vagrant_c('resume')) menu.addAction('PROVISION', lambda: self.vagrant_c('provision')) menu.addAction('PACKAGE', lambda: self.vagrant_c('package')) menu.addAction('INIT', lambda: self.vagrant_c('init')) menu.addSeparator() menu.addAction('DESTROY (!!!)', lambda: self.vagrant_c('destroy')) self.locator.get_service('explorer').add_project_menu(menu, lang='all') self.process = QProcess() self.process.readyReadStandardOutput.connect(self.readOutput) self.process.readyReadStandardError.connect(self.readErrors) self.process.finished.connect(self._process_finished) self.process.error.connect(self._process_finished) # Proxy support, by reading http_proxy os env variable proxy_url = QUrl(environ.get('http_proxy', '')) QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy if str(proxy_url.scheme()).startswith('http') else QNetworkProxy.Socks5Proxy, proxy_url.host(), proxy_url.port(), proxy_url.userName(), proxy_url.password())) \ if 'http_proxy' in environ else None self.mainwidget = QTabWidget() self.mainwidget.tabCloseRequested.connect(lambda: self.mainwidget.setTabPosition(1) if self.mainwidget.tabPosition() == 0 else self.mainwidget.setTabPosition(0)) self.mainwidget.setStyleSheet('QTabBar{font-weight:bold;}') self.mainwidget.setMovable(True) self.mainwidget.setTabsClosable(True) self.dock, self.scrollable = QDockWidget(), QScrollArea() self.scrollable.setWidgetResizable(True) self.scrollable.setWidget(self.mainwidget) self.dock.setWindowTitle(__doc__) self.dock.setStyleSheet('QDockWidget::title{text-align: center;}') self.dock.setWidget(self.scrollable) self.locator.get_service('misc').add_widget(self.dock, QIcon.fromTheme("virtualbox"), __doc__) self.tab1, self.tab2, self.tab3 = QGroupBox(), QGroupBox(), QGroupBox() self.tab4, self.tab5, self.tab6 = QGroupBox(), QGroupBox(), QGroupBox() for a, b in ((self.tab1, 'Basics'), (self.tab2, 'General Options'), (self.tab3, 'VM Package Manager'), (self.tab4, 'VM Provisioning'), (self.tab5, 'VM Desktop GUI'), (self.tab6, 'Run')): a.setTitle(b) a.setToolTip(b) self.mainwidget.addTab(a, QIcon.fromTheme("virtualbox"), b) QPushButton(QIcon.fromTheme("help-about"), 'About', self.dock ).clicked.connect(lambda: QMessageBox.information(self.dock, __doc__, HELPMSG)) self.vmname = QLineEdit(self.get_name()) self.vmname.setPlaceholderText('type_your_VM_name_here_without_spaces') self.vmname.setToolTip('Type VM name, no spaces or special characters') self.target = QLabel('<b>Vagrant Target Folder: ' + path.join(BASE, self.vmname.text())) self.vmname.textChanged.connect(lambda: self.target.setText( '<b>Vagrant Target Folder: ' + path.join(BASE, self.vmname.text()))) self.btn1 = QPushButton(QIcon.fromTheme("face-smile-big"), 'Suggestion') self.btn1.setToolTip('Suggest me a Random VM name !') self.btn1.clicked.connect(lambda: self.vmname.setText(self.get_name())) self.vmcode, self.vmarch = QComboBox(), QComboBox() self.vmcode.addItems(['saucy', 'raring', 'quantal', 'precise']) self.vmarch.addItems(['x86_64 (amd64) 64-Bits', 'x86 (i386) 32-Bits']) vboxg1 = QVBoxLayout(self.tab1) for each_widget in (QLabel('<b>Name for VM'), self.vmname, self.btn1, QLabel('<b>Choose Ubuntu Codename for the VM:</b>'), self.vmcode, QLabel('<b>Choose Architecture for VM:'), self.vmarch, self.target): vboxg1.addWidget(each_widget) self.chrt = QCheckBox('LOW CPU priority for Backend Process') self.chttps = QComboBox() self.chttps.addItems(['https', 'http']) try: self.vinfo1 = QLabel('''<b> Vagrant Backend Version: </b> {}, <b> VirtualBox Backend Version: </b> {}. '''.format( getoutput('vagrant --version', shell=1).strip(), getoutput('vboxmanage --version', shell=1).strip())) except: self.vinfo1 = QLabel('<b>Warning: Failed to query Vagrant Backend!') self.qckb1 = QCheckBox(' Open target directory later') self.qckb1.setToolTip('Open the target directory when finished') self.qckb2 = QCheckBox(' Save a LOG file to target later') self.qckb2.setToolTip('Save a read-only .LOG file to target') self.qckb3 = QCheckBox(' NO run Headless Mode, use a Window') self.qckb3.setToolTip('Show the VM on a Window GUI instead of Headless') self.cpu, self.ram = QSpinBox(), QSpinBox() self.cpu.setRange(25, 99) self.cpu.setValue(99) self.ram.setRange(512, 4096) self.ram.setValue(1024) vboxg2 = QVBoxLayout(self.tab2) for each_widget in (self.qckb1, self.qckb2, self.qckb3, self.chrt, QLabel('<b>Max CPU Limit for VM:</b>'), self.cpu, QLabel('<b>Max RAM Limit for VM:</b>'), self.ram, QLabel('<b>Download Protocol Type:</b>'), self.chttps, self.vinfo1): vboxg2.addWidget(each_widget) self.qckb10 = QCheckBox('Run apt-get update on the created VM') self.qckb11 = QCheckBox('Run apt-get dist-upgrade on the created VM') self.qckb12 = QCheckBox('Run apt-get check on the created VM') self.qckb12 = QCheckBox('Run apt-get clean on the created VM') self.qckb13 = QCheckBox('Run apt-get autoremove on the created VM') self.qckb14 = QCheckBox('Try to Fix Broken packages if any on the VM') self.aptproxy, self.portredirect = QLineEdit(), QLineEdit('8000, 9000') self.aptproxy.setPlaceholderText(' user:password@proxyaddress:port ') vboxg3 = QVBoxLayout(self.tab3) for each_widget in (self.qckb10, self.qckb11, self.qckb12, self.qckb13, self.qckb14, QLabel('<b>Network Proxy for apt-get on the VM'), self.aptproxy, QLabel('<b>Network Port Redirects for the VM'), self.portredirect): vboxg3.addWidget(each_widget) self.aptpkg = QTextEdit('build-essential git python-pip vim mc wget') self.aptppa, self.pippkg = QLineEdit(), QTextEdit('virtualenv yolk') self.aptppa.setPlaceholderText(' ppa:ninja-ide-developers/daily ') self.requirements = QLineEdit() self.requirements.setPlaceholderText(' /full/path/to/requirements.txt ') self.requirements.setCompleter(self.completer) vboxg4 = QVBoxLayout(self.tab4) for each_widget in (QLabel('<b>Custom APT Ubuntu package'), self.aptpkg, QLabel('<b>Custom APT Ubuntu PPA:</b> '), self.aptppa, QLabel('<b>Custom PIP Python packages:</b> '), self.pippkg, QLabel('<b>Custom PIP Python requirements: '), self.requirements): vboxg4.addWidget(each_widget) self.buttonGroup = QButtonGroup() self.buttonGroup.buttonClicked[QAbstractButton].connect(self.get_de_pkg) vboxg5 = QVBoxLayout(self.tab5) for i, d in enumerate(('Ubuntu Unity', 'KDE Plasma', 'LXDE', 'XFCE')): button = QPushButton(d) button.setCheckable(True) button.setMinimumSize(75, 50) button.setToolTip(d) vboxg5.addWidget(button) self.buttonGroup.addButton(button) self.output = QTextEdit(''' We have persistent objects, they are called files. -Ken Thompson. ''') self.runbtn = QPushButton(QIcon.fromTheme("media-playback-start"), 'Start Vagrant Instrumentation Now !') self.runbtn.setMinimumSize(75, 50) self.runbtn.clicked.connect(self.build) glow = QGraphicsDropShadowEffect(self) glow.setOffset(0) glow.setBlurRadius(99) glow.setColor(QColor(99, 255, 255)) self.runbtn.setGraphicsEffect(glow) self.stopbt = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop Vagrant') self.stopbt.clicked.connect(lambda: self.process.stop()) self.killbt = QPushButton(QIcon.fromTheme("application-exit"), 'Force Kill Vagrant') self.killbt.clicked.connect(lambda: self.process.kill()) vboxg6 = QVBoxLayout(self.tab6) for each_widget in (QLabel('<b>Multiprocess Output Logs'), self.output, self.runbtn, self.stopbt, self.killbt): vboxg6.addWidget(each_widget) [a.setChecked(True) for a in (self.qckb1, self.qckb2, self.qckb3, self.qckb10, self.qckb11, self.qckb12, self.qckb13, self.qckb14, self.chrt)] self.mainwidget.setCurrentIndex(5)
class CoverArtImage: # Indicate if types are provided by the source, ie. CAA or certain file # formats may have types associated with cover art, but some other sources # don't provide such information support_types = False # `is_front` has to be explicitely set, it is used to handle CAA is_front # indicator is_front = None sourceprefix = "URL" def __init__(self, url=None, types=[], comment='', data=None): if url is not None: self.parse_url(url) else: self.url = None self.types = types self.comment = comment self.datahash = None # thumbnail is used to link to another CoverArtImage, ie. for PDFs self.thumbnail = None self.can_be_saved_to_tags = True self.can_be_saved_to_disk = True self.can_be_saved_to_metadata = True if data is not None: self.set_data(data) def parse_url(self, url): self.url = QUrl(url) self.host = str(self.url.host()) self.port = self.url.port(80) self.path = str(self.url.encodedPath()) if self.url.hasQuery(): self.path += '?' + str(self.url.encodedQuery()) @property def source(self): if self.url is not None: return u"%s: %s" % (self.sourceprefix, self.url.toString()) else: return u"%s" % self.sourceprefix def is_front_image(self): """Indicates if image is considered as a 'front' image. It depends on few things: - if `is_front` was set, it is used over anything else - if `types` was set, search for 'front' in it - if `support_types` is False, default to True for any image - if `support_types` is True, default to False for any image """ if not self.can_be_saved_to_metadata: # ignore thumbnails return False if self.is_front is not None: return self.is_front if u'front' in self.types: return True return (self.support_types is False) def imageinfo_as_string(self): if self.datahash is None: return "" return "w=%d h=%d mime=%s ext=%s datalen=%d file=%s" % ( self.width, self.height, self.mimetype, self.extension, self.datalength, self.tempfile_filename) def __repr__(self): p = [] if self.url is not None: p.append("url=%r" % self.url.toString()) if self.types: p.append("types=%r" % self.types) if self.is_front is not None: p.append("is_front=%r" % self.is_front) if self.comment: p.append("comment=%r" % self.comment) return "%s(%s)" % (self.__class__.__name__, ", ".join(p)) def __unicode__(self): p = [u'Image'] if self.url is not None: p.append(u"from %s" % self.url.toString()) if self.types: p.append(u"of type %s" % u','.join(self.types)) if self.comment: p.append(u"and comment '%s'" % self.comment) return u' '.join(p) def __str__(self): return unicode(self).encode('utf-8') def set_data(self, data): """Store image data in a file, if data already exists in such file it will be re-used and no file write occurs """ if self.datahash: self.datahash.delete_file() self.datahash = None try: (self.width, self.height, self.mimetype, self.extension, self.datalength) = imageinfo.identify(data) except imageinfo.IdentificationError as e: raise CoverArtImageIdentificationError(e) try: self.datahash = DataHash(data, suffix=self.extension) except (OSError, IOError) as e: raise CoverArtImageIOError(e) @property def maintype(self): """Returns one type only, even for images having more than one type set. This is mostly used when saving cover art to tags because most formats don't support multiple types for one image. Images coming from CAA can have multiple types (ie. 'front, booklet'). """ if self.is_front_image() or not self.types or u'front' in self.types: return u'front' # TODO: do something better than randomly using the first in the list return self.types[0] def _make_image_filename(self, filename, dirname, metadata): filename = ScriptParser().eval(filename, metadata) if config.setting["ascii_filenames"]: if isinstance(filename, unicode): filename = unaccent(filename) filename = replace_non_ascii(filename) if not filename: filename = "cover" if not os.path.isabs(filename): filename = os.path.join(dirname, filename) # replace incompatible characters if config.setting["windows_compatibility"] or sys.platform == "win32": filename = replace_win32_incompat(filename) # remove null characters filename = filename.replace("\x00", "") return encode_filename(filename) def save(self, dirname, metadata, counters): """Saves this image. :dirname: The name of the directory that contains the audio file :metadata: A metadata object :counters: A dictionary mapping filenames to the amount of how many images with that filename were already saved in `dirname`. """ if not self.can_be_saved_to_disk: return if (config.setting["caa_image_type_as_filename"] and not self.is_front_image()): filename = self.maintype log.debug("Make cover filename from types: %r -> %r", self.types, filename) else: filename = config.setting["cover_image_filename"] log.debug("Using default cover image filename %r", filename) filename = self._make_image_filename(filename, dirname, metadata) overwrite = config.setting["save_images_overwrite"] ext = self.extension image_filename = self._next_filename(filename, counters) while os.path.exists(image_filename + ext) and not overwrite: if not self._is_write_needed(image_filename + ext): break image_filename = self._next_filename(filename, counters) else: new_filename = image_filename + ext # Even if overwrite is enabled we don't need to write the same # image multiple times if not self._is_write_needed(new_filename): return log.debug("Saving cover image to %r", new_filename) try: new_dirname = os.path.dirname(new_filename) if not os.path.isdir(new_dirname): os.makedirs(new_dirname) shutil.copyfile(self.tempfile_filename, new_filename) except (OSError, IOError) as e: raise CoverArtImageIOError(e) def _next_filename(self, filename, counters): if counters[filename]: new_filename = "%s (%d)" % (filename, counters[filename]) else: new_filename = filename counters[filename] += 1 return new_filename def _is_write_needed(self, filename): if (os.path.exists(filename) and os.path.getsize(filename) == self.datalength): log.debug("Identical file size, not saving %r", filename) return False return True @property def data(self): """Reads the data from the temporary file created for this image. May raise CoverArtImageIOError """ try: return self.datahash.data except (OSError, IOError) as e: raise CoverArtImageIOError(e) @property def tempfile_filename(self): return self.datahash.filename def types_as_string(self, translate=True, separator=', '): if self.types: types = self.types elif self.is_front_image(): types = [u'front'] else: types = [u'-'] if translate: types = [translate_caa_type(type) for type in types] return separator.join(types)
def __init__(self, AUTO): ' Initialize QWidget inside MyMainWindow ' super(MyMainWindow, self).__init__() QWidget.__init__(self) self.auto = AUTO self.statusBar().showMessage(' {}'.format(__doc__)) self.setStyleSheet('QStatusBar{color:grey;}') self.setWindowTitle(__doc__) self.setWindowIcon(QIcon.fromTheme("face-monkey")) self.setFont(QFont('Ubuntu Light', 10)) self.setMaximumSize(QDesktopWidget().screenGeometry().width(), QDesktopWidget().screenGeometry().height()) self.base = path.abspath(path.join(getcwd(), str(datetime.now().year))) # directory auto completer self.completer = QCompleter(self) self.dirs = QDirModel(self) self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot) self.completer.setModel(self.dirs) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.completer.setCompletionMode(QCompleter.PopupCompletion) # process self.process1 = None self.process2 = None self.cmd1 = 'nice -n {n} arecord{v} -f {f} -c {c} -r {b} -t raw' self.cmd2 = 'oggenc - -r -C {c} -R {b} -q {q} {d}{t}{a} -o {o}' self.process3 = QProcess(self) #self.process3.finished.connect(self.on_process3_finished) #self.process3.error.connect(self.on_process3_error) self.cmd3 = ('nice -n 20 ' + 'sox "{o}" -n spectrogram -x {x} -y {y} -z 99 -t "{o}" -o "{o}.png"') self.actual_file = '' # re starting timers, one stops, one starts self.timerFirst = QTimer(self) self.timerFirst.timeout.connect(self.end) self.timerSecond = QTimer(self) self.timerSecond.timeout.connect(self.run) # Proxy support, by reading http_proxy os env variable proxy_url = QUrl(environ.get('http_proxy', '')) QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy if str(proxy_url.scheme()).startswith('http') else QNetworkProxy.Socks5Proxy, proxy_url.host(), proxy_url.port(), proxy_url.userName(), proxy_url.password())) \ if 'http_proxy' in environ else None print((' INFO: Proxy Auto-Config as ' + str(proxy_url))) # basic widgets layouts and set up self.mainwidget = QTabWidget() self.mainwidget.setToolTip(__doc__) self.mainwidget.setMovable(True) self.mainwidget.setTabShape(QTabWidget.Triangular) self.mainwidget.setContextMenuPolicy(Qt.CustomContextMenu) self.mainwidget.setStyleSheet('QTabBar{color:white;font-weight:bold;}') self.mainwidget.setTabBar(TabBar(self)) self.mainwidget.setTabsClosable(False) self.setCentralWidget(self.mainwidget) self.dock1 = QDockWidget() self.dock2 = QDockWidget() self.dock3 = QDockWidget() self.dock4 = QDockWidget() self.dock5 = QDockWidget() for a in (self.dock1, self.dock2, self.dock3, self.dock4, self.dock5): a.setWindowModality(Qt.NonModal) # a.setWindowOpacity(0.9) a.setWindowTitle(__doc__ if a.windowTitle() == '' else a.windowTitle()) a.setStyleSheet('QDockWidget::title{text-align:center;}') self.mainwidget.addTab(a, QIcon.fromTheme("face-smile"), 'Double Click Me') # Paleta de colores para pintar transparente self.palette().setBrush(QPalette.Base, Qt.transparent) self.setPalette(self.palette()) self.setAttribute(Qt.WA_OpaquePaintEvent, False) # toolbar and basic actions self.toolbar = QToolBar(self) self.toolbar.setIconSize(QSize(24, 24)) # spacer widget for left self.left_spacer = QWidget(self) self.left_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # spacer widget for right self.right_spacer = QWidget(self) self.right_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) qaqq = QAction(QIcon.fromTheme("application-exit"), 'Quit', self) qaqq.setShortcut('Ctrl+Q') qaqq.triggered.connect(exit) qamin = QAction(QIcon.fromTheme("go-down"), 'Minimize', self) qamin.triggered.connect(lambda: self.showMinimized()) qamax = QAction(QIcon.fromTheme("go-up"), 'Maximize', self) qanor = QAction(QIcon.fromTheme("view-fullscreen"), 'AutoCenter AutoResize', self) qanor.triggered.connect(self.center) qatim = QAction(QIcon.fromTheme("mail-signed-verified"), 'View Date and Time', self) qatim.triggered.connect(self.timedate) qabug = QAction(QIcon.fromTheme("help-about"), 'Report a Problem', self) qabug.triggered.connect(lambda: qabug.setDisabled(True) if not call( 'xdg-open mailto:' + '*****@*****.**'.decode('rot13'), shell=True) else ' ERROR ') qamax.triggered.connect(lambda: self.showMaximized()) qaqt = QAction(QIcon.fromTheme("help-about"), 'About Qt', self) qaqt.triggered.connect(lambda: QMessageBox.aboutQt(self)) qakde = QAction(QIcon.fromTheme("help-about"), 'About KDE', self) if KDE: qakde.triggered.connect(KHelpMenu(self, "", False).aboutKDE) qaslf = QAction(QIcon.fromTheme("help-about"), 'About Self', self) if KDE: qaslf.triggered.connect( KAboutApplicationDialog(aboutData, self).exec_) else: qaslf.triggered.connect(lambda: QMessageBox.about(self.mainwidget, __doc__, ''.join((__doc__, linesep, 'version ', __version__, ', (', __license__, '), by ', __author__, ', ( ', __email__, ' )', linesep )))) qafnt = QAction(QIcon.fromTheme("tools-check-spelling"), 'Set GUI Font', self) if KDE: font = QFont() qafnt.triggered.connect(lambda: self.setStyleSheet(''.join(( '*{font-family:', str(font.toString()), '}')) if KFontDialog.getFont(font)[0] == QDialog.Accepted else '')) else: qafnt.triggered.connect(lambda: self.setStyleSheet(''.join(('*{font-family:', str(QFontDialog.getFont()[0].toString()), '}')))) qasrc = QAction(QIcon.fromTheme("applications-development"), 'View Source Code', self) qasrc.triggered.connect(lambda: call('xdg-open {}'.format(__file__), shell=True)) qakb = QAction(QIcon.fromTheme("input-keyboard"), 'Keyboard Shortcuts', self) qakb.triggered.connect(lambda: QMessageBox.information(self.mainwidget, 'Keyboard Shortcuts', ' Ctrl+Q = Quit ')) qapic = QAction(QIcon.fromTheme("camera-photo"), 'Take a Screenshot', self) qapic.triggered.connect(lambda: QPixmap.grabWindow( QApplication.desktop().winId()).save(QFileDialog.getSaveFileName( self.mainwidget, " Save Screenshot As ...", path.expanduser("~"), ';;(*.png) PNG', 'png'))) qatb = QAction(QIcon.fromTheme("go-top"), 'Toggle ToolBar', self) qatb.triggered.connect(lambda: self.toolbar.hide() if self.toolbar.isVisible() is True else self.toolbar.show()) qati = QAction(QIcon.fromTheme("zoom-in"), 'Switch ToolBar Icon Size', self) qati.triggered.connect(lambda: self.toolbar.setIconSize(self.toolbar.iconSize() * 4) if self.toolbar.iconSize().width() * 4 == 24 else self.toolbar.setIconSize(self.toolbar.iconSize() / 4)) qasb = QAction(QIcon.fromTheme("preferences-other"), 'Toggle Tabs Bar', self) qasb.triggered.connect(lambda: self.mainwidget.tabBar().hide() if self.mainwidget.tabBar().isVisible() is True else self.mainwidget.tabBar().show()) qadoc = QAction(QIcon.fromTheme("help-browser"), 'On-line Docs', self) qadoc.triggered.connect(lambda: open_new_tab(str(__url__).strip())) qapy = QAction(QIcon.fromTheme("help-about"), 'About Python', self) qapy.triggered.connect(lambda: open_new_tab('http://python.org/about')) qali = QAction(QIcon.fromTheme("help-browser"), 'Read Licence', self) qali.triggered.connect(lambda: open_new_tab(__full_licence__)) qacol = QAction(QIcon.fromTheme("preferences-system"), 'Set GUI Colors', self) if KDE: color = QColor() qacol.triggered.connect(lambda: self.setStyleSheet(''.join(('* { background-color: ', str(color.name()), '}'))) if KColorDialog.getColor(color, self) else '') else: qacol.triggered.connect(lambda: self.setStyleSheet(''.join(( ' * { background-color: ', str(QColorDialog.getColor().name()), ' } ')))) qatit = QAction(QIcon.fromTheme("preferences-system"), 'Set the App Window Title', self) qatit.triggered.connect(self.seTitle) self.toolbar.addWidget(self.left_spacer) self.toolbar.addSeparator() self.toolbar.addActions((qaqq, qamin, qanor, qamax, qasrc, qakb, qacol, qatim, qatb, qafnt, qati, qasb, qatit, qapic, qadoc, qali, qaslf, qaqt, qakde, qapy, qabug)) self.addToolBar(Qt.TopToolBarArea, self.toolbar) self.toolbar.addSeparator() self.toolbar.addWidget(self.right_spacer) # define the menu menu = self.menuBar() # File menu items menu.addMenu('&File').addActions((qaqq, )) menu.addMenu('&Window').addActions((qamax, qanor, qamin)) # Settings menu menu.addMenu('&Settings').addActions((qasrc, qacol, qafnt, qatim, qatb, qati, qasb, qapic)) # Help menu items menu.addMenu('&Help').addActions((qadoc, qakb, qabug, qali, qaqt, qakde, qapy, qaslf)) # Tray Icon tray = QSystemTrayIcon(QIcon.fromTheme("face-devilish"), self) tray.setToolTip(__doc__) traymenu = QMenu() traymenu.addActions((qamax, qanor, qamin, qaqq)) tray.setContextMenu(traymenu) tray.show() def contextMenuRequested(point): ' quick and dirty custom context menu ' menu = QMenu() menu.addActions((qaqq, qamin, qanor, qamax, qasrc, qakb, qacol, qafnt, qati, qasb, qatb, qatim, qatit, qapic, qadoc, qali, qaslf, qaqt, qakde, qapy, qabug)) menu.exec_(self.mapToGlobal(point)) self.mainwidget.customContextMenuRequested.connect(contextMenuRequested) def must_be_checked(widget_list): ' widget tuple passed as argument should be checked as ON ' for each_widget in widget_list: try: each_widget.setChecked(True) except: pass def must_have_tooltip(widget_list): ' widget tuple passed as argument should have tooltips ' for each_widget in widget_list: try: each_widget.setToolTip(each_widget.text()) except: each_widget.setToolTip(each_widget.currentText()) finally: each_widget.setCursor(QCursor(Qt.PointingHandCursor)) def must_autofillbackground(widget_list): ' widget tuple passed as argument should have filled background ' for each_widget in widget_list: try: each_widget.setAutoFillBackground(True) except: pass def must_glow(widget_list): ' apply an glow effect to the widget ' for glow, each_widget in enumerate(widget_list): try: if each_widget.graphicsEffect() is None: glow = QGraphicsDropShadowEffect(self) glow.setOffset(0) glow.setBlurRadius(99) glow.setColor(QColor(99, 255, 255)) each_widget.setGraphicsEffect(glow) # glow.setEnabled(False) try: each_widget.clicked.connect(lambda: each_widget.graphicsEffect().setEnabled(True) if each_widget.graphicsEffect().isEnabled() is False else each_widget.graphicsEffect().setEnabled(False)) except: each_widget.sliderPressed.connect(lambda: each_widget.graphicsEffect().setEnabled(True) if each_widget.graphicsEffect().isEnabled() is False else each_widget.graphicsEffect().setEnabled(False)) except: pass ####################################################################### # dock 1 QLabel('<h1 style="color:white;"> Record !</h1>', self.dock1).resize( self.dock3.size().width() / 4, 25) self.group1 = QGroupBox() self.group1.setTitle(__doc__) self.spec = QPushButton(self) self.spec.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.spec.setMinimumSize(self.spec.size().width(), 250) self.spec.setFlat(True) self.spec.clicked.connect(self.spectro) self.clock = QLCDNumber() self.clock.setSegmentStyle(QLCDNumber.Flat) self.clock.setMinimumSize(self.clock.size().width(), 50) self.clock.setNumDigits(25) self.timer1 = QTimer(self) self.timer1.timeout.connect(lambda: self.clock.display( datetime.now().strftime("%d-%m-%Y %H:%M:%S %p"))) self.timer1.start(1000) self.clock.setToolTip(datetime.now().strftime("%c %x")) self.clock.setCursor(QCursor(Qt.CrossCursor)) self.diskBar = QProgressBar() self.diskBar.setMinimum(0) self.diskBar.setMaximum(statvfs(HOME).f_blocks * statvfs(HOME).f_frsize / 1024 / 1024 / 1024) self.diskBar.setValue(statvfs(HOME).f_bfree * statvfs(HOME).f_frsize / 1024 / 1024 / 1024) self.diskBar.setToolTip(str(statvfs(HOME).f_bfree * statvfs(HOME).f_frsize / 1024 / 1024 / 1024) + ' Gigabytes free') self.feedback = QPlainTextEdit(''.join(('<center><h3>', __doc__, ', version', __version__, __license__, ' <br> by ', __author__, ' <i>(Dev)</i>, Radio Comunitaria FM Reconquista <i>(Q.A.)</i><br>', 'FMReconquista.org.ar & GitHub.com/JuanCarlosPaco/Cinta-Testigo'))) self.rec = QPushButton(QIcon.fromTheme("media-record"), 'Record') self.rec.setMinimumSize(self.rec.size().width(), 50) self.rec.clicked.connect(self.go) # self.run self.stop = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop') self.stop.clicked.connect(self.end) self.kill = QPushButton(QIcon.fromTheme("process-stop"), 'Kill') self.kill.clicked.connect(self.killer) vboxg1 = QVBoxLayout(self.group1) for each_widget in ( QLabel('<b style="color:white;"> Spectro'), self.spec, QLabel('<b style="color:white;"> Time '), self.clock, QLabel('<b style="color:white;"> Disk '), self.diskBar, QLabel('<b style="color:white;"> STDOUT + STDIN '), self.feedback, QLabel('<b style="color:white;"> Record '), self.rec, self.stop, self.kill): vboxg1.addWidget(each_widget) self.group2 = QGroupBox() self.group2.setTitle(__doc__) self.slider = QSlider(self) self.slid_l = QLabel(self.slider) self.slider.setCursor(QCursor(Qt.OpenHandCursor)) self.slider.sliderPressed.connect(lambda: self.slider.setCursor(QCursor(Qt.ClosedHandCursor))) self.slider.sliderReleased.connect(lambda: self.slider.setCursor(QCursor(Qt.OpenHandCursor))) self.slider.valueChanged.connect(lambda: self.slider.setToolTip(str(self.slider.value()))) self.slider.valueChanged.connect(lambda: self.slid_l.setText( '<h2 style="color:white;">{}'.format(self.slider.value()))) self.slider.setMinimum(10) self.slider.setMaximum(99) self.slider.setValue(30) self.slider.setOrientation(Qt.Vertical) self.slider.setTickPosition(QSlider.TicksBothSides) self.slider.setTickInterval(2) self.slider.setSingleStep(10) self.slider.setPageStep(10) vboxg2 = QVBoxLayout(self.group2) for each_widget in ( QLabel('<b style="color:white;">MINUTES of recording'), self.slider, QLabel('<b style="color:white;"> Default: 30 Min')): vboxg2.addWidget(each_widget) group3 = QGroupBox() group3.setTitle(__doc__) try: self.label2 = QLabel(getoutput('sox --version', shell=True)) self.label4 = QLabel(getoutput('arecord --version', shell=1)[:25]) self.label6 = QLabel(str(getoutput('oggenc --version', shell=True))) except: print(''' ERROR: No SOX, OGGenc avaliable ! ( sudo apt-get install vorbis-tools sox alsa-utils ) ''') exit() self.button5 = QPushButton(QIcon.fromTheme("audio-x-generic"), 'OGG --> ZIP') self.button5.clicked.connect(lambda: make_archive( str(QFileDialog.getSaveFileName(self, "Save OGG to ZIP file As...", getcwd(), ';;(*.zip)', 'zip')).replace('.zip', ''), "zip", path.abspath(path.join(getcwd(), str(datetime.now().year))))) self.button1 = QPushButton(QIcon.fromTheme("folder-open"), 'Files') self.button1.clicked.connect(lambda: call('xdg-open ' + getcwd(), shell=True)) self.button0 = QPushButton( QIcon.fromTheme("preferences-desktop-screensaver"), 'LCD OFF') self.button0.clicked.connect(lambda: call('sleep 3 ; xset dpms force off', shell=True)) vboxg3 = QVBoxLayout(group3) for each_widget in ( QLabel('<b style="color:white;"> OGG Output Codec '), self.label6, QLabel('<b style="color:white;"> Raw Record Backend '), self.label4, QLabel('<b style="color:white;"> Helper Libs '), self.label2, QLabel('<b style="color:white;"> OGG ZIP '), self.button5, QLabel('<b style="color:white;"> Files '), self.button1, QLabel('<b style="color:white;"> LCD '), self.button0): vboxg3.addWidget(each_widget) container = QWidget() hbox = QHBoxLayout(container) for each_widget in (self.group2, self.group1, group3): hbox.addWidget(each_widget) self.dock1.setWidget(container) # dock 2 QLabel('<h1 style="color:white;"> Hardware !</h1>', self.dock2).resize( self.dock2.size().width() / 4, 25) try: audioDriverStr = {Solid.AudioInterface.Alsa: "ALSA", Solid.AudioInterface.OpenSoundSystem: "Open Sound", Solid.AudioInterface.UnknownAudioDriver: "Unknown?"} audioInterfaceTypeStr = { Solid.AudioInterface.AudioControl: "Control", Solid.AudioInterface.UnknownAudioInterfaceType: "Unknown?", Solid.AudioInterface.AudioInput: "In", Solid.AudioInterface.AudioOutput: "Out"} soundcardTypeStr = { Solid.AudioInterface.InternalSoundcard: "Internal", Solid.AudioInterface.UsbSoundcard: "USB3", Solid.AudioInterface.FirewireSoundcard: "FireWire", Solid.AudioInterface.Headset: "Headsets", Solid.AudioInterface.Modem: "Modem"} display = QTreeWidget() display.setAlternatingRowColors(True) display.setHeaderLabels(["Items", "ID", "Drivers", "I / O", "Type"]) display.setColumnWidth(0, 350) display.setColumnWidth(1, 350) display.setColumnWidth(3, 75) # retrieve a list of Solid.Device for this machine deviceList = Solid.Device.allDevices() # filter the list of all devices and display matching results # note that we never create a Solid.AudioInterface object, but # receive one from the 'asDeviceInterface' call for device in deviceList: if device.isDeviceInterface( Solid.DeviceInterface.AudioInterface): audio = device.asDeviceInterface( Solid.DeviceInterface.AudioInterface) devtype = audio.deviceType() devstr = [] for key in audioInterfaceTypeStr: flag = key & devtype if flag: devstr.append(audioInterfaceTypeStr[key]) QTreeWidgetItem(display, [device.product(), audio.name(), audioDriverStr[audio.driver()], "/".join(devstr), soundcardTypeStr[audio.soundcardType()]]) self.dock2.setWidget(display) except: self.dock2.setWidget(QLabel(""" <center style='color:white;'> <h1>:(<br>ERROR: Please, install PyKDE !</h1><br> <br><i> (Sorry, can not use non-Qt Libs). Thanks </i><center>""")) ## dock 3 QLabel('<h1 style="color:white;"> Previews !</h1>', self.dock3).resize( self.dock3.size().width() / 4, 25) self.fileView = QColumnView() self.fileView.updatePreviewWidget.connect(self.play) self.fileView.setToolTip(' Browse and Preview Files ') self.media = None self.model = QDirModel() self.fileView.setModel(self.model) self.dock3.setWidget(self.fileView) # dock4 QLabel('<h1 style="color:white;"> Setup !</h1>', self.dock4).resize( self.dock4.size().width() / 4, 25) self.group4 = QGroupBox() self.group4.setTitle(__doc__) self.combo0 = QComboBox() self.combo0.addItems(['S16_LE', 'S32_LE', 'S16_BE', 'U16_LE', 'U16_BE', 'S24_LE', 'S24_BE', 'U24_LE', 'U24_BE', 'S32_BE', 'U32_LE', 'U32_BE']) self.combo1 = QComboBox() self.combo1.addItems(['1', '-1', '0', '2', '3', '4', '5', '6', '7', '8', '9', '10']) self.combo2 = QComboBox() self.combo2.addItems(['128', '256', '512', '1024', '64', '32', '16']) self.combo3 = QComboBox(self) self.combo3.addItems(['MONO', 'STEREO', 'Surround']) self.combo4 = QComboBox() self.combo4.addItems(['44100', '96000', '48000', '32000', '22050', '16000', '11025', '8000']) self.combo5 = QComboBox(self) self.combo5.addItems(['20', '19', '18', '17', '16', '15', '14', '13', '12', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '0']) self.nepochoose = QCheckBox('Auto-Tag Files using Nepomuk Semantic') self.chckbx0 = QCheckBox('Disable Software based Volume Control') self.chckbx1 = QCheckBox('Output Sound Stereo-to-Mono Downmix') self.chckbx2 = QCheckBox('Add Date and Time MetaData to Sound files') self.chckbx3 = QCheckBox('Add Yourself as the Author Artist of Sound') vboxg4 = QVBoxLayout(self.group4) for each_widget in ( QLabel('<b style="color:white;"> Sound OGG Quality'), self.combo1, QLabel('<b style="color:white;"> Sound Record Format'), self.combo0, QLabel('<b style="color:white;"> Sound KBps '), self.combo2, QLabel('<b style="color:white;"> Sound Channels '), self.combo3, QLabel('<b style="color:white;"> Sound Sample Rate '), self.combo4, QLabel('<b style="color:white;"> Sound Volume'), self.chckbx0, QLabel('<b style="color:white;"> Sound Mix'), self.chckbx1, QLabel('<b style="color:white;"> Sound Meta'), self.chckbx2, QLabel('<b style="color:white;"> Sound Authorship'), self.chckbx3, QLabel('<b style="color:white;"> CPUs Priority'), self.combo5, QLabel('<b style="color:white;">Nepomuk Semantic User Experience'), self.nepochoose): vboxg4.addWidget(each_widget) self.dock4.setWidget(self.group4) # dock 5 QLabel('<h1 style="color:white;"> Voice Changer ! </h1>', self.dock5 ).resize(self.dock5.size().width() / 3, 25) self.group5 = QGroupBox() self.group5.setTitle(__doc__) self.dial = QDial() self.dial.setCursor(QCursor(Qt.OpenHandCursor)) self.di_l = QLabel(self.dial) self.di_l.resize(self.dial.size() / 8) self.dial.sliderPressed.connect(lambda: self.dial.setCursor(QCursor(Qt.ClosedHandCursor))) self.dial.sliderReleased.connect(lambda: self.dial.setCursor(QCursor(Qt.OpenHandCursor))) self.dial.valueChanged.connect(lambda: self.dial.setToolTip(str(self.dial.value()))) self.dial.valueChanged.connect(lambda: self.di_l.setText( '<h1 style="color:white;">{}'.format(self.dial.value()))) self.dial.setValue(0) self.dial.setMinimum(-999) self.dial.setMaximum(999) self.dial.setSingleStep(100) self.dial.setPageStep(100) self.dial.setWrapping(False) self.dial.setNotchesVisible(True) self.defo = QPushButton(QIcon.fromTheme("media-playback-start"), 'Run') self.defo.setMinimumSize(self.defo.size().width(), 50) self.defo.clicked.connect(lambda: self.process3.start( 'play -q -V0 "|rec -q -V0 -n -d -R riaa pitch {} "' .format(self.dial.value()) if int(self.dial.value()) != 0 else 'play -q -V0 "|rec -q -V0 --multi-threaded -n -d -R bend {} "' .format(' 3,2500,3 3,-2500,3 ' * 999))) self.qq = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop') self.qq.clicked.connect(self.process3.kill) self.die = QPushButton(QIcon.fromTheme("process-stop"), 'Kill') self.die.clicked.connect(lambda: call('killall rec', shell=True)) vboxg5 = QVBoxLayout(self.group5) for each_widget in (self.dial, self.defo, self.qq, self.die): vboxg5.addWidget(each_widget) self.dock5.setWidget(self.group5) # configure some widget settings must_be_checked((self.nepochoose, self.chckbx1, self.chckbx2, self.chckbx3)) must_have_tooltip((self.label2, self.label4, self.label6, self.combo0, self.nepochoose, self.combo1, self.combo2, self.combo3, self.combo4, self.combo5, self.chckbx0, self.chckbx1, self.chckbx2, self.chckbx3, self.rec, self.stop, self.defo, self.qq, self.die, self.kill, self.button0, self.button1, self.button5)) must_autofillbackground((self.clock, self.label2, self.label4, self.label6, self.nepochoose, self.chckbx0, self.chckbx1, self.chckbx2, self.chckbx3)) must_glow((self.rec, self.dial, self.combo1)) self.nepomuk_get('testigo') if self.auto is True: self.go()
def __init__(self, parent=None): " Initialize QWidget inside MyMainWindow " super(MyMainWindow, self).__init__(parent) QWidget.__init__(self) self.statusBar().showMessage(" " + __doc__) self.setStyleSheet("QStatusBar{color:grey;}") self.setWindowTitle(__doc__) self.setWindowIcon(QIcon.fromTheme("face-monkey")) self.setFont(QFont("Ubuntu Light", 10)) self.setMaximumSize(QDesktopWidget().screenGeometry().width(), QDesktopWidget().screenGeometry().height()) # directory auto completer self.completer = QCompleter(self) self.dirs = QDirModel(self) self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot) self.completer.setModel(self.dirs) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.completer.setCompletionMode(QCompleter.PopupCompletion) # process self.process = QProcess(self) # self.process.finished.connect(self.on_process_finished) # self.process.error.connect(self.on_process_error) # Proxy support, by reading http_proxy os env variable proxy_url = QUrl(environ.get("http_proxy", "")) QNetworkProxy.setApplicationProxy( QNetworkProxy( QNetworkProxy.HttpProxy if str(proxy_url.scheme()).startswith("http") else QNetworkProxy.Socks5Proxy, proxy_url.host(), proxy_url.port(), proxy_url.userName(), proxy_url.password(), ) ) if "http_proxy" in environ else None print((" INFO: Proxy Auto-Config as " + str(proxy_url))) # basic widgets layouts and set up self.mainwidget = QTabWidget() self.mainwidget.setToolTip(__doc__) self.mainwidget.setMovable(True) self.mainwidget.setTabShape(QTabWidget.Triangular) self.mainwidget.setTabsClosable(True) self.mainwidget.setContextMenuPolicy(Qt.CustomContextMenu) self.mainwidget.tabCloseRequested.connect( lambda: self.mainwidget.setTabPosition(1) if self.mainwidget.tabPosition() == 0 else self.mainwidget.setTabPosition(0) ) self.setCentralWidget(self.mainwidget) self.dock1 = QDockWidget() self.dock2 = QDockWidget() self.dock3 = QDockWidget() for a in (self.dock1, self.dock2, self.dock3): a.setWindowModality(Qt.NonModal) a.setWindowOpacity(0.9) a.setWindowTitle(__doc__ if a.windowTitle() == "" else a.windowTitle()) a.setStyleSheet(" QDockWidget::title{text-align:center;}") a.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.mainwidget.addTab(a, QIcon.fromTheme("face-cool"), str(a.windowTitle()).strip().lower()) # Paleta de colores para pintar transparente self.palette().setBrush(QPalette.Base, Qt.transparent) self.setPalette(self.palette()) self.setAttribute(Qt.WA_OpaquePaintEvent, False) # toolbar and basic actions self.toolbar = QToolBar(self) self.toolbar.setIconSize(QSize(24, 24)) # spacer widget for left self.left_spacer = QWidget(self) self.left_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # spacer widget for right self.right_spacer = QWidget(self) self.right_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) qaqq = QAction(QIcon.fromTheme("application-exit"), "Quit", self) qaqq.setShortcut("Ctrl+Q") qaqq.triggered.connect(exit) qamin = QAction(QIcon.fromTheme("go-down"), "Minimize", self) qamin.triggered.connect(lambda: self.showMinimized()) qamax = QAction(QIcon.fromTheme("go-up"), "Maximize", self) qanor = QAction(QIcon.fromTheme("go-up"), "AutoCenter AutoResize", self) qanor.triggered.connect(self.center) qatim = QAction(QIcon.fromTheme("go-up"), "View Date and Time", self) qatim.triggered.connect(self.timedate) qabug = QAction(QIcon.fromTheme("help-about"), "Report a Problem", self) qabug.triggered.connect( lambda: qabug.setDisabled(True) if not call("xdg-open mailto:" + "*****@*****.**".decode("rot13"), shell=True) else " ERROR " ) qamax.triggered.connect(lambda: self.showMaximized()) qaqt = QAction(QIcon.fromTheme("help-about"), "About Qt", self) qaqt.triggered.connect(lambda: QMessageBox.aboutQt(self)) qaslf = QAction(QIcon.fromTheme("help-about"), "About Self", self) qaslf.triggered.connect( lambda: QMessageBox.about( self.mainwidget, __doc__, "".join( ( __doc__, linesep, "version ", __version__, ", (", __license__, "), by ", __author__, ", ( ", __email__, " )", linesep, ) ), ) ) qasrc = QAction(QIcon.fromTheme("applications-development"), "View Source Code", self) qasrc.triggered.connect(lambda: call("xdg-open " + __file__, shell=1)) qakb = QAction(QIcon.fromTheme("input-keyboard"), "Keyboard Shortcuts", self) qakb.triggered.connect( lambda: QMessageBox.information(self.mainwidget, "Keyboard Shortcuts", " Ctrl+Q = Quit ") ) qapic = QAction(QIcon.fromTheme("camera-photo"), "Take a Screenshot", self) qapic.triggered.connect( lambda: QPixmap.grabWindow(QApplication.desktop().winId()).save( QFileDialog.getSaveFileName( self.mainwidget, " Save Screenshot As ...", path.expanduser("~"), ";;(*.png) PNG", "png" ) ) ) qatb = QAction(QIcon.fromTheme("help-browser"), "Toggle ToolBar", self) qatb.triggered.connect(lambda: self.toolbar.hide() if self.toolbar.isVisible() is True else self.toolbar.show()) qati = QAction(QIcon.fromTheme("help-browser"), "Switch ToolBar Icon Size", self) qati.triggered.connect( lambda: self.toolbar.setIconSize(self.toolbar.iconSize() * 4) if self.toolbar.iconSize().width() * 4 == 24 else self.toolbar.setIconSize(self.toolbar.iconSize() / 4) ) qasb = QAction(QIcon.fromTheme("help-browser"), "Toggle Tabs Bar", self) qasb.triggered.connect( lambda: self.mainwidget.tabBar().hide() if self.mainwidget.tabBar().isVisible() is True else self.mainwidget.tabBar().show() ) qadoc = QAction(QIcon.fromTheme("help-browser"), "On-line Docs", self) qadoc.triggered.connect(lambda: open_new_tab(__url__)) qapy = QAction(QIcon.fromTheme("help-browser"), "About Python", self) qapy.triggered.connect(lambda: open_new_tab("http://python.org/about")) qali = QAction(QIcon.fromTheme("help-browser"), "Read Licence", self) qali.triggered.connect(lambda: open_new_tab(__full_licence__)) qacol = QAction(QIcon.fromTheme("preferences-system"), "Set GUI Colors", self) qacol.triggered.connect( lambda: self.setStyleSheet( """ * { background-color: %s } """ % QColorDialog.getColor().name() ) ) qatit = QAction(QIcon.fromTheme("preferences-system"), "Set the App Window Title", self) qatit.triggered.connect(self.seTitle) qafnt = QAction(QIcon.fromTheme("help-about"), "Set GUI Font", self) if KDE: font = QFont() qafnt.triggered.connect( lambda: self.setStyleSheet("*{font-family: %s}" % font.toString()) if KFontDialog.getFont(font)[0] == QDialog.Accepted else "" ) else: qafnt.triggered.connect( lambda: self.setStyleSheet("*{font-family: %s}" % QFontDialog.getFont()[0].toString()) ) self.toolbar.addWidget(self.left_spacer) self.toolbar.addSeparator() for b in ( qaqq, qamin, qanor, qamax, qasrc, qakb, qacol, qatim, qatb, qati, qasb, qatit, qafnt, qapic, qadoc, qali, qaslf, qaqt, qapy, qabug, ): self.toolbar.addAction(b) self.addToolBar(Qt.TopToolBarArea, self.toolbar) self.toolbar.addSeparator() self.toolbar.addWidget(self.right_spacer) def contextMenuRequested(point): " quick and dirty custom context menu " menu = QMenu() menu.addActions( ( qaqq, qamin, qanor, qamax, qasrc, qakb, qacol, qati, qasb, qatb, qatim, qatit, qafnt, qapic, qadoc, qali, qaslf, qaqt, qapy, qabug, ) ) menu.exec_(self.mapToGlobal(point)) self.mainwidget.customContextMenuRequested.connect(contextMenuRequested) def must_be_checked(widget_list): " widget tuple passed as argument should be checked as ON " for each_widget in widget_list: try: each_widget.setChecked(True) except: pass def must_have_tooltip(widget_list): " widget tuple passed as argument should have tooltips " for each_widget in widget_list: try: each_widget.setToolTip(each_widget.text()) except: each_widget.setToolTip(each_widget.currentText()) finally: each_widget.setCursor(QCursor(Qt.PointingHandCursor)) def must_autofillbackground(widget_list): " widget tuple passed as argument should have filled background " for each_widget in widget_list: try: each_widget.setAutoFillBackground(True) except: pass ####################################################################### self.group1 = QGroupBox() self.group1.setTitle(" Blender ") self.arch = QLabel("<center><b>" + architecture()[0]) self.ost = QLabel("<center><b>" + sys.platform) self.downf = QLineEdit(path.join(path.expanduser("~"), "blender")) self.downf.setCompleter(self.completer) self.borig = QPushButton(QIcon.fromTheme("folder-open"), "Open") self.borig.clicked.connect( lambda: self.downf.setText( path.join( str(QFileDialog.getExistingDirectory(self.mainwidget, "Open a Folder", path.expanduser("~"))), "blender", ) ) ) self.bugs = QPushButton(QIcon.fromTheme("help-faq"), "Report Bugs!") self.bugs.clicked.connect(lambda: open_new_tab("http://www.blender.org/development/report-a-bug")) self.go = QPushButton(QIcon.fromTheme("emblem-favorite"), "Run Blender") self.go.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.go.clicked.connect(self.run) vboxg1 = QVBoxLayout(self.group1) for each_widget in ( self.go, QLabel(""), QLabel('<h3 style="color:white;"> Download Folder Path: </h3>'), self.downf, self.borig, QLabel('<h3 style="color:white;"> Bugs: </h3>'), self.bugs, QLabel('<h3 style="color:white;"> OS: </h3>'), self.ost, QLabel('<h3 style="color:white;"> Architexture: </h3>'), self.arch, QLabel( """<i style="color:white;"> Warning: this builds arent as stable as releases, use at your own risk</i>""" ), ): vboxg1.addWidget(each_widget) self.group2 = QGroupBox() self.group2.setTitle("Options") self.nwfl = QCheckBox("Force opening with borders") self.smll = QCheckBox("Auto Center and Auto Resize the Window") self.lrgf = QCheckBox("Start with the console window open") self.case = QCheckBox("BGE: Run on 50 hertz without dropping frames") self.cnvt = QCheckBox("BGE: Use Vertex Arrays for rendering") self.blnk = QCheckBox("BGE: No Texture Mipmapping") self.spac = QCheckBox("BGE: Linear Texture Mipmap instead of Nearest") self.whit = QCheckBox("Turn Debugging ON") self.tabz = QCheckBox("Enable floating point exceptions") self.sprs = QCheckBox("Disable the crash handler") self.filn = QCheckBox("Enable debug messages from FFmpeg library") self.plac = QCheckBox("Enable debug messages for python") self.plac = QCheckBox("Enable debug messages for the event system") self.plac = QCheckBox("Enable debug messages for event handling") self.plac = QCheckBox("Enable debug messages for the window manager") self.tbs = QComboBox(self.group2) self.tbs.addItems(["0", "1", "2", "3"]) self.nice = QComboBox(self.group2) self.nice.addItems(["0", "1", "2", "3"]) vboxg2 = QVBoxLayout(self.group2) for each_widget in ( self.nwfl, self.smll, self.lrgf, self.case, self.cnvt, self.blnk, self.spac, self.whit, self.tabz, self.sprs, self.filn, QLabel("BLAH BLAH BLAH"), self.tbs, QLabel("BLAH BLAH BLAH"), self.nice, ): vboxg2.addWidget(each_widget) group3 = QGroupBox() group3.setTitle("Even More Options") self.plai = QCheckBox("Enable debug messages from libmv library") self.nocr = QCheckBox("Skip reading the startup.blend in the home dir") self.ridt = QCheckBox("Set BLENDER_SYSTEM_DATAFILES environment var") self.nocm = QCheckBox("Set BLENDER_SYSTEM_SCRIPTS environment var") self.rdif = QCheckBox("Set BLENDER_SYSTEM_PYTHON environment var") self.clip = QCheckBox("Disable joystick support") self.noti = QCheckBox("Disable GLSL shading") self.pret = QCheckBox("Force sound system to None") self.lolz = QCheckBox("Disable automatic python script execution") self.odif = QCheckBox("Run blender with an interactive console") self.plac = QCheckBox("Enable all debug messages, excludes libmv") self.plac = QCheckBox("Enable time profiling for background jobs") self.plac = QCheckBox("Do not use native pixel size for high res") self.wdth = QComboBox(group3) self.wdth.addItems(["OPENAL", "NULL", "SDL", "JACK"]) self.bcknd = QComboBox(group3) self.bcknd.addItems(["0", "5", "10", "15", "20"]) vboxg3 = QVBoxLayout(group3) for each_widget in ( self.plai, self.nocr, self.ridt, self.nocm, self.rdif, self.pret, self.clip, self.noti, self.lolz, self.odif, self.plac, QLabel('<b style="color:white">Force sound system to specific device'), self.wdth, QLabel('<b style="color:white">CPU Priority'), self.bcknd, ): vboxg3.addWidget(each_widget) # dock 2 the waterfall scrollable = QScrollArea() scrollable.setWidget(QLabel("".join((urlopen("http://builder.blender.org/waterfall").readlines()[23:])))) self.dock2.setWidget(scrollable) # dock 3 the build status stats = QLabel( "<center>" + "".join((urlopen("http://builder.blender.org/one_line_per_build").readlines()[23:])).strip() + "</center>" ) self.dock3.setWidget(stats) # configure some widget settings must_be_checked((self.nwfl, self.smll, self.lrgf, self.clip, self.cnvt, self.plai, self.noti)) must_have_tooltip( ( self.plai, self.nocr, self.ridt, self.nocm, self.rdif, self.pret, self.clip, self.noti, self.lolz, self.odif, self.plac, self.wdth, self.bcknd, self.nwfl, self.smll, self.lrgf, self.case, self.cnvt, self.blnk, self.spac, self.whit, self.tabz, self.sprs, self.filn, self.tbs, self.nice, self.arch, self.ost, ) ) must_autofillbackground( ( self.plai, self.nocr, self.ridt, self.nocm, self.rdif, self.pret, self.clip, self.noti, self.lolz, self.odif, self.plac, self.wdth, self.bcknd, self.nwfl, self.smll, self.lrgf, self.case, self.cnvt, self.blnk, self.spac, self.whit, self.tabz, self.sprs, self.filn, self.tbs, self.nice, scrollable, stats, self.arch, self.ost, ) ) container = QWidget() hbox = QHBoxLayout(container) for each_widget in (self.group2, self.group1, group3): hbox.addWidget(each_widget) self.dock1.setWidget(container)
def __init__(self, parent=None): " Initialize QWidget inside MyMainWindow " super(MyMainWindow, self).__init__(parent) QWidget.__init__(self) self.statusBar().showMessage(" {}".format(__doc__)) self.setStyleSheet("QStatusBar{color:grey;}") self.setWindowTitle(__doc__) self.setWindowIcon(QIcon.fromTheme("face-monkey")) self.setFont(QFont("Ubuntu Light", 10)) self.setMaximumSize(QDesktopWidget().screenGeometry().width(), QDesktopWidget().screenGeometry().height()) # directory auto completer self.completer = QCompleter(self) self.dirs = QDirModel(self) self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot) self.completer.setModel(self.dirs) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.completer.setCompletionMode(QCompleter.PopupCompletion) # Proxy support, by reading http_proxy os env variable proxy_url = QUrl(environ.get("http_proxy", "")) QNetworkProxy.setApplicationProxy( QNetworkProxy( QNetworkProxy.HttpProxy if str(proxy_url.scheme()).startswith("http") else QNetworkProxy.Socks5Proxy, proxy_url.host(), proxy_url.port(), proxy_url.userName(), proxy_url.password(), ) ) if "http_proxy" in environ else None print((" INFO: Proxy Auto-Config as " + str(proxy_url))) # basic widgets layouts and set up self.mainwidget = QTabWidget() self.mainwidget.setToolTip(__doc__) self.mainwidget.setContextMenuPolicy(Qt.CustomContextMenu) self.mainwidget.tabCloseRequested.connect(lambda: self.mainwidget.setTabPosition(randint(0, 3))) # if self.mainwidget.tabPosition() == 0 # else self.mainwidget.setTabPosition(0)) self.mainwidget.setStyleSheet("QTabBar{color:white;font-weight:bold;}") self.mainwidget.setTabBar(TabBar(self)) self.mainwidget.setMovable(True) self.mainwidget.setTabsClosable(True) self.mainwidget.setTabShape(QTabWidget.Triangular) self.setCentralWidget(self.mainwidget) self.dock1 = QDockWidget() self.dock2 = QDockWidget() self.dock3 = QDockWidget() for a in (self.dock1, self.dock2, self.dock3): a.setWindowModality(Qt.NonModal) a.setWindowOpacity(0.9) a.setWindowTitle(__doc__ if a.windowTitle() == "" else a.windowTitle()) a.setStyleSheet(" QDockWidget::title{text-align:center;}") self.mainwidget.addTab(a, QIcon.fromTheme("face-smile"), "Double Click Me") # Paleta de colores para pintar transparente self.palette().setBrush(QPalette.Base, Qt.transparent) self.setPalette(self.palette()) self.setAttribute(Qt.WA_OpaquePaintEvent, False) # toolbar and basic actions self.toolbar = QToolBar(self) self.toolbar.setIconSize(QSize(24, 24)) # spacer widget for left self.left_spacer = QWidget(self) self.left_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # spacer widget for right self.right_spacer = QWidget(self) self.right_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) qaqq = QAction(QIcon.fromTheme("application-exit"), "Quit", self) qaqq.setShortcut("Ctrl+Q") qaqq.triggered.connect(exit) qamin = QAction(QIcon.fromTheme("go-down"), "Minimize", self) qamin.triggered.connect(lambda: self.showMinimized()) qamax = QAction(QIcon.fromTheme("go-up"), "Maximize", self) qanor = QAction(QIcon.fromTheme("view-fullscreen"), "AutoCenter AutoResize", self) qanor.triggered.connect(self.center) qatim = QAction(QIcon.fromTheme("mail-signed-verified"), "View Date and Time", self) qatim.triggered.connect(self.timedate) qabug = QAction(QIcon.fromTheme("help-about"), "Report a Problem", self) qabug.triggered.connect( lambda: qabug.setDisabled(True) if not call("xdg-open mailto:" + "*****@*****.**".decode("rot13"), shell=True) else " ERROR " ) qamax.triggered.connect(lambda: self.showMaximized()) qaqt = QAction(QIcon.fromTheme("help-about"), "About Qt", self) qaqt.triggered.connect(lambda: QMessageBox.aboutQt(self)) qakde = QAction(QIcon.fromTheme("help-about"), "About KDE", self) if KDE: qakde.triggered.connect(KHelpMenu(self, "", False).aboutKDE) qaslf = QAction(QIcon.fromTheme("help-about"), "About Self", self) if KDE: qaslf.triggered.connect(KAboutApplicationDialog(aboutData, self).exec_) else: qaslf.triggered.connect( lambda: QMessageBox.about( self.mainwidget, __doc__, "".join( ( __doc__, linesep, "version ", __version__, ", (", __license__, "), by ", __author__, ", ( ", __email__, " )", linesep, ) ), ) ) qafnt = QAction(QIcon.fromTheme("tools-check-spelling"), "Set GUI Font", self) if KDE: font = QFont() qafnt.triggered.connect( lambda: self.setStyleSheet( "".join(("*{font-family:", str(font.toString()), "}")) if KFontDialog.getFont(font)[0] == QDialog.Accepted else "" ) ) else: qafnt.triggered.connect( lambda: self.setStyleSheet("".join(("*{font-family:", str(QFontDialog.getFont()[0].toString()), "}"))) ) qasrc = QAction(QIcon.fromTheme("applications-development"), "View Source Code", self) qasrc.triggered.connect(lambda: call("xdg-open {}".format(__file__), 1)) qakb = QAction(QIcon.fromTheme("input-keyboard"), "Keyboard Shortcuts", self) qakb.triggered.connect( lambda: QMessageBox.information(self.mainwidget, "Keyboard Shortcuts", " Ctrl+Q = Quit ") ) qapic = QAction(QIcon.fromTheme("camera-photo"), "Take a Screenshot", self) qapic.triggered.connect( lambda: QPixmap.grabWindow(QApplication.desktop().winId()).save( QFileDialog.getSaveFileName( self.mainwidget, " Save Screenshot As ...", path.expanduser("~"), ";;(*.png) PNG", "png" ) ) ) qatb = QAction(QIcon.fromTheme("go-top"), "Toggle ToolBar", self) qatb.triggered.connect(lambda: self.toolbar.hide() if self.toolbar.isVisible() is True else self.toolbar.show()) qati = QAction(QIcon.fromTheme("help-browser"), "Switch ToolBar Icon Size", self) qati.triggered.connect( lambda: self.toolbar.setIconSize(self.toolbar.iconSize() * 4) if self.toolbar.iconSize().width() * 4 == 24 else self.toolbar.setIconSize(self.toolbar.iconSize() / 4) ) qasb = QAction(QIcon.fromTheme("zoom-in"), "Toggle Tabs Bar", self) qasb.triggered.connect( lambda: self.mainwidget.tabBar().hide() if self.mainwidget.tabBar().isVisible() is True else self.mainwidget.tabBar().show() ) qadoc = QAction(QIcon.fromTheme("help-browser"), "On-line Docs", self) qadoc.triggered.connect(lambda: open_new_tab(__url__)) qapy = QAction(QIcon.fromTheme("help-about"), "About Python", self) qapy.triggered.connect(lambda: open_new_tab("http://python.org/about")) qali = QAction(QIcon.fromTheme("help-browser"), "Read Licence", self) qali.triggered.connect(lambda: open_new_tab(__full_licence__)) qacol = QAction(QIcon.fromTheme("preferences-system"), "Set GUI Colors", self) if KDE: color = QColor() qacol.triggered.connect( lambda: self.setStyleSheet("".join(("* { background-color: ", str(color.name()), "}"))) if KColorDialog.getColor(color, self) else "" ) else: qacol.triggered.connect( lambda: self.setStyleSheet( "".join((" * { background-color: ", str(QColorDialog.getColor().name()), " } ")) ) ) qatit = QAction(QIcon.fromTheme("preferences-system"), "Set the App Window Title", self) qatit.triggered.connect(self.seTitle) self.toolbar.addWidget(self.left_spacer) self.toolbar.addSeparator() for b in ( qaqq, qamin, qanor, qamax, qasrc, qakb, qacol, qatim, qatb, qafnt, qati, qasb, qatit, qapic, qadoc, qali, qaslf, qaqt, qakde, qapy, qabug, ): self.toolbar.addAction(b) self.addToolBar(Qt.TopToolBarArea, self.toolbar) self.toolbar.addSeparator() self.toolbar.addWidget(self.right_spacer) # define the menu menu = self.menuBar() # File menu items menu.addMenu("&File").addActions((qaqq,)) menu.addMenu("&Window").addActions((qamax, qanor, qamin)) # Settings menu menu.addMenu("&Settings").addActions((qasrc, qacol, qafnt, qatim, qatb, qati, qasb, qapic)) # Help menu items menu.addMenu("&Help").addActions((qadoc, qakb, qabug, qali, qaqt, qakde, qapy, qaslf)) # Tray Icon tray = QSystemTrayIcon(QIcon.fromTheme("face-devilish"), self) tray.setToolTip(__doc__) traymenu = QMenu() traymenu.addActions((qamax, qanor, qamin, qaqq)) tray.setContextMenu(traymenu) tray.show() def contextMenuRequested(point): " quick and dirty custom context menu " menu = QMenu() menu.addActions( ( qaqq, qamin, qanor, qamax, qasrc, qakb, qacol, qafnt, qati, qasb, qatb, qatim, qatit, qapic, qadoc, qali, qaslf, qaqt, qakde, qapy, qabug, ) ) menu.exec_(self.mapToGlobal(point)) self.mainwidget.customContextMenuRequested.connect(contextMenuRequested) def must_be_checked(widget_list): " widget tuple passed as argument should be checked as ON " for each_widget in widget_list: try: each_widget.setChecked(True) except: pass def must_have_tooltip(widget_list): " widget tuple passed as argument should have tooltips " for each_widget in widget_list: try: each_widget.setToolTip(each_widget.text()) except: each_widget.setToolTip(each_widget.currentText()) finally: each_widget.setCursor(QCursor(Qt.PointingHandCursor)) def must_autofillbackground(widget_list): " widget tuple passed as argument should have filled background " for each_widget in widget_list: try: each_widget.setAutoFillBackground(True) except: pass def must_glow(widget_list): " apply an glow effect to the widget " for glow, each_widget in enumerate(widget_list): try: if each_widget.graphicsEffect() is None: glow = QGraphicsDropShadowEffect(self) glow.setOffset(0) glow.setBlurRadius(99) glow.setColor(QColor(99, 255, 255)) each_widget.setGraphicsEffect(glow) # glow.setEnabled(False) try: each_widget.clicked.connect( lambda: each_widget.graphicsEffect().setEnabled(True) if each_widget.graphicsEffect().isEnabled() is False else each_widget.graphicsEffect().setEnabled(False) ) except: each_widget.sliderPressed.connect( lambda: each_widget.graphicsEffect().setEnabled(True) if each_widget.graphicsEffect().isEnabled() is False else each_widget.graphicsEffect().setEnabled(False) ) except: pass ####################################################################### self.group1 = QGroupBox() self.group1.setTitle(__doc__) self.frmt = QComboBox(self.group1) self.frmt.addItems(["blah ", "blah blah", "blah blah blah"]) self.file1 = QLineEdit() self.file1.setPlaceholderText("/full/path/to/one_file.py") self.file1.setCompleter(self.completer) self.borig = QPushButton(QIcon.fromTheme("folder-open"), "Open") vboxg1 = QVBoxLayout(self.group1) for each_widget in ( QLabel('<b style="color:white;">some comment'), self.file1, self.borig, QLabel('<b style="color:white;">Lorem Impsum'), self.frmt, ): vboxg1.addWidget(each_widget) self.group2 = QGroupBox() self.group2.setTitle(__doc__) self.nwfl = QCheckBox("Be Awesome") self.smll = QCheckBox("Solve the Squaring of the Circle") self.lrgf = QCheckBox("Im just a QCheckBox") self.case = QCheckBox("Use Quantum Processing") vboxg2 = QVBoxLayout(self.group2) for each_widget in (self.nwfl, self.smll, self.lrgf, self.case): vboxg2.addWidget(each_widget) group3 = QGroupBox() group3.setTitle(__doc__) self.plai = QCheckBox("May the Force be with You") self.nocr = QCheckBox("Im just a Place Holder") self.ridt = QCheckBox("Lorem Impsum") self.nocm = QCheckBox("Divide by Zero") vboxg3 = QVBoxLayout(group3) for each_widget in (self.plai, self.nocr, self.ridt, self.nocm): vboxg3.addWidget(each_widget) container = QWidget() hbox = QHBoxLayout(container) for each_widget in (self.group2, self.group1, group3): hbox.addWidget(each_widget) self.dock1.setWidget(container) # dock 2 self.dock2.setWidget(QPlainTextEdit()) # dock 3 self.dock3.setWidget(QCalendarWidget()) # configure some widget settings must_be_checked((self.nwfl, self.smll, self.lrgf, self.plai)) must_have_tooltip((self.plai, self.nocr, self.ridt, self.nocm, self.nwfl, self.smll, self.lrgf, self.case)) must_autofillbackground( (self.plai, self.nocr, self.ridt, self.nocm, self.nwfl, self.smll, self.lrgf, self.case) ) must_glow((self.plai, self.nocr, self.ridt, self.nocm, self.nwfl))