示例#1
0
 def _delayedDelivery(self, otherID, msgID, recvTime, error, errorMessage):
     otherID = convert_string(otherID)
     errorMessage = convert_string(errorMessage)
     
     if otherID in self._openChats:
         chatWindow = self._openChats[otherID]
         chatWindow.getChatWidget().delayedDelivery(msgID, recvTime, error, errorMessage)
 def _loadIndex(self):
     try:
         self.settings = QSettings(get_settings().get_config("remote_pictures", "index"), QSettings.NativeFormat)
                     
         storedThumbnails  = self.settings.value("categoryThumbnails", None)
         if storedThumbnails != None:
             storedThumbnails = storedThumbnails.toMap()
             for aCat in storedThumbnails:
                 thumbnailPath = convert_string(storedThumbnails[aCat].toString())
                 aCat = convert_string(aCat)
                 if aCat == u"Not Categorized":
                     aCat = PrivacySettings.NO_CATEGORY
                 self._addCategory(aCat, thumbnailPath)
                 
         categoryPictures = self.settings.value("categoryPictures", None)
         if categoryPictures != None:
             tmpDict = categoryPictures.toMap()
             added = time()
             for aCat in tmpDict:
                 newKey = convert_string(aCat)
                 if newKey == u"Not Categorized":
                     newKey = PrivacySettings.NO_CATEGORY
                 picTupleList = tmpDict[aCat].toList()
                 for picTuple in picTupleList:
                     tupleList = picTuple.toList()
                     picURL = convert_string(tupleList[0].toString())
                     picDesc = convert_string(tupleList[1].toString())
                     self.addPicture(newKey, picURL, picDesc, None, added, None, None)
                     if not picDesc:
                         picDesc = None
                     
     except:
         self.logger.exception("Could not load thumbnail index.")
 def displayImage(self, cat, picID, picRow, hasPrev, hasNext):
     cat = convert_string(cat)
     picURL = convert_string(picRow[RemotePicturesStorage.PIC_URL_COL])
     picFile = convert_string(picRow[RemotePicturesStorage.PIC_FILE_COL])
     picDesc = convert_string(picRow[RemotePicturesStorage.PIC_DESC_COL])
     if picDesc is None:
         picDesc = u""
     picSender = convert_string(picRow[RemotePicturesStorage.PIC_SENDER_COL])
     picTime = picRow[RemotePicturesStorage.PIC_ADDED_COL]
     
     self.currentCategory = cat
     self.categoryLabel.setText(cat)
     
     self.curPicIndex = picID
     if picFile and os.path.exists(picFile):
         self.imageLabel.setImage(picFile)
     elif picURL:
         self.imageLabel.setURL(picURL)
     else:
         self.logger.warning("No image source specified")
         self.imageLabel.displayFallbackPic()
     
     if picSender:
         self.imageLabel.setToolTip(u"Sent to you by %s,\nSent %s" % (get_peers().getDisplayedPeerName(pID=picSender),
                                                                      formatTime(localtime(picTime))))
     else:
         self.imageLabel.setToolTip(u"")
         
     self.descriptionLabel.setText(picDesc)
     self.setCurrentIndex(1)
     
     self.prevButton.setEnabled(hasPrev)
     self.nextButton.setEnabled(hasNext)
     
     self._categoryOpened.emit()
 def sendMessage(self, otherID, msgHTML, msgID=None, msgTime=None, isNoResend=False):
     otherID = convert_string(otherID)
     msgHTML = convert_string(msgHTML)
     
     if msgID == None:
         msgID = self._getNextMessageID()
         isResend = False
     else:
         isResend = True
         
     if isNoResend:
         isResend = False
     
     if msgTime == None:
         msgTime = time()
     
     msgDict = {u"id": msgID,
                u"format": u"html",
                u"data": msgHTML,
                u"time": msgTime}
     
     try:
         msgDictJSON = json.dumps(msgDict)
     except:
         self.logger.exception("Error serializing private message: %s", msgDict)
         return
     
     get_server().call("HELO_PM " + msgDictJSON, peerIDs=[otherID])
     self._waitingForAck[msgID] = (otherID,
                                   time() if isResend else msgTime,
                                   msgHTML,
                                   isResend)
示例#5
0
 def _addLogMessage(self, record):
     self._records.append(record)
     
     msg = record.msg
     if not isinstance(msg, basestring):
         msg = unicode(msg)
     try:
         msg = convert_string(msg) % record.args
     except:
         msg = u"(Error formatting log message) " +\
          convert_string(msg) +\
          ', '.join(unicode(v) for v in record.args)
         
     dirname = os.path.dirname(record.pathname)
     source = u"%s:%d" % (os.path.join(os.path.basename(dirname), os.path.basename(record.pathname)), record.lineno)
     fullsource = u"%s:%d" % (record.pathname, record.lineno)
     component = record.name
     if component.startswith("lunchinator."):
         component = component[12:]
     error = 1 if record.levelno == logging.WARNING else 2 if record.levelno == logging.ERROR else 0
     self._logModel.appendRow([self._createItem(strftime("%H:%M:%S", localtime(record.created)), error),
                               self._createItem(record.levelname, error),
                               self._createItem(component, error),
                               self._createItem(msg, error),
                               self._createItem(source, error, fullsource)])
 
     
示例#6
0
 def set_next_lunch_time(self, begin_time, end_time):
     if begin_time == None:
         self._next_lunch_begin, self._next_lunch_end = None, None
         
     begin_time = convert_string(begin_time)
     self._next_lunch_begin = self._check_lunch_time(begin_time, self._next_lunch_begin)
     end_time = convert_string(end_time)
     self._next_lunch_end = self._check_lunch_time(end_time, self._next_lunch_end)
 def _checkSendInfoDict(self, pluginName, category):
     pluginName = convert_string(pluginName)
     category = convert_string(category)
     pi = get_plugin_manager().getPluginByName(pluginName, category)
     if pi != None:
         po = pi.plugin_object
         if po.extendsInfoDict():
             get_server().call_info()
示例#8
0
 def _avatarChanged(self, peerID, newFile):
     peerID = convert_string(peerID)
     newFile = convert_string(newFile)
     
     if peerID == self._otherID:
         self.setOtherIconPath(get_peers().getPeerAvatarFile(pID=peerID))
     if peerID == get_settings().get_ID():
         self.setOwnIconPath(get_peers().getPeerAvatarFile(pID=peerID))
 def _pluginDeactivated(self, pluginName, category):
     pluginName = convert_string(pluginName)
     category = convert_string(category)
     pi = get_plugin_manager().getPluginByName(pluginName, category)
     if pi:
         with self._lock:
             removed = self._removeActionsForPlugin(pi)
         if removed:
             get_notification_center().emitPeerActionsRemoved(removed)
 def _pluginActivated(self, pluginName, category):
     pluginName = convert_string(pluginName)
     category = convert_string(category)
     pi = get_plugin_manager().getPluginByName(pluginName, category)
     if pi:
         with self._lock:
             added = self._addActionsForPlugin(pi)
         if added:
             get_notification_center().emitPeerActionsAdded(added)
示例#11
0
 def _pluginActivated(self, pName, pCat):
     pName = convert_string(pName)
     pCat = convert_string(pCat)
     if pCat == "gui":
         try:
             pluginInfo = get_plugin_manager().getPluginByName(pName, u"gui")
             self.addPluginWidget(pluginInfo.plugin_object, pName)
         except:
             getCoreLogger().exception("while including plugins %s", str(sys.exc_info()))
示例#12
0
 def _pluginWillBeDeactivated(self, pName, pCat):
     pName = convert_string(pName)
     pCat = convert_string(pCat)
     if pCat == "gui":
         pluginInfo = get_plugin_manager().getPluginByName(pName, pCat)
         try:
             pluginInfo.plugin_object.destroy_widget()
         except:
             getCoreLogger().exception("Error destroying plugin widget for plugin %s", pName)
         self.removePluginWidget(pName)
示例#13
0
 def _displayedPeerNameChanged(self, pID, newName, _infoDict):
     pID = convert_string(pID)
     newName = convert_string(newName)
     
     if pID == self._otherID:
         self._otherName = newName
         self._updateOtherName()
     if pID == get_settings().get_ID():
         self._ownName = newName
         self._updateOwnName()
示例#14
0
 def link_clicked(self, url):
     if not url.host():
         if url.hasQueryItem("reply-to") and url.hasQueryItem("screen-name"):
             self._reply_to_id = long(convert_string(url.queryItemValue("reply-to")))
             self.post_field.setPlainText("@"+convert_string(url.queryItemValue("screen-name"))+" ")
             self.set_status("Reply to @"+convert_string(url.queryItemValue("screen-name")))
         else:
             self.logger.error("Unknown command from link: "+str(url.toString()))
     else:
         webbrowser.open(str(url.toString()))
 def categoryThumbnailChanged(self, cat, thumbnailPath, thumbnailSize):
     cat = convert_string(cat)
     thumbnailPath = convert_string(thumbnailPath)
     
     row = self._categoryToRow.get(cat, None)
     if row is None:
         self.logger.warning("Invalid category (%s), cannot set thumbnail", cat)
         return
     item = self.item(row)
     self._initializeItem(item, thumbnailPath, thumbnailSize, cat, adding=False)
示例#16
0
 def toggle_plugin(self, p_name, p_cat, new_state):
     try:
         p_cat = convert_string(p_cat)
         p_name = convert_string(p_name)
         
         if new_state:
             get_plugin_manager().activatePluginByName(p_name, p_cat)
         else:
             get_plugin_manager().deactivatePluginByName(p_name, p_cat)
     except:
         getCoreLogger().exception("Error toggling plugin")
示例#17
0
 def save_options_widget_data(self, **_kwargs):
     from PyQt4.QtCore import Qt
     from logging_level_settings.logging_level_gui import LogLevelModel
     get_settings().set_logging_level(self._ui.getGlobalLevelText())
     
     model = self._ui.getModel() 
     for row in xrange(model.rowCount()):
         loggerName = convert_string(model.item(row, LogLevelModel.NAME_COLUMN).data(LogLevelModel.KEY_ROLE).toString())
         levelText = convert_string(model.item(row, LogLevelModel.LEVEL_COLUMN).data(Qt.DisplayRole).toString())
         level = self._getLevelFromText(levelText)
         setLoggingLevel(loggerName, level)
示例#18
0
 def receiveFileSlot(self, addr, file_size, file_name, tcp_port, successFunc, errorFunc):
     addr = convert_string(addr)
     file_name = convert_string(file_name)
     dr = DataReceiverThread.receiveSingleFile(addr, file_name, file_size, tcp_port, getCoreLogger(), "avatar%s" % addr, True, parent=self)
     if successFunc:
         dr.successfullyTransferred.connect(lambda _thread, _path : successFunc())
     if errorFunc:
         dr.errorOnTransfer.connect(lambda _thread, _msg : errorFunc())
     dr.successfullyTransferred.connect(self.successfullyReceivedFile)
     dr.errorOnTransfer.connect(self.errorOnTransfer)
     dr.finished.connect(dr.deleteLater)
     dr.start()
示例#19
0
 def _displayOwnMessage(self, otherID, msgID, recvTime, msgHTML, msgTime, status, errorMsg):
     otherID = convert_string(otherID)
     msgHTML = convert_string(msgHTML)
     errorMsg = convert_string(errorMsg)
     if recvTime == -1:
         recvTime = None
     if not errorMsg:
         errorMsg = None
     
     if otherID in self._openChats:
         chatWindow = self._openChats[otherID]
         chatWindow.getChatWidget().addOwnMessage(msgID, recvTime, msgHTML, msgTime, status, errorMsg)
示例#20
0
 def convertDict(cls, aDict):
     newDict = {}
     for aKey in aDict:
         newKey = aKey
         if type(aKey) == QString:
             newKey = convert_string(aKey)
         aValue = aDict[aKey]
         if type(aValue) == QString:
             aValue = convert_string(aValue)
         elif type(aValue) == QVariant:
             aValue = convert_string(aValue.toString())
         newDict[newKey] = aValue
     return newDict
 def _receivedSuccessfullySlot(self, otherID, msgHTML, msgTime, msgDict, recvTime):
     otherID = convert_string(otherID)
     msgHTML = convert_string(msgHTML)
     try:
         self._getStorage().addOtherMessage(msgDict[u"id"], otherID, msgTime, msgHTML, recvTime)
         self._displayMessageLock.lock()
         try:
             self._currentlyDisplaying[otherID].remove(msgDict[u"id"])
         finally:
             self._displayMessageLock.unlock()
     except:
         self.logger.exception("Error storing partner message")
     self._sendAnswer(otherID, msgDict, recvTime=recvTime)
 def addCategory(self, cat, thumbnailPath, thumbnailSize):
     cat = convert_string(cat)
     thumbnailPath = convert_string(thumbnailPath)
     
     item = QStandardItem()
     item.setEditable(False)
     item.setData(QVariant(cat if cat != PrivacySettings.NO_CATEGORY else u"Not Categorized"), Qt.DisplayRole)
     self._initializeItem(item, thumbnailPath, thumbnailSize, cat, True)
     item.setData(QVariant() if thumbnailPath is None else QVariant(thumbnailPath), self.PATH_ROLE)
     catv = QVariant(cat)
     item.setData(catv, self.SORT_ROLE)
     item.setData(catv, self.CAT_ROLE)
     
     self._categoryToRow[cat] = self.rowCount()
     self.appendRow([item])
示例#23
0
 def externalRowRemoved(self, key):
     if type(key) == QString:
         key = convert_string(key)
     if key in self.keys:
         index = self.keys.index(key)
         del self.keys[index]
         self.removeRow(index)
 def _getSelectedPeer(self, selection=None):
     if selection is None:
         selection = self._peerList.selectionModel().selection()
     if len(selection.indexes()) > 0:
         index = iter(selection.indexes()).next()
         return convert_string(index.data(HistoryPeersModel.KEY_ROLE).toString())
     return None
示例#25
0
    def updateLogList(self, logsAdded=None, logsRenamed=None):
        selectedMember = self.get_selected_log_member()

        if logsAdded == None:
            self.log_tree_view.clear()
            logsAdded = []
            for index, logFile in enumerate(reversed(self.listLogFilesForMember(selectedMember))):
                logsAdded.append((index, logFile))
            if len(logsAdded) == 0:
                self.log_tree_view.clear()
                self.log_tree_view.addTopLevelItem(
                    QTreeWidgetItem(self.log_tree_view, QStringList("No logs available."))
                )
                self.log_tree_view.setSelectionMode(QTreeWidget.NoSelection)
                self.logSizeLabel.setText("No logs")
                self.clearLogsButton.setEnabled(False)
                return

        if logsRenamed != None:
            for index, oldName, newName in logsRenamed:
                # index + 1 because of the "requesting" item
                item = self.log_tree_view.topLevelItem(index + 1)
                if item != None:
                    itemLogFile = convert_string(item.data(0, Qt.UserRole).toString())
                    if itemLogFile != oldName:
                        self.logger.warning(
                            "index does not correspond to item in list:\n\t%s\n\t%s", itemLogFile, oldName
                        )
                    self.initializeLogItem(item, newName)

        if len(logsAdded) == 0:
            self.log_tree_view.takeTopLevelItem(0)
        else:
            for index, logFile in logsAdded:
                oldItem = self.log_tree_view.topLevelItem(index)
                item = None
                if oldItem != None and oldItem.data(0, Qt.UserRole) == None:
                    # requested item has been received
                    item = oldItem
                else:
                    item = QTreeWidgetItem()
                    oldItem = None

                if logFile == None:
                    item.setData(0, Qt.DisplayRole, QVariant("Requesting..."))
                    QTimer.singleShot(6000, partial(self.requestTimedOut, item))
                else:
                    self.initializeLogItem(item, logFile)

                if oldItem == None:
                    # else, the old item is being modified
                    self.log_tree_view.insertTopLevelItem(index, item)
                self.log_tree_view.setSelectionMode(QTreeWidget.SingleSelection)

        totalSize = 0
        for aLogFile in self.listLogFilesForMember(selectedMember):
            totalSize += os.path.getsize(aLogFile)

        self.logSizeLabel.setText("%s consumed" % self.formatFileSize(totalSize))
        self.clearLogsButton.setEnabled(True)
示例#26
0
 def getSelectedRequirements(self):
     reqs = []
     for row in xrange(self._reqTable.topLevelItemCount()):
         rowItem = self._reqTable.topLevelItem(row)
         if rowItem.checkState(0) == Qt.Checked:
             reqs.append(convert_string(rowItem.data(0, self._REQUIREMENT_ROLE).toString()))
     return reqs
示例#27
0
 def externalRowUpdated(self, key, data):
     if type(key) == QString:
         key = convert_string(key)
     data = self._checkDict(data)
     if key in self.keys:
         index = self.keys.index(key)
         self.updateRow(key, data, index)
示例#28
0
 def _convertOption(self, o, v, new_v):
     try:
         choiceOptions = self.option_choice.get(o, None)
         if choiceOptions is not None:
             if not choiceOptions:
                 choiceOptions = self._getChoiceOptions(o)
             finalValue = None
             for aValue in choiceOptions:
                 if new_v.upper() == aValue.upper():
                     finalValue = aValue
                     break
             if finalValue != None:
                 return finalValue
             else:
                 # keep old value
                 return self._getOptionValue(o)
         elif type(v) == types.IntType:
             return int(new_v)
         elif type(v) == types.BooleanType:
             if new_v.strip().upper() in ["TRUE", "YES", "1"]:
                 return True
             else:
                 return False
         elif type(v) in (types.StringType, types.UnicodeType):
             return convert_string(new_v)
         else:
             self.logger.error("type of value %s %s not supported, using default", o, v)
     except:
         self.logger.exception("could not convert value of %s from config to type %s (%s) using default", o, type(v), new_v)
示例#29
0
 def _checkLogMessage(self, record):
     try:
         if self._notAgain.checkState() == Qt.Checked:
             return
         if record.levelno >= logging.ERROR:
             recMsg = record.msg
             if not isinstance(recMsg, basestring):
                 recMsg = unicode(recMsg)
             err = convert_string(recMsg) % record.args
             component = record.name
             if component.startswith("lunchinator."):
                 component = component[12:]
                 
             msg = u"%s - In component %s (%s:%d):\n%s" % (strftime("%H:%M:%S", localtime(record.created)),
                                                           component,
                                                           record.pathname,
                                                           record.lineno,
                                                           err)
             if record.exc_info:
                 out = StringIO()
                 traceback.print_tb(record.exc_info[2], file=out)
                 msg += u"\nStack trace:\n" + out.getvalue() + formatException(record.exc_info) + u"\n"
                 
             self._errorLog.append(msg)
             self._empty = False
             if not self.isVisible():
                 self.showNormal()
                 self.raise_()
                 self.activateWindow()
     except:
         from lunchinator.log import getCoreLogger
         getCoreLogger().info(formatException())
 def editorEvent(self, event, _model, option_, modelIndex):
     if self._column and modelIndex.column() != self._column:
         return False
     option = QStyleOptionViewItemV4(option_)
     self.initStyleOption(option, modelIndex)
     text = QString(option.text)
     if not text:
         self.parent().unsetCursor()
         return False
     
     if event.type() not in (QEvent.MouseMove, QEvent.MouseButtonRelease, QEvent.MouseButtonPress) \
         or not (option.state & QStyle.State_Enabled):
         return False
     
     if modelIndex.row() != self.mouseOverDocumentRow:
         return False
     
     # Get the link at the mouse position
     pos = event.pos()
     messageRect = self._getMessageRect(option, self.mouseOverDocument, modelIndex)
     anchor = convert_string(self.mouseOverDocument.documentLayout().anchorAt(QPointF(pos) - QPointF(messageRect.topLeft())))
     if anchor == "":
         if messageRect.contains(pos):
             self.parent().setCursor(Qt.IBeamCursor)
         else:
             self.parent().unsetCursor()
     else:
         self.parent().setCursor(Qt.PointingHandCursor)               
         if event.type() == QEvent.MouseButtonRelease:
             if anchor.startswith(u"www."):
                 anchor = u"http://" + anchor
             webbrowser.open(anchor)
             return True 
     return False
示例#31
0
    def append(self, text, additives):
        if additives:
            text += u" ("
            selfText = convert_string(self.toPlainText())
            if selfText:
                selfLen = len(selfText) + 1  # newline at end
            else:
                selfLen = 0
            textLen = selfLen + len(text)

            first = True
            for additive in additives:
                if not first:
                    text += u", "
                    textLen += 2

                for pos in xrange(textLen, textLen + len(additive)):
                    self.additives[pos] = additive
                text += additive

                textLen += len(additive)
                first = False
            text += u")"
        super(GrowingTextEdit, self).append(text)