Esempio n. 1
0
    def icon(self):
        """
        Returns the most fitting icon for the file
        @return: the icon
        @rtype: QIcon
        """
        if self.isDirectory:
            return QIcon.fromTheme("folder")
        else:
            ext = os.path.splitext(self.name)[-1][1:].lower()
            theme = None

            if ext in ['exe', 'dll', 'bat', 'dylib', 'sh', 'run']:
                theme = "application-x-executable"
            elif ext in ['mp3', 'ogg', 'wav', 'wma', 'flac']:
                theme = "audio-x-generic"
            elif ext in ['ttf', 'woff', 'eot']:
                theme = "font-x-generic"
            elif ext in ['png', 'jpg', 'jpeg', 'gif', 'svg', ' bmp']:
                theme = "image-x-generic"
            elif ext in [
                    'avi', 'wmv', 'qt', 'mkv', 'flv', 'mpg', 'ram', 'mov',
                    'mp4'
            ]:
                theme = "video-x-generic"

            if not theme:
                theme = "text-x-generic"

            return QIcon.fromTheme(theme)
Esempio n. 2
0
 def __init__(self, schid, cgid, dbid, name, channel, groups, parent=None):
     try:
         super(QDialog, self).__init__(parent)
         setupUi(self, path.join(getPluginPath(), "scripts", "channelGroupChanger", "channelGroupSelect.ui"))
         self.setAttribute(Qt.WA_DeleteOnClose)
         self.setWindowTitle("%s | %i"%(name,channel))
         cache = False
         try:
             icons = IconPack.current()
             icons.open()
             cache = ServerCache(schid)
         except: from traceback import format_exc;ts3lib.logMessage("Could not load icons: {}".format(format_exc()), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)
         # self.channelGroups.addItems(list(groups.values()))
         self.channelGroups.clear()
         for key,p in groups.items():
             try:
                 item = QListWidgetItem(self.channelGroups)
                 item.setText(p[0])
                 item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                 item.setCheckState(Qt.Checked if key == cgid else Qt.Unchecked)
                 item.setData(Qt.UserRole, key)
                 if (cache):
                     try:
                         if p[1] == 0: continue;
                         elif p[1] in range(100, 700, 100):
                             item.setIcon(QIcon(IconPack.icon(icons,"group_{}".format(p[1]))))
                         else: item.setIcon(QIcon(ServerCache.icon(cache,p[1]&0xFFFFFFFF)))
                     except: from traceback import format_exc;ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)
             except: from traceback import format_exc;ts3lib.logMessage("Could set icon: {}".format(format_exc()), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)
         icons.close()
         # self.channelGroups.sortItems()
         self.channelGroups.connect("itemChanged(QListWidgetItem*)", self.onSelectedChannelGroupChangedEvent)
         self.schid = schid;self.dbid = dbid;self.channel = channel
     except: from traceback import format_exc;ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0);pass
Esempio n. 3
0
    def icon(self):
        """
        Returns the most fitting icon for the file
        @return: the icon
        @rtype: QIcon
        """
        if self.isDirectory:
            return QIcon.fromTheme("folder")
        else:
            ext = os.path.splitext(self.name)[-1][1:].lower()
            theme = None

            if ext in ['exe', 'dll', 'bat', 'dylib', 'sh', 'run']:
                theme = "application-x-executable"
            elif ext in ['mp3', 'ogg', 'wav', 'wma', 'flac']:
                theme = "audio-x-generic"
            elif ext in ['ttf', 'woff', 'eot']:
                theme = "font-x-generic"
            elif ext in ['png', 'jpg', 'jpeg', 'gif', 'svg', ' bmp']:
                theme = "image-x-generic"
            elif ext in ['avi', 'wmv', 'qt', 'mkv', 'flv', 'mpg', 'ram', 'mov',
                         'mp4']:
                theme = "video-x-generic"

            if not theme:
                theme = "text-x-generic"

            return QIcon.fromTheme(theme)
Esempio n. 4
0
    def setupList(self):
        self.pluginsTable.clear()
        self.pluginsTable.setRowCount(len(self.host.plugins))

        try:
            ico = ts3client.IconPack.current()
            ico.open()
        except Exception as e:
            ico = None
            ts3print(self._tr("Error loading iconpack: {exception}").
                     format(exception=e), ts3defines.LogLevel.LogLevel_ERROR,
                     "pyTSon.ConfigurationDialog.setupList", 0)

        row = 0
        diffapi = self.cfg.getboolean("general", "differentApi",
                                      fallback=False)
        for key, p in self.host.plugins.items():
            if diffapi or p.apiVersion == pytson.getCurrentApiVersion():
                item = QTableWidgetItem(p.name)
                item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable |
                              Qt.ItemIsEnabled)
                item.setCheckState(Qt.Checked if key in self.host.active
                                   else Qt.Unchecked)
                item.setData(Qt.UserRole, key)
                self.pluginsTable.setItem(row, 0, item)

                if p.offersConfigure:
                    setbutton = QToolButton()
                    setbutton.connect("clicked()", lambda n=p.name:
                                      self.onSettingsButtonClicked(n))
                    setbutton.setToolTip(self._tr("Configure"))
                    if ico:
                        setbutton.setIcon(QIcon(ico.icon("SETTINGS")))
                    self.pluginsTable.setCellWidget(row, 1, setbutton)

                    if p.name not in self.host.active:
                        setbutton.setEnabled(False)

                rembutton = QToolButton()
                if ico:
                    rembutton.setIcon(QIcon(ico.icon("DELETE")))
                rembutton.connect("clicked()", lambda n=p.name:
                                  self.onRemoveButtonClicked(n))
                rembutton.setToolTip(self._tr("Remove"))
                self.pluginsTable.setCellWidget(row, 2, rembutton)

                row += 1

        if ico:
            ico.close()

        self.pluginsTable.setRowCount(row)
        self.pluginsTable.sortItems(0)
Esempio n. 5
0
 def setupTable(self):
     try:
         self.tbl_members.clearContents()
         self.tbl_members.setRowCount(0)
         cache = ts3client.ServerCache(self.schid)
         (err, suid) = ts3lib.getServerVariable(self.schid, ts3defines.VirtualServerProperties.VIRTUALSERVER_UNIQUE_IDENTIFIER)
         q = self.execSQL("SELECT * FROM '{}|{}'".format(suid, self.cid))
         while q.next():
             pos = self.tbl_members.rowCount
             if PluginHost.cfg.getboolean("general", "verbose"): print(pos)
             self.tbl_members.insertRow(pos)
             self.tbl_members.setItem(pos, 0, QTableWidgetItem(datetime.utcfromtimestamp(q.value("timestamp")).strftime('%Y-%m-%d %H:%M:%S')))
             self.tbl_members.setItem(pos, 1, QTableWidgetItem(q.value("name")))
             self.tbl_members.setItem(pos, 2, QTableWidgetItem(q.value("uid")))
             self.tbl_members.setItem(pos, 3, QTableWidgetItem(str(q.value("dbid"))))
             box = QComboBox()
             box.connect("currentIndexChanged(int index)", self.currentIndexChanged)
             i = 0
             for cgroup in self.cgroups:
                 icon = QIcon(cache.icon(self.cgroups[cgroup]["icon"]))
                 text = "{} ({})".format(self.cgroups[cgroup]["name"], cgroup)
                 box.addItem(icon, text)
                 box.setItemData(i, cgroup)
                 if cgroup == q.value("cgid"): box.setCurrentIndex(i)
                 i += 1
             self.tbl_members.setCellWidget(pos, 4, box)
             self.tbl_members.setItem(pos, 5, QTableWidgetItem("{} ({})".format(q.value("invokername"), q.value("INVOKERUID"))))
     except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)
Esempio n. 6
0
 def getButton(self, name, iconname, line, action):
     size = QSize(16, 16)
     button = buttons.PyPushButton()
     icon = QIcon(iconname)
     icon.actualSize(size)
     button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
     button.setMaximumSize(size)
     button.setMinimumSize(size)
     button.text = ""
     button.name = name
     button.setIcon(icon)
     button.setFlat(True)
     button.setEnabled(False)
     button.connect('clicked()', action)
     line.buttons.append(button)
     return button
Esempio n. 7
0
 def badgeItem(self, badge, alt=False):
     item = QListWidgetItem(self.badges[badge]["name"])
     item.setData(Qt.UserRole, badge)
     item.setToolTip(self.badges[badge]["description"])
     item.setIcon(
         QIcon("{}\\{}{}".format(self.icons, self.badges[badge]["filename"],
                                 "_details" if alt else "")))
     return item
Esempio n. 8
0
    def __init__(self,
                 script,
                 schid,
                 clid,
                 uid,
                 name,
                 ip,
                 mytsid,
                 hwid,
                 servertype,
                 parent=None):
        try:
            super(QDialog, self).__init__(parent)
            setupUi(self, "%s/ban.ui" % script.path)
            try:
                icons = IconPack.current()
                icons.open()
                self.icon_warning = QIcon(icons.icon("WARNING"))
            except:
                pass
            self.setAttribute(Qt.WA_DeleteOnClose)
            self.cfg = script.cfg
            self.ini = script.ini
            self.schid = schid
            self.templates = script.templates
            self.whitelist = script.whitelist
            self.prefix = script.prefix
            self.suffix = script.suffix
            self.name = script.name
            if script.cfg.getboolean("last", "expanded"):
                self.disableReasons(True)
            height = script.cfg.get("last", "height")
            if height: self.resize(self.width, int(height))
            else: self.disableReasons()
            alt = script.cfg.getboolean("last", "alternate")
            if alt: self.chk_alternate.setChecked(True)
            dblclick = script.cfg.getboolean("last", "ban on doubleclick")
            if dblclick: self.chk_doubleclick.setChecked(True)
            for reason in script.templates:
                self.lst_reasons.addItem(reason)
                self.box_reason.addItem(reason)
            self.box_reason.setEditText(script.cfg.get(
                "last", "reason"))  # setItemText(0, )
            """
            ipREX = QRegExp("[\w+\/]{27}=")
            ipREX.setCaseSensitivity(Qt.CaseInsensitive)
            ipREX.setPatternSyntax(QRegExp.RegExp)

            regValidator = QRegExpValidator(ipREX,0)
            self.txt_ip.setValidator(regValidator)
            """
            # self.txt_ip.setInputMask( "000.000.000.000" )

            self.setup(script, schid, clid, uid, name, ip, mytsid, hwid,
                       servertype)
        except:
            ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                              "pyTSon", 0)
Esempio n. 9
0
 def badgeItem(self, badge, alt=False, ext=False):
     try:
         lst = self.extbadges if ext else self.badges
         item = QListWidgetItem(lst[badge]["name"])
         item.setData(Qt.UserRole, badge)
         try: item.setToolTip(lst[badge]["description"])
         except: pass
         try: item.setIcon(QIcon("{}\\{}{}".format(self.icons, lst[badge]["filename"],"_details" if alt else "")))
         except: pass
         return item
     except: ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)
Esempio n. 10
0
 def badgeItem(self, badge, alt=False, ext=False):
     try:
         lst = self.extbadges if ext else self.badges
         item = QListWidgetItem(lst[badge]["name"])
         item.setData(Qt.UserRole, badge)
         path = "{}\\{}".format(self.icons, lst[badge]["filename"])
         item.setToolTip(
             '{}<br/><center><img width="64" height="64" src="{}_details">'.
             format(lst[badge]["description"], path))
         item.setIcon(QIcon("{}{}".format(path, "_details" if alt else "")))
         return item
     except:
         ts3lib.logMessage(format_exc(), ts3defines.LogLevel.LogLevel_ERROR,
                           "pyTSon", 0)
         pass
Esempio n. 11
0
def setIcon(obj, iconpack, pluginicons=None):
    """
    Sets the icon of a QWidget (if it has a property Icon) to an icon in the
    iconpack represented by a variable which is acquired by the property
    'pytsonicon' of the object.
    If the property instead contains a string formated as
    "octicons:filename.png", the icon is set to filename.png of the octicons
    pack.
    If no such property is available, nothing is done.
    @param obj: the widget
    @type obj: QWidget
    @param iconpack: the iconpack
    @type iconpack: ts3client.IconPack
    @param pluginicons: callable which gets a string and either returns the
    path to the image file or returns a QPixmap to set the icon property to;
    defaults to None
    @type pluginicons: Callable(str) -> str or QIcon
    """
    if iconpack:
        if hasattr(obj, "setIcon") and hasattr(obj, "pytsonicon"):
            var = obj.pytsonicon

            if var.startswith("octicons:"):
                fname = os.path.join(pytson.getPluginPath("ressources",
                                     "octicons", var.split(":")[1]))
                if os.path.isfile(fname):
                    obj.setIcon(QIcon(fname))
            elif var.startswith("plugin:"):
                if pluginicons:
                    ico = pluginicons(var.split(":")[1])
                    if type(ico) is str:
                        obj.setIcon(QIcon(ico))
                    else:
                        obj.setIcon(ico)
            else:
                obj.setIcon(QIcon(iconpack.icon(var)))
Esempio n. 12
0
 def getButton(self, name, iconname, line, action):
     size = QSize(20, 20)
     button = buttons.PyPushButton()
     icon = QIcon(QPixmap(iconname).scaled(size))
     button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
     button.setMaximumSize(size)
     button.setMinimumSize(size)
     button.text = ""
     button.name = name
     button.setIcon(icon)
     button.setFlat(True)
     if action != None:
         button.connect('clicked()', action)
     if line != None:
         button.setEnabled(False)
         line.buttons.append(button)
     return button
Esempio n. 13
0
    def __init__(self, schid, cid, password='', path='/', parent=None, *,
                 staticpath=False, readonly=False, downloaddir=None,
                 iconpack=None):
        """
        Instantiates a new object.
        @param schid: the id of the serverconnection handler
        @type schid: int
        @param cid: the id of the channel
        @type cid: int
        @param password: password to the channel, defaults to an empty string
        @type password: str
        @param path: path to display, defaults to the root path
        @type path: str
        @param parent: parent of the dialog; optional keyword arg;
        defaults to None
        @type parent: QWidget
        @param staticpath: if set to True, the initial path can't be
        changed by the user; optional keyword arg; defaults to False
        @type staticpath: bool
        @param readonly: if set to True, the user can't download, upload
        or delete files, or create new directories; optional keyword arg;
        defaults to False
        @type readonly: bool
        @param downloaddir: directory to download files to; optional keyword
        arg; defaults to None; if set to None, the TS3 client's download
        directory is used
        @type downloaddir: str
        @param iconpack: iconpack to load icons from; optional keyword arg;
        defaults to None; if set to None, the current iconpack is used
        @type iconpack: ts3client.IconPack
        """
        super(QDialog, self).__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)

        iconpackopened = False
        if not iconpack:
            try:
                iconpack = ts3client.IconPack.current()
                iconpack.open()
                iconpackopened = True
            except Exception as e:
                self.delete()
                raise e

        try:
            setupUi(self, pytson.getPluginPath("ressources", "filebrowser.ui"),
                    iconpack=iconpack)

            self.statusbar = SmartStatusBar(self)
            self.layout().addWidget(self.statusbar)
            self.statusbar.hide()
        except Exception as e:
            self.delete()
            raise e

        err, cname = ts3lib.getChannelVariableAsString(schid, cid,
                                                       ChannelProperties.
                                                       CHANNEL_NAME)

        if err == ERROR_ok:
            self.setWindowTitle(self._tr("File Browser - {cname}").format(
                                cname=cname))
        else:
            self.setWindowTitle(self._tr("File Browser"))

        self.schid = schid
        self.cid = cid
        self.password = password
        self.path = None

        self.staticpath = staticpath
        self.readonly = readonly

        self.createretcode = None
        self.delretcode = None

        if not self.readonly and not downloaddir:
            cfg = ts3client.Config()
            q = cfg.query("SELECT value FROM filetransfer "
                          "WHERE key='DownloadDir'")
            del cfg

            if q.next():
                self.downloaddir = q.value("value")
            else:
                self.delete()
                raise Exception("Error getting DownloadDir from config")
        else:
            self.downloaddir = downloaddir

        if not self.readonly:
            menu = self.menu = QMenu(self)

            self.openAction = menu.addAction(QIcon(iconpack.icon("FILE_UP")),
                                             self._tr("Open"))
            self.openAction.connect("triggered()",
                                    self.on_openAction_triggered)

            self.downAction = menu.addAction(QIcon(iconpack.icon("DOWN")),
                                             self._tr("Download"))
            self.downAction.connect("triggered()", self.downloadFiles)
            self.renameAction = menu.addAction(QIcon(iconpack.icon("EDIT")),
                                               self._tr("Rename"))
            self.renameAction.connect("triggered()",
                                      self.on_renameAction_triggered)
            self.copyAction = menu.addAction(QIcon(iconpack.icon("COPY")),
                                             self._tr("Copy URL"))
            self.copyAction.connect("triggered()",
                                    self.on_copyAction_triggered)
            self.delAction = menu.addAction(QIcon(iconpack.icon("DELETE")),
                                            self._tr("Delete"))
            self.delAction.connect("triggered()", self.deleteFiles)

            self.upAction = menu.addAction(QIcon(iconpack.icon("UP")),
                                           self._tr("Upload files"))
            self.upAction.connect("triggered()", self.uploadFiles)
            self.createAction = menu.addAction(QIcon.fromTheme("folder"),
                                               self._tr("Create Folder"))
            self.createAction.connect("triggered()", self.createFolder)
            self.refreshAction = menu.addAction(QIcon(iconpack.icon(
                                                "FILE_REFRESH")),
                                                self._tr("Refresh"))
            self.refreshAction.connect("triggered()", self.refresh)

            self.allactions = [self.openAction, self.downAction,
                               self.renameAction, self.copyAction,
                               self.delAction, self.upAction,
                               self.createAction, self.refreshAction]

        self.collector = FileCollector(schid, cid, password, self.downloaddir)
        self.collector.collectionFinished.connect(self._startDownload)
        self.collector.collectionError.connect(self.showError)

        self.fileDoubleClicked = Signal()
        self.contextMenuRequested = Signal()

        self.transdlg = None

        self.listmodel = FileListModel(schid, cid, password, self,
                                       readonly=readonly)
        self.listmodel.pathChanged.connect(self.onPathChanged)
        self.listmodel.error.connect(self.showError)

        self.proxy = QSortFilterProxyModel(self)
        self.proxy.setSortRole(Qt.UserRole)
        self.proxy.setSortCaseSensitivity(Qt.CaseInsensitive)
        self.proxy.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.proxy.setSourceModel(self.listmodel)

        self.listmodel.path = path

        self._adjustUi()

        if iconpackopened:
            iconpack.close()

        PluginHost.registerCallbackProxy(self)
Esempio n. 14
0
    def __init__(self,
                 schid,
                 cid,
                 password='',
                 path='/',
                 parent=None,
                 *,
                 staticpath=False,
                 readonly=False,
                 downloaddir=None,
                 iconpack=None):
        """
        Instantiates a new object.
        @param schid: the id of the serverconnection handler
        @type schid: int
        @param cid: the id of the channel
        @type cid: int
        @param password: password to the channel, defaults to an empty string
        @type password: str
        @param path: path to display, defaults to the root path
        @type path: str
        @param parent: parent of the dialog; optional keyword arg;
        defaults to None
        @type parent: QWidget
        @param staticpath: if set to True, the initial path can't be
        changed by the user; optional keyword arg; defaults to False
        @type staticpath: bool
        @param readonly: if set to True, the user can't download, upload
        or delete files, or create new directories; optional keyword arg;
        defaults to False
        @type readonly: bool
        @param downloaddir: directory to download files to; optional keyword
        arg; defaults to None; if set to None, the TS3 client's download
        directory is used
        @type downloaddir: str
        @param iconpack: iconpack to load icons from; optional keyword arg;
        defaults to None; if set to None, the current iconpack is used
        @type iconpack: ts3client.IconPack
        """
        super(QDialog, self).__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)

        iconpackopened = False
        if not iconpack:
            try:
                iconpack = ts3client.IconPack.current()
                iconpack.open()
                iconpackopened = True
            except Exception as e:
                self.delete()
                raise e

        try:
            setupUi(self,
                    pytson.getPluginPath("ressources", "filebrowser.ui"),
                    iconpack=iconpack)

            self.statusbar = SmartStatusBar(self)
            self.layout().addWidget(self.statusbar)
            self.statusbar.hide()
        except Exception as e:
            self.delete()
            raise e

        err, cname = ts3lib.getChannelVariableAsString(
            schid, cid, ChannelProperties.CHANNEL_NAME)

        if err == ERROR_ok:
            self.setWindowTitle(
                self._tr("File Browser - {cname}").format(cname=cname))
        else:
            self.setWindowTitle(self._tr("File Browser"))

        self.schid = schid
        self.cid = cid
        self.password = password
        self.path = None

        self.staticpath = staticpath
        self.readonly = readonly

        self.createretcode = None
        self.delretcode = None

        if not self.readonly and not downloaddir:
            cfg = ts3client.Config()
            q = cfg.query("SELECT value FROM filetransfer "
                          "WHERE key='DownloadDir'")
            del cfg

            if q.next():
                self.downloaddir = q.value("value")
            else:
                self.delete()
                raise Exception("Error getting DownloadDir from config")
        else:
            self.downloaddir = downloaddir

        if not self.readonly:
            menu = self.menu = QMenu(self)

            self.openAction = menu.addAction(QIcon(iconpack.icon("FILE_UP")),
                                             self._tr("Open"))
            self.openAction.connect("triggered()",
                                    self.on_openAction_triggered)

            self.downAction = menu.addAction(QIcon(iconpack.icon("DOWN")),
                                             self._tr("Download"))
            self.downAction.connect("triggered()", self.downloadFiles)
            self.renameAction = menu.addAction(QIcon(iconpack.icon("EDIT")),
                                               self._tr("Rename"))
            self.renameAction.connect("triggered()",
                                      self.on_renameAction_triggered)
            self.copyAction = menu.addAction(QIcon(iconpack.icon("COPY")),
                                             self._tr("Copy URL"))
            self.copyAction.connect("triggered()",
                                    self.on_copyAction_triggered)
            self.delAction = menu.addAction(QIcon(iconpack.icon("DELETE")),
                                            self._tr("Delete"))
            self.delAction.connect("triggered()", self.deleteFiles)

            self.upAction = menu.addAction(QIcon(iconpack.icon("UP")),
                                           self._tr("Upload files"))
            self.upAction.connect("triggered()", self.uploadFiles)
            self.createAction = menu.addAction(QIcon.fromTheme("folder"),
                                               self._tr("Create Folder"))
            self.createAction.connect("triggered()", self.createFolder)
            self.refreshAction = menu.addAction(
                QIcon(iconpack.icon("FILE_REFRESH")), self._tr("Refresh"))
            self.refreshAction.connect("triggered()", self.refresh)

            self.allactions = [
                self.openAction, self.downAction, self.renameAction,
                self.copyAction, self.delAction, self.upAction,
                self.createAction, self.refreshAction
            ]

        self.collector = FileCollector(schid, cid, password, self.downloaddir)
        self.collector.collectionFinished.connect(self._startDownload)
        self.collector.collectionError.connect(self.showError)

        self.fileDoubleClicked = Signal()
        self.contextMenuRequested = Signal()

        self.transdlg = None

        self.listmodel = FileListModel(schid,
                                       cid,
                                       password,
                                       self,
                                       readonly=readonly)
        self.listmodel.pathChanged.connect(self.onPathChanged)
        self.listmodel.error.connect(self.showError)

        self.proxy = QSortFilterProxyModel(self)
        self.proxy.setSortRole(Qt.UserRole)
        self.proxy.setSortCaseSensitivity(Qt.CaseInsensitive)
        self.proxy.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.proxy.setSourceModel(self.listmodel)

        self.listmodel.path = path

        self._adjustUi()

        if iconpackopened:
            iconpack.close()

        PluginHost.registerCallbackProxy(self)
Esempio n. 15
0
    def serversReply(self, reply):
        try:
            _api = self.serverBrowser.config['GENERAL']['api']
            _reason = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)
            _reply = reply.readAll()
            servers = json.loads(_reply.data().decode('utf-8'))
            if self.serverBrowser.config["GENERAL"]["debug"] == "True":
                ts3.printMessageToCurrentTab("servers: %s" % servers)
            self.status.setText("Response from \"{0}\": {1}: {2}".format(
                _api, _reason,
                reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute)))
            palette = QPalette()
            if not _reason == 200:
                palette.setColor(QPalette.Foreground, Qt.red)
            self.status.setPalette(palette)

            self.status.setText(
                "Status: %s" %
                reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute))
            if servers["status"] == "success":
                self.pages = servers["result"]["pagestotal"]
                self.pageLabel.setText(
                    str(servers["result"]["pageactive"]) + " / " +
                    str(servers["result"]["pagestotal"]))
                self.pageLabel.updateGeometry()
                self.info.setText(
                    str(servers["result"]["itemsshown"]) + " / " +
                    str(servers["result"]["itemstotal"]) + " Servers shown.")
                self.serverList.setRowCount(0)
            elif servers["status"] == "error":
                self.info.setText("Requested Page: " + str(self.page))
                self.status.setText(servers["status"].title() + ": " +
                                    servers["result"]["message"] + " (" +
                                    str(servers["result"]["code"]) + ")")
                palette = QPalette()
                palette.setColor(QPalette.Foreground, Qt.red)
                self.status.setPalette(palette)
                return
            else:
                self.info.setText("Requested Page: " + str(self.page))
                palette = QPalette()
                palette.setColor(QPalette.Foreground, Qt.red)
                self.status.setPalette(palette)
                return
            _list = self.serverList
            _filters = self.serverBrowser.config["FILTERS"]
            if servers["result"]["pageactive"] == 1:
                self.previous.setEnabled(False)
            else:
                self.previous.setEnabled(True)
            if servers["result"]["pageactive"] == servers["result"][
                    "pagestotal"]:
                self.next.setEnabled(False)
            else:
                self.next.setEnabled(True)
            for key in servers["result"]["data"]:
                if self.buhl(
                        _filters["hideFull"]) and key["users"] >= key["slots"]:
                    continue
                elif self.buhl(_filters["hideEmpty"]) and key["users"] <= 0:
                    continue
                else:
                    rowPosition = _list.rowCount
                    _list.insertRow(rowPosition)
                    # if key['premium']:
                    #     _list.setItem(rowPosition, 0, QTableWidgetItem("Yes"))
                    # else:
                    #     _list.setItem(rowPosition, 0, QTableWidgetItem("No"))
                    _list.setItem(rowPosition, 0,
                                  QTableWidgetItem(key['name']))
                    _list.setItem(
                        rowPosition, 1,
                        QTableWidgetItem(
                            str(key['users']) + ' / ' + str(key['slots'])))
                    if key['users'] >= key['slots']:
                        palette = QPalette()
                        palette.setColor(QPalette.Foreground, Qt.red)
                        _list.setPalette(palette)
                    item_country = QTableWidgetItem(
                        self.getCountryNamebyID(key['country']))
                    item_country.setIcon(QIcon(self.flags.flag(
                        key['country'])))
                    _list.setItem(rowPosition, 2, item_country)
                    item_createchannels = QTableWidgetItem()
                    if key['createchannels']:
                        item_createchannels.setText("Yes")
                        item_createchannels.setIcon(
                            QIcon(IconPack.icon(self.icons, "channel_create")))
                    else:
                        item_createchannels.setText("No")
                        item_createchannels.setIcon(
                            QIcon(IconPack.icon(self.icons, "channel_delete")))
                    _list.setItem(rowPosition, 3, item_createchannels)
                    item_password = QTableWidgetItem()
                    if key['password']:
                        item_password.setText("Yes")
                        item_password.setIcon(
                            QIcon(IconPack.icon(self.icons,
                                                "channel_private")))
                    else:
                        item_password.setText("No")
                        item_password.setIcon(
                            QIcon(IconPack.icon(self.icons, "channel_green")))
                    _list.setItem(rowPosition, 4, item_password)
                    _list.setItem(rowPosition, 5,
                                  QTableWidgetItem(key["address"]))
                    # first_cell = _list.item(rowPosition, 0)
                    # first_cell.setData(Qt.UserRole, key['address'])
            _color = self.serverBrowser.config["GENERAL"][
                "alternatebackgroundcolor"]
            if _color != "":
                _list.styleSheet = "alternate-background-color: {0};".format(
                    _color)
            else:
                _list.setAlternatingRowColors(False)
        except:
            ts3.logMessage(traceback.format_exc(),
                           ts3defines.LogLevel.LogLevel_ERROR, "pyTSon", 0)
Esempio n. 16
0
    #qplace.Position.setZ(oldz + 0.1)
  
    newpos = qplace.Position
    newpos.setZ(oldz + 0.1)
    qplace.Position = newpos
    print qplace.Position.z(), "."    
        
if 0:
    from PythonQt.QtCore import QFile, QSize
    from PythonQt.QtGui import QLineEdit, QHBoxLayout,  QLabel, QPushButton, QSizePolicy, QIcon
    
    box = r.c.widget.findChild("QHBoxLayout", "meshLine")
    #print box.layoutSpacing
    button = QPushButton()

    icon = QIcon("pymodules/editgui/ok.png")
    icon.actualSize(QSize(16, 16))
    
    button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
    button.setMaximumSize(QSize(16, 16))
    button.setMinimumSize(QSize(16, 16))

    button.text = ""
    button.name = "Apply"
    button.setIcon(icon)
    box.addWidget(button)
    
    #~ line = r.c.widget.findChild("QLineEdit", "meshLineEdit")
    #~ print line.sizePolicy.horizontalPolicy(), QSizePolicy.Expanding
    
if 0:
Esempio n. 17
0
    def __init__(self, cfg, parent):
        super().__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowTitle("Eventlog")

        self.cfg = cfg

        self.pauseButton = QPushButton("Pause", self)
        self.pauseButton.setCheckable(True)
        self.pauseButton.connect("toggled(bool)", self.onPauseButtonToggled)
        self.spacer = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.maxLabel = QLabel("Maximum Events:", self)
        self.maxSpin = QSpinBox(self)
        self.maxSpin.setMaximum(10000)
        self.maxSpin.setToolTip("Set to 0 to not shrink events at all")
        self.maxSpin.setValue(cfg.getint("maximumEvents"))
        self.maxSpin.connect("valueChanged(int)", self.onMaxSpinChanged)

        self.sublay1 = QHBoxLayout()
        self.sublay1.addWidget(self.pauseButton)
        self.sublay1.addItem(self.spacer)
        self.sublay1.addWidget(self.maxLabel)
        self.sublay1.addWidget(self.maxSpin)

        self.filterLabel = QLabel("Filter:", self)
        self.filterEdit = QLineEdit(self)
        self.filterEdit.connect("textChanged(QString)",
                                self.onFilterEditChanged)
        self.filterButton = QToolButton(self)
        self.filterButton.connect("clicked()", self.filterEdit.clear)
        try:
            ico = ts3client.IconPack.current()
            ico.open()
            self.filterButton.setIcon(QIcon(ico.icon("ERROR")))
            ico.close()
        except Exception as e:
            self.filterButton.setText("X")

        self.sublay2 = QHBoxLayout()
        self.sublay2.addWidget(self.filterLabel)
        self.sublay2.addWidget(self.filterEdit)
        self.sublay2.addWidget(self.filterButton)

        self.model = EventlogModel(self)
        self.model.maximumEvents = cfg.getint("maximumEvents")
        self.proxy = QSortFilterProxyModel(self)
        self.proxy.setFilterRole(Qt.UserRole)
        self.proxy.setSourceModel(self.model)

        self.tree = QTreeView(self)
        self.tree.header().hide()
        self.tree.setModel(self.proxy)

        self.lay = QVBoxLayout(self)
        self.lay.addLayout(self.sublay1)
        self.lay.addLayout(self.sublay2)
        self.lay.addWidget(self.tree)

        self.resize(cfg.getint("width"), cfg.getint("height"))

        self.connect("finished(int)", self.onFinished)
Esempio n. 18
0
    #qplace.Position.setZ(oldz + 0.1)

    newpos = qplace.Position
    newpos.setZ(oldz + 0.1)
    qplace.Position = newpos
    print qplace.Position.z(), "."

if 0:
    from PythonQt.QtCore import QFile, QSize
    from PythonQt.QtGui import QLineEdit, QHBoxLayout, QLabel, QPushButton, QSizePolicy, QIcon

    box = r.c.widget.findChild("QHBoxLayout", "meshLine")
    #print box.layoutSpacing
    button = QPushButton()

    icon = QIcon("pymodules/editgui/ok.png")
    icon.actualSize(QSize(16, 16))

    button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
    button.setMaximumSize(QSize(16, 16))
    button.setMinimumSize(QSize(16, 16))

    button.text = ""
    button.name = "Apply"
    button.setIcon(icon)
    box.addWidget(button)

    #~ line = r.c.widget.findChild("QLineEdit", "meshLineEdit")
    #~ print line.sizePolicy.horizontalPolicy(), QSizePolicy.Expanding

if 0:
Esempio n. 19
0
    def init_ui(self):
        loader = QUiLoader()
        
        # Container widget
        self.container = ui = loader.load(QFile("pymodules/loadurlhandler/webbrowser.ui"))
        
        # Webview
        self.webview = QWebView(self.container)
        self.webview.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
        
        self.webview.connect("loadStarted()", self.on_load_start)
        self.webview.connect("loadFinished(bool)", self.on_load_stop)
        self.webview.connect("loadProgress(int)", self.on_load_progress)
        self.webview.connect("linkClicked(QUrl)", self.link_clicked)
        
        layout = ui.findChild("QVBoxLayout", "verticalLayout_Container")
        layout.insertWidget(2, self.webview)
        
        # Buttons
        ui.findChild("QPushButton", "pushButton_ClearCookie").hide()
        self.button_back = ui.findChild("QPushButton", "pushButton_Back")
        self.button_forward = ui.findChild("QPushButton", "pushButton_Forward")
        self.button_refresh = ui.findChild("QPushButton", "pushButton_Refresh")
        self.button_stop = ui.findChild("QPushButton", "pushButton_Stop")
        self.button_go = ui.findChild("QPushButton", "pushButton_Go")        

        self.button_back.setIcon(QIcon("./data/ui/images/arrow_left_48.png"));
        self.button_back.setIconSize(QSize(20, 20));
        self.button_forward.setIcon(QIcon("./data/ui/images/arrow_right_48.png"));
        self.button_forward.setIconSize(QSize(20, 20));
        self.button_refresh.setIcon(QIcon("./data/ui/images/refresh_48.png"));
        self.button_refresh.setIconSize(QSize(20, 20));
        self.button_stop.setIcon(QIcon("./data/ui/images/cross_48.png"));
        self.button_stop.setIconSize(QSize(20, 20));
        self.button_stop.setEnabled(False);
        self.button_go.setIcon(QIcon("./data/ui/images/arrow_right_green_48.png"));
        self.button_go.setIconSize(QSize(20, 20));

        self.button_back.connect("clicked()", self.on_back)
        self.button_forward.connect("clicked()", self.on_forward)
        self.button_refresh.connect("clicked()", self.on_refresh)
        self.button_stop.connect("clicked()", self.on_stop)
        self.button_go.connect("clicked()", self.go_to_linedit_url)
        
        # Address bar
        self.lineedit_address = ui.findChild("QComboBox", "comboBox_Address")
        self.lineedit_address.lineEdit().connect("returnPressed()", self.go_to_linedit_url)
        
        # Progress bar and label
        self.progress_bar = ui.findChild("QProgressBar", "progressBar_Status")
        self.progress_bar.hide()
        
        self.progress_label = ui.findChild("QLabel", "label_Status")
        
        # Add to scene
        #uism = naali.ui
        #self.proxywidget = r.createUiProxyWidget(self.container)
        #self.proxywidget.setWindowTitle("Naali Web Browser")
        #self.proxywidget.connect("Visible(bool)", self.vibibility_changed)
        #if not uism.AddWidgetToScene(self.proxywidget):
        #    r.logError('LoadURLHandler: Adding the ProxyWidget to the scene failed.')
        self.container.show()
Esempio n. 20
0
    def data(self, index, role):
        obj = self._indexObject(index)

        if role == Qt.DisplayRole:
            if type(obj) is Client:
                if obj.isRecording:
                    return "*** %s *** [RECORDING]" % obj.displayName
                else:
                    return obj.displayName

            return obj.name
        elif role == ServerViewRoles.isspacer:
            return type(obj) is Channel and obj.isSpacer
        elif type(obj) is Channel and role == ServerViewRoles.spacertype:
            return obj.spacerType
        elif type(obj) is Channel and role == ServerViewRoles.spacercustomtext:
            return obj.spacerCustomtext
        elif type(obj) is Channel and role == ServerViewRoles.spaceralignment:
            return obj.spacerAlignment
        elif role == Qt.DecorationRole:
            if not (type(obj) is Channel and obj.isSpacer):
                return QIcon(self.iconpack.icon(obj.iconVariable()))
        elif role == ServerViewRoles.statusicons:
            ret = []
            if type(obj) is Channel:
                if obj.isDefault:
                    ret.append(QIcon(self.iconpack.icon("DEFAULT")))
                if obj.codec == ts3defines.CodecType.CODEC_OPUS_MUSIC:
                    ret.append(QIcon(self.iconpack.icon("MUSIC")))
                if obj.neededTalkPower > 0:
                    ret.append(QIcon(self.iconpack.icon("MODERATED")))
                if obj.iconID != 0:
                    ret.append(QIcon(self.icons.icon(obj.iconID)))
            elif type(obj) is Client:
                # badges
                # priority speaker
                if obj.isPrioritySpeaker:
                    ret.append(QIcon(self.iconpack.icon("CAPTURE")))
                # istalker
                if obj.isTalker:
                    ret.append(QIcon(self.iconpack.icon("IS_TALKER")))
                elif obj.talkPower < obj.parentNode.neededTalkPower:
                    ret.append(QIcon(self.iconpack.icon("INPUT_MUTED")))
                # channelgroup
                if obj.channelGroup in self.cgicons:
                    ret.append(
                        QIcon(self.icons.icon(self.cgicons[obj.channelGroup])))
                # servergroups
                for sg in obj.serverGroups:
                    if sg in self.sgicons:
                        ret.append(QIcon(self.icons.icon(self.sgicons[sg])))
                # clienticon
                if obj.iconID != 0:
                    ret.append(QIcon(self.icons.icon(obj.iconID)))
                # talkrequest
                if obj.isRequestingTalkPower:
                    ret.append(QIcon(self.iconpack.icon("REQUEST_TALK_POWER")))
                # flag
                if obj.country != "":
                    ret.append(QIcon(self.countries.flag(obj.country)))
            else:
                assert type(obj) is Server
                if obj.iconID != 0:
                    ret.append(QIcon(self.icons.icon(obj.iconID)))

            return ret
        elif role == Qt.FontRole:
            if type(obj) is Client and obj.isme:
                font = QApplication.font()
                font.setBold(True)
                return font
        elif role == Qt.ForegroundRole:
            if type(obj) is Client and obj.isRecording:
                return QColor(Qt.darkRed)

        return None
Esempio n. 21
0
    def __init__(self):
        self.sels = []
        self.selmasses = {}
        Component.__init__(self)
        self.resetValues()
        self.worldstream = r.getServerConnection()
        self.usingManipulator = False
        self.useLocalTransform = False
        #self.cpp_python_handler = None
        self.left_button_down = False
        self.keypressed = False
        self.editing = False

        self.editingKeyTrigger = (Qt.Key_M, Qt.ShiftModifier)
        self.shortcuts = {
            self.editingKeyTrigger: self.toggleEditingKeyTrigger,
            (Qt.Key_R, Qt.NoModifier): self.rotateObject,
            (Qt.Key_S, Qt.NoModifier): self.scaleObject,
            (Qt.Key_G, Qt.NoModifier): self.translateObject,
            (Qt.Key_Tab, Qt.NoModifier): self.cycleManipulator,
            (Qt.Key_Z, Qt.ControlModifier): self.undo,
            (Qt.Key_Delete, Qt.NoModifier): self.deleteObject,
            (Qt.Key_L, Qt.AltModifier): self.linkObjects,
            (Qt.Key_L, Qt.ControlModifier | Qt.ShiftModifier):
            self.unlinkObjects,
        }

        # Connect to key pressed signal from input context
        self.edit_inputcontext = naali.createInputContext("object-edit", 100)
        self.edit_inputcontext.SetTakeMouseEventsOverQt(True)
        #print "connecting to",self.edit_inputcontext
        self.edit_inputcontext.connect('KeyPressed(KeyEvent*)',
                                       self.on_keypressed)

        # Connect to mouse events
        self.edit_inputcontext.connect('MouseScroll(MouseEvent*)',
                                       self.on_mousescroll)
        self.edit_inputcontext.connect('MouseLeftPressed(MouseEvent*)',
                                       self.on_mouseleftpressed)
        self.edit_inputcontext.connect('MouseLeftReleased(MouseEvent*)',
                                       self.on_mouseleftreleased)
        self.edit_inputcontext.connect('MouseMove(MouseEvent*)',
                                       self.on_mousemove)

        self.resetManipulators()

        self.selection_rect = QRect()
        self.selection_rect_startpos = None

        r.c = self  #this is for using objectedit from command.py

        self.selection_box_entity = None
        self.selection_box = None
        self.selection_box_inited = False

        self.menuToggleAction = None
        mainWindow = naali.ui.MainWindow()
        if mainWindow:
            self.menuToggleAction = QAction(
                QIcon("./data/ui/images/worldbuilding/transform-move.png"),
                "Toggle Object Manipulation", 0)
            self.menuToggleAction.connect("triggered()",
                                          self.toggleEditingKeyTrigger)
            if naali.server.IsAboutToStart() == False:
                naali.client.connect("Connected()", self.on_connected_tundra)
                naali.client.connect("Disconnected()",
                                     self.on_disconnected_tundra)
            else:
                editMenu = mainWindow.AddMenu("Edit")
                editMenu.addAction(self.menuToggleAction)
        self.toggleEditing(False)
        """