Esempio n. 1
0
def _Ship_Orbit(targetID, followRange):
    if _IsAlreadyFollowingBallAtRange(session.shipid,
                                      targetID,
                                      followRange,
                                      moveMode=destiny.DSTBALL_ORBIT):
        return
    sm.GetService('space').SetIndicationTextForcefully(
        ballMode=destiny.DSTBALL_ORBIT,
        followId=targetID,
        followRange=followRange)
    bp = sm.GetService('michelle').GetRemotePark()
    bp.CmdOrbit(targetID, followRange)
    if not sm.GetService('machoNet').GetGlobalConfig().get(
            'newAutoNavigationKillSwitch', False):
        sm.GetService('autoPilot').CancelSystemNavigation()
    sm.GetService('flightPredictionSvc').OptionActivated(
        'Orbit', targetID, followRange)
    try:
        slimItem = sm.GetService('michelle').GetItem(targetID)
        if slimItem:
            sm.ScatterEvent('OnClientEvent_Orbit', slimItem)
        else:
            log.LogTraceback('Failed at scattering orbit event')
    except Exception as e:
        log.LogTraceback('Failed at scattering orbit event')
Esempio n. 2
0
def GetSchematicData(processorTypeID):
    schematicsData = cfg.schematicsByPin[processorTypeID]
    if len(schematicsData) == 0:
        log.LogTraceback(
            'Authoring error: No schematics found for processor pin with typeID %s'
            % processorTypeID)
    schematics = []
    for s in schematicsData:
        try:
            schematic = cfg.schematics.Get(s.schematicID)
        except:
            log.LogTraceback('Authoring error: No schematic found with id=%s' %
                             s.schematicID)
            raise

        inputs, outputs = _GetSchematicInputsAndOutputs(schematic.schematicID)
        outputsDict = {}
        for o in outputs:
            outputsDict[o.typeID] = o.quantity

        volumePerCycle = planetCommon.GetCommodityTotalVolume(outputsDict)
        volumePerHour = planetCommon.GetBandwidth(
            volumePerCycle, schematic.cycleTime * const.SEC)
        sData = util.KeyVal(name=schematic.schematicName,
                            schematicID=schematic.schematicID,
                            cycleTime=schematic.cycleTime,
                            outputs=outputs,
                            inputs=inputs,
                            outputVolume=volumePerHour)
        schematics.append((sData.name, sData))

    return uiutil.SortListOfTuples(schematics)
Esempio n. 3
0
    def ToPickle(self, value, nonblocking = 1):
        try:
            self.compressedPart = 0
            self.added_objects = {}
            ret = blue.marshal.Save(value, self.GetObjectID)
            if nonblocking and len(ret) > self.machoNet.largeResponseWarningThreshold:
                ctk = GetLocalStorage().get('calltimer.key', None)
                if len(ret) > self.machoNet.largeResponseErrorThreshold:
                    if ctk is not None:
                        self.machoNet.LogError('Unacceptably large response from ', ctk, ', ', len(ret), ' bytes')
                    else:
                        try:
                            self.machoNet.LogError('Unacceptably large response from unknown source, ', len(ret), ' bytes - ', repr(value)[:1024])
                        except Exception:
                            self.machoNet.LogError('Unacceptably large response from unknown source 2, ', len(ret), ' bytes - ', ret[:256])

                    log.LogTraceback()
                elif ctk is not None:
                    self.machoNet.LogWarn('Unacceptably large response from ', ctk, ', ', len(ret), ' bytes')
                else:
                    try:
                        self.machoNet.LogWarn('Unacceptably large response from unknown source, ', len(ret), ' bytes - ', repr(value)[:1024])
                    except Exception:
                        self.machoNet.LogWarn('Unacceptably large response from unknown source 2, ', len(ret), ' bytes - ', ret[:256])

            return ret
        except StandardError:
            self.machoNet.LogError("That was NOT a nice thing to do!  Keep yo' unpicklables to yourself.")
            log.LogTraceback()
            raise 
Esempio n. 4
0
def FmtDate(date, fmt='ll'):
    if date is None:
        return
    if fmt == 'nn':
        log.LogTraceback(
            "Incorrect format statement used, 'nn' would result in a return value of None for all input."
        )
        fmt = 'll'
    if date < 0:
        log.LogTraceback('Negative value in FmtDate')
        date *= -1
    year1800 = const.YEAR365 * 199L
    if fmt[1] not in ('l', 's', 'n'):
        log.LogTraceback('Incorrect format statement used', fmt)
        raise RuntimeError('InvalidArg', fmt)
    if date < year1800:
        if fmt[1] == 's':
            return localizationUtil.FormatTimeIntervalShortWritten(
                date, showFrom='day', showTo='second')
        else:
            return localizationUtil.FormatTimeIntervalWritten(date,
                                                              showFrom='day',
                                                              showTo='second')
    else:
        if fmt in ('ll', 'sl', 'nn', 'xs'):
            return localization.GetByLabel(
                '/Carbon/UI/Common/DateTime/SimpleDateUTC', datetime=date)
        if fmt in ('ls', 'ss'):
            return localization.GetByLabel(
                '/Carbon/UI/Common/DateTime/DateLongShort', datetime=date)
        if fmt in ('ln', 'sn', 'xn'):
            return localization.GetByLabel(
                '/Carbon/UI/Common/DateTime/DateLongNone', datetime=date)
        if fmt == 'nl':
            return localization.GetByLabel('/Carbon/UI/Common/DateTime/Time',
                                           datetime=date)
        if fmt == 'ns':
            return localization.GetByLabel(
                '/Carbon/UI/Common/DateTime/HoursAndMinutes', datetime=date)
        if fmt == 'xl':
            return localization.GetByLabel(
                '/Carbon/UI/Common/DateTime/SimpleDateUTC', datetime=date)
        if fmt == 'el':
            return localization.GetByLabel(
                '/Carbon/UI/Common/DateTime/DateExtendedLong', datetime=date)
        if fmt == 'es':
            return localization.GetByLabel(
                '/Carbon/UI/Common/DateTime/DateExtendedShort', datetime=date)
        if fmt == 'en':
            return localization.GetByLabel(
                '/Carbon/UI/Common/DateTime/DateExtendedNone', datetime=date)
        log.LogTraceback('InvalidArg', fmt)
        raise RuntimeError('InvalidArg', fmt)
 def CloseTransport(caller, tid, msg):
     if caller.transportsByID.has_key(tid):
         try:
             caller.transportsByID[tid].Write(msg)
         except StandardError:
             log.LogTraceback()
             caller.transportsByID[tid].Close('Write failed big time in CloseTransport')
             sys.exc_clear()
         except:
             log.LogTraceback()
             caller.transportsByID[tid].Close('Write failed big time in CloseTransport, non-standard error')
             raise
Esempio n. 6
0
 def ApplyAttributes(self, attributes):
     fontsize = attributes.get('fontsize', None)
     if fontsize is not None:
         attributes.fontsize = self.default_fontsize
         log.LogTraceback('You are not allowed to change fontsize of a font style - find another style to use or use uicontrols.Label for custom labels')
     uppercase = attributes.get('uppercase', None)
     if uppercase is not None:
         attributes.uppercase = self.default_uppercase
         log.LogTraceback('You are not allowed to change uppercase of a font style - find another style to use or use uicontrols.Label for custom labels')
     letterspace = attributes.get('letterspace', None)
     if letterspace is not None:
         attributes.letterspace = self.default_letterspace
         log.LogTraceback('You are not allowed to change letterspace of a font style - find another style to use or use uicontrols.Label for custom labels')
     Label.ApplyAttributes(self, attributes)
 def ParseObjectID(self, objectID):
     """
     The counterpart to GetObjectID() for Blue.marshal.Load, which only calls it for objects that were
     custom-marshaled using GetObjectID(). Returns a MachoObjectConnection proxy for remote
     "by reference" objects, using the object and timestamp (ref ID) serialized into the stream.
     """
     if session is None:
         self.machoNet.LogError('Session is none during ParseObjectID!!!')
         log.LogTraceback()
     t = blue.marshal.Load(objectID, self.ParseObjectID)
     if len(t) == 2:
         objectID, refID = t
         pa = {}
     else:
         objectID, pa, refID = t
     if objectID not in session.machoObjectsByID:
         nid, oid = objectID.split(':')
         if nid != self.identifier:
             if nid[0] == 'C':
                 if self.otherDudesAddress.addressType == const.ADDRESS_TYPE_CLIENT:
                     objectID = 'C=%d:%s' % (
                         self.otherDudesAddress.clientID, oid)
             return MachoObjectConnection(session.GetActualSession(), self,
                                          objectID, pa, refID)
         raise RuntimeError(
             'The specified object (%s) does not exist within this session (%s)'
             % (strx(objectID), strx(session)))
     return weakref.proxy(session.machoObjectsByID[objectID][1])
Esempio n. 8
0
    def DumpToLogThread(self):
        if self.broken or not self.msglog:
            return
        logfile = None
        try:
            filename = self.GetLogfileName()
            try:
                logfile = file(filename, 'a')
            except:
                if self.newfileAttempts < 3:
                    LogWarn('Failed to open the logfile %s, creating new logfile...' % filename)
                    filename = self.GetLogfileName(reset=True)
                    LogWarn('new logfile name is: ', filename)
                    self.newfileAttempts += 1
                    logfile = file(filename, 'a')
                else:
                    self.broken = 1
                    LogException(toAlertSvc=0)
                sys.exc_clear()

            if logfile:
                try:
                    logfile.writelines(self.msglog)
                    logfile.close()
                except IOError:
                    log.LogTraceback()
                    sys.exc_clear()

                self.msglog = []
        except:
            LogException(toAlertSvc=0)
            sys.exc_clear()

        if logfile and not logfile.closed:
            logfile.close()
Esempio n. 9
0
 def OnProcessLoginProgress(self,
                            what,
                            prefix=None,
                            current=1,
                            total=1,
                            response=None):
     if what not in LoginProgressLabels.keys():
         text = "Unexpected step in OnProcessLoginProgress, '%s'" % what
         log.LogTraceback(extraText=text, severity=log.LGERR)
         return
     self.processingBulkData = 0
     useMorph = 1
     args = {}
     if what == 'loginprogress::gettingbulkdata':
         self.processingBulkData = total
         args['current'] = current
         args['total'] = total
         useMorph = 0
     msg = localization.GetByLabel(LoginProgressLabels[what], **args)
     uthread.new(sm.GetService('loading').ProgressWnd,
                 localization.GetByLabel('/Carbon/UI/Login/LoggingIn'),
                 msg,
                 current,
                 total,
                 useMorph=useMorph,
                 autoTick=useMorph)
     blue.pyos.synchro.Yield()
Esempio n. 10
0
    def OnTraceMouseDownWithUrl_thread(self, url):
        if not url.startswith('showinfo:'):
            return
        itemID = None
        ids = url[9:].split('//')
        try:
            itemID = None
            if len(ids) > 1:
                itemID = int(ids[1])
        except:
            log.LogTraceback(
                'failed to convert string to ids when opening radial menu for link'
            )
            return

        if itemID is None or not util.IsSolarSystem(itemID):
            return
        localStargate = uix.FindLocalStargate(itemID)
        if localStargate:
            destinationID = localStargate.itemID
            typeID = localStargate.typeID
        else:
            destinationID = itemID
            typeID = const.typeSolarSystem
        sm.GetService('menu').TryExpandActionMenu(itemID=destinationID,
                                                  clickedObject=self,
                                                  typeID=typeID)
Esempio n. 11
0
    def __setitem__(self, ind, row):
        if self in self.__immutable__:
            raise RuntimeError('Immutable IndexRowsets may not be modified')
        if type(row) == type([]):
            self.items[ind] = row
        else:
            if hasattr(row, '__columns__'):
                rowHeader = row.__columns__
                rowLine = list(row)
            else:
                rowHeader = row.header
                rowLine = row.line
            if len(self.header) != len(rowHeader):
                line = [None] * len(self.header)
                for i in range(len(self.header)):
                    cname = self.header[i]
                    try:
                        idx = rowHeader.index(cname)
                    except ValueError:
                        raise RuntimeError('Mismatched row headers - game is broken', self.header, rowHeader)

                    line[i] = rowLine[idx]

                if self.stacktraceCnt < 2:
                    log.LogTraceback('rowset')
                    self.stacktraceCnt += 1
                self.items[ind] = line
            else:
                self.items[ind] = rowLine
Esempio n. 12
0
def FindClients(attr, val):
    ret = []
    for v in val:
        try:
            r = []
            for sid in sessionsByAttribute[attr].get(v, {}).iterkeys():
                if sid in sessionsBySID:
                    s = sessionsBySID[sid]
                    if hasattr(s, 'clientID'):
                        ret.append(s.clientID)
                else:
                    r.append(sid)

            for each in r:
                del sessionsByAttribute[attr][v][each]

        except:
            srv = sm.services['sessionMgr']
            srv.LogError('Session map borked')
            srv.LogError('sessionsByAttribute=', sessionsByAttribute)
            srv.LogError('sessionsBySID=', sessionsBySID)
            log.LogTraceback()
            raise

    return ret
Esempio n. 13
0
    def LinkWeapons(self, shipID, toID, fromID, merge = True):
        if toID == fromID:
            return
        toItem = self.dogmaItems[toID]
        fromItem = self.dogmaItems[fromID]
        for item in (toItem, fromItem):
            if not item.IsOnline():
                raise UserError('CantLinkModuleNotOnline')

        if toItem.typeID != fromItem.typeID:
            self.LogInfo('LinkWeapons::Modules not of same type', toItem, fromItem)
            return
        if toItem.groupID not in const.dgmGroupableGroupIDs:
            self.LogInfo('group not groupable', toItem, fromItem)
            return
        if shipID is None or shipID != fromItem.locationID:
            log.LogTraceback('LinkWeapons::Modules not located in the same place')
        masterID = self.GetMasterModuleID(shipID, toID)
        if not masterID:
            masterID = toID
        slaveID = self.IsInWeaponBank(shipID, fromID)
        if slaveID:
            if merge:
                info = self.remoteDogmaLM.MergeModuleGroups(shipID, masterID, slaveID)
            else:
                info = self.remoteDogmaLM.PeelAndLink(shipID, masterID, slaveID)
        else:
            info = self.remoteDogmaLM.LinkWeapons(shipID, masterID, fromID)
        self.OnWeaponBanksChanged(shipID, info)
Esempio n. 14
0
    def LoadPresetsFromUserSettings(self):
        try:
            if settings.user.overview.Get('overviewPresets', None) is not None:
                oldPresets = settings.user.overview.Get('overviewPresets',
                                                        {}).copy()
                settings.user.overview.Set('oldBackup_overviewPresets',
                                           oldPresets.copy())
                for presetKey, presetValue in oldPresets.iteritems():
                    presetValue.pop('ewarFilters', None)

                settings.user.overview.Delete('overviewPresets')
            else:
                oldPresets = {}
        except Exception as e:
            log.LogTraceback('Error when migrating overview presets, e = %s' %
                             e)
            settings.user.overview.Delete('overviewPresets')
            oldPresets = {}

        self.allPresets = settings.user.overview.Get('overviewProfilePresets',
                                                     oldPresets)
        self.unsavedPresets = settings.user.overview.Get(
            'overviewProfilePresets_notSaved', {})
        self.ReorderPresets(self.allPresets)
        self.ReorderPresets(self.unsavedPresets)
def UnterMachoRemoteServiceCall(self, dude, retvals, sess, nodeID, service,
                                method, args, keywords):
    try:
        if nodeID == sm.services['machoNet'].GetNodeID():
            if 'machoTimeout' in keywords:
                keywords = copy.copy(keywords)
                del keywords['machoTimeout']
            retvals.append(
                (0, nodeID,
                 apply(getattr(sess.ConnectToService(service), method), args,
                       keywords)))
        else:
            retvals.append(
                (0, nodeID,
                 self.RemoteServiceCallWithoutTheStars(sess, nodeID, service,
                                                       method, args,
                                                       keywords)))
    except StandardError as e:
        log.LogException()
        retvals.append((1, nodeID, e))
        sys.exc_clear()
    except Exception as e:
        log.LogTraceback()
        retvals.append((1, nodeID, e))
        raise
    finally:
        dude.Done()
Esempio n. 16
0
    def __UberMachoRemoteServiceCall(self, sess, service, method, nodes, *args, **keywords):
        retvals = []
        dude = UberDude(len(nodes), service, method)
        if not len(nodes):
            raise UnMachoDestination('No target nodes available for UberMachoRemoteServiceCall')
        uberMachoRaise = keywords.get('uberMachoRaise', False)
        if 'uberMachoRaise' in keywords:
            keywords = copy.copy(keywords)
            del keywords['uberMachoRaise']
        if 'machoTimeout' in keywords:
            keywords = copy.copy(keywords)
        else:
            keywords['machoTimeout'] = 60
        machoTimeout = keywords.get('machoTimeout', 60)
        for each in nodes:
            uthread.worker(blue.pyos.taskletTimer.GetCurrent() + '::RPC', UnterMachoRemoteServiceCall, self, dude, retvals, sess, each, service, method, args, keywords)

        if dude.Await(machoTimeout) == 2:
            log.LogTraceback('Local Timeout')
            n = copy.copy(nodes)
            for r in retvals:
                n.remove(r[1])

            for nodeID in n:
                self.machoNet.LogError('Node ', nodeID, " has not completed it's uber-macho call")
                retvals.append((1, nodeID, RuntimeError('Local Timeout')))

        if uberMachoRaise:
            for isexception, nodeID, ret in retvals:
                if isexception:
                    raise UberMachoException(retvals)

        return retvals
Esempio n. 17
0
 def RemoveSubLocation(self, itemKey):
     flagID = itemKey[1]
     subLocation = self.subLocations.get(flagID, None)
     if subLocation is not None:
         if subLocation != itemKey:
             log.LogTraceback('RemoveSubLocation used for subloc with occupied flag %s' % strx((itemKey, subLocation)))
         del self.subLocations[flagID]
Esempio n. 18
0
    def __getattr__(self, attribute):
        try:
            log.LogTraceback()
        except StandardError:
            sys.exc_clear()

        raise RuntimeError("Attempted to access %s from a non-blocking call's result" % attribute)
Esempio n. 19
0
    def _SavePortraits(self, charIDs):
        length = len(charIDs)
        sm.GetService('loading').ProgressWnd(
            localization.GetByLabel('UI/Shared/GeneratingPicture'), '', 0,
            length)
        portraitSaveSize = self.GetPortraitSaveSize()
        for i, charID in enumerate(charIDs):
            imagePath = self.portraits.GetImage(charID,
                                                portraitSaveSize,
                                                forceUpdate=True)
            if imagePath:
                cacheFile = blue.paths.ResolvePath(imagePath)
                try:
                    shutil.copy2(
                        cacheFile,
                        blue.sysinfo.GetUserDocumentsDirectory() +
                        '/EVE/capture/Portraits/%s.jpg' % charID)
                except WindowsError as e:
                    log.LogTraceback('Failed to copy character image')
                    self.LogError(e, 'Failed to copy character image')

            sm.GetService('loading').ProgressWnd(
                localization.GetByLabel('UI/Shared/GeneratingPicture'), '',
                i + 1, length)

        sm.GetService('loading').ProgressWnd(
            localization.GetByLabel('UI/Shared/GeneratingPicture'), '', length,
            length)
Esempio n. 20
0
    def _MakeShipActive(self, shipID, oldShipID):
        myCharID = session.charid
        self.LoadItem(myCharID)
        uthread.Lock(self, 'makeShipActive')
        try:
            while not session.IsItSafe():
                self.LogInfo('MakeShipActive - session is mutating. Sleeping for 250ms')
                blue.pyos.synchro.SleepSim(250)

            if shipID is None:
                log.LogTraceback('Unexpectedly got shipID = None')
                return
            self.shipIDBeingDisembarked = self.GetCurrentShipID()
            shipDogmaItem = self.GetDogmaItem(shipID)
            self.StartPassiveEffects(shipID, shipDogmaItem.typeID)
            self.scatterAttributeChanges = False
            try:
                self.selectedDronesTracker.Clear()
                if oldShipID is not None:
                    self.UnfitItemFromLocation(oldShipID, myCharID)
                    if shipID != oldShipID:
                        self.UnloadItem(oldShipID)
                self.ApplyBrainEffects(shipID, myCharID)
            finally:
                self.shipIDBeingDisembarked = None
                self.scatterAttributeChanges = True

        finally:
            uthread.UnLock(self, 'makeShipActive')
Esempio n. 21
0
def CountSessions(attr, val):
    """
        Counts all sessions which have attribute 'attr' in val
    """
    cnt = 0
    for v in val:
        try:
            r = []
            for sid in sessionsByAttribute[attr].get(v, {}).iterkeys():
                if sid in sessionsBySID:
                    cnt += 1
                else:
                    r.append(sid)

            for each in r:
                del sessionsByAttribute[attr][v][each]

        except:
            srv = sm.services['sessionMgr']
            srv.LogError('Session map borked')
            srv.LogError('sessionsByAttribute=', sessionsByAttribute)
            srv.LogError('sessionsBySID=', sessionsBySID)
            log.LogTraceback()
            raise

    return cnt
Esempio n. 22
0
    def DeleteFolder(self, folderID):
        folder = self.folders[folderID]
        deleteFolder = True
        if folder.ownerID == session.charid:
            bookmarks = self.bookmarkMgr.DeleteFolder(folderID)
        else:
            bookmarkIDs = set()
            isModerator = util.IsBookmarkModerator(session.corprole)
            for bookmarkID, bookmark in self.bookmarkCache.iteritems():
                if bookmark.folderID != folderID:
                    continue
                if not isModerator and getattr(bookmark, 'creatorID', None) != session.charid:
                    raise UserError('CantDeleteCorpBookmarksNotDirector')
                bookmarkIDs.add(bookmarkID)

            deleteFolder, bookmarks = self.corpBookmarkMgr.DeleteFolder(folderID, bookmarkIDs)
        if deleteFolder:
            try:
                del self.folders[folderID]
            except KeyError:
                log.LogTraceback('DeleteFolder - Failed to del folder')
                sys.exc_clear()

        else:
            uthread.new(eve.Message, 'BookmarkFolderNotDeleted')
        for bookmark in bookmarks:
            try:
                del self.bookmarkCache[bookmark.bookmarkID]
            except KeyError:
                self.LogInfo('DeleteFolder - bookmark not there', bookmark.bookmarkID)
                sys.exc_clear()

        self.RefreshWindow()
Esempio n. 23
0
 def ApplyAttributes(self, attributes):
     Container.ApplyAttributes(self, attributes)
     size = self.width
     if self.width != self.height:
         log.LogTraceback(
             "ShipModuleReactivationTimer don't have width and height as the same value"
         )
     maskSize = round(size * 1.28)
     Sprite(parent=self,
            name='maskSprite',
            align=uiconst.CENTER,
            pos=(0, 0, maskSize, maskSize),
            texturePath=
            'res:/UI/Texture/classes/ShipUI/slotSolidBackground.png',
            color=(0, 0, 0, 1))
     gaugeRadius = self.height / 2 - 3
     self.gauge = DashedCircle(parent=self,
                               dashCount=18,
                               dashSizeFactor=4.0,
                               range=math.pi * 2,
                               lineWidth=6,
                               radius=gaugeRadius,
                               startAngle=math.pi / 2,
                               startColor=(1, 1, 1, 0.3),
                               endColor=(1, 1, 1, 0.3))
     self.endTime = None
Esempio n. 24
0
    def __GetMailServer(self):
        if not self.mail_server:
            try:
                local_hostname = blue.pyos.GetEnv().get('COMPUTERNAME', '?')
                self.mail_server = None
                server = None
                if hasattr(prefs, 'alertEmailServer'):
                    server = str(prefs.alertEmailServer)
                    self.LogInfo('Alert service using mail server from prefs.ini:', prefs.alertEmailServer)
                elif self.location == LOCATION_TQ:
                    server = '10.210.10.251'
                    self.LogInfo('Alert service using default TQ mailserver', server)
                elif self.location == LOCATION_BFC:
                    server = '10.210.10.251'
                    self.LogInfo('Alert service using default BFC mailserver', server)
                elif self.location == LOCATION_CCP:
                    server = 'rkv-it-exch.ccp.ad.local'
                    self.LogInfo('Alert service using default CCP mailserver', server)
                if server:
                    if sys.version_info[:3] == (2, 2, 1):
                        self.mail_server = smtplib.SMTP(server)
                    else:
                        self.mail_server = smtplib.SMTP(server, local_hostname=local_hostname)
            except StandardError:
                log.LogTraceback('Mail server not working.', severity=log.LGWARN)
                sys.exc_clear()
                self.mail_server = None

        return self.mail_server
Esempio n. 25
0
    def RestorePinFromRow(self, pinRow):
        pinID = self.PrimePin(pinRow.id, pinRow.typeID, pinRow.ownerID, pinRow.latitude, pinRow.longitude, lastRunTime=pinRow.lastRunTime, state=pinRow.state)
        if pinID is None:
            log.LogTraceback('Unable to prime pin being loaded from data')
            return
        groupID = cfg.invtypes.Get(pinRow.typeID).groupID
        if groupID == const.groupProcessPins:
            if getattr(pinRow, 'schematicID', None) is not None:
                self.pins[pinRow.id].SetSchematic(cfg.schematics.Get(pinRow.schematicID))
            if getattr(pinRow, 'hasReceivedInputs', None) is not None:
                self.pins[pinRow.id].hasReceivedInputs = pinRow.hasReceivedInputs
            if getattr(pinRow, 'receivedInputsLastCycle', None) is not None:
                self.pins[pinRow.id].receivedInputsLastCycle = pinRow.receivedInputsLastCycle
        elif groupID == const.groupCommandPins or groupID == const.groupSpaceportPins:
            self.pins[pinRow.id].lastLaunchTime = pinRow.lastLaunchTime
            if groupID == const.groupCommandPins:
                self.commandPin = self.pins[pinRow.id]
        elif groupID == const.groupExtractionControlUnitPins:
            if getattr(pinRow, 'heads', None) is not None:
                self.SetHeads(pinRow.id, pinRow.heads)
            if getattr(pinRow, 'programType', None) is None:
                self.LogInfo('Pin', pinRow.id, 'has none program type, clearing program')
                self.pins[pinRow.id].ClearProgram()
            else:
                self.LogInfo('Installing program on pin', pinRow.id, pinRow.programType, pinRow.cycleTime, pinRow.expiryTime, pinRow.qtyPerCycle, pinRow.headRadius, pinRow.installTime)
                self.pins[pinRow.id].InstallProgram(pinRow.programType, pinRow.cycleTime, pinRow.expiryTime, pinRow.qtyPerCycle, pinRow.headRadius, lastRunTime=pinRow.lastRunTime, installTime=pinRow.installTime)
        self.pins[pinRow.id].SetState(pinRow.state)
        for typeID, quantity in pinRow.contents.iteritems():
            self.pins[pinRow.id].SetContents(pinRow.contents)

        return pinID
Esempio n. 26
0
    def GetLinkMenu(self, parent, url):
        m = []
        if url.startswith('showinfo:'):
            ids = url[9:].split('//')
            try:
                typeID = int(ids[0])
                itemID = None
                bookmark = None
                filterFunc = None
                if len(ids) > 1:
                    itemID = int(ids[1])
                if len(ids) > 2:
                    invtype = cfg.invtypes.Get(typeID)
                    if invtype.categoryID == const.categoryBlueprint:
                        filterFunc = {
                            localization.GetByLabel('UI/Commands/ShowInfo')
                        }
                    else:
                        bookmark = self.GetBookmark(ids, itemID, typeID)
                m += sm.GetService('menu').GetMenuFormItemIDTypeID(
                    itemID,
                    typeID,
                    bookmark,
                    ignoreMarketDetails=0,
                    filterFunc=filterFunc)
                m += sm.GetService('menu').GetGMTypeMenu(typeID, divs=True)
                for item in m:
                    if item is not None:
                        if item[0] == localization.GetByLabel(
                                'UI/Inventory/ItemActions/SetNewPasswordForContainer'
                        ):
                            m.remove(item)

            except:
                log.LogTraceback(
                    'failed to convert string to ids in Browser:ShowInfo')
                return []

        else:
            if url.startswith('preview:'):
                return []
            if url.startswith('contract:'):
                m += [(MenuLabel('UI/Contracts/ShowContract'), self.Contract,
                       (url[9:], ))]
                return m
        for eachUrlOption in HINTLABELS.keys():
            if url.startswith(eachUrlOption):
                return m

        if self.ValidateURL(url):
            url = url.replace('&amp;', '&')
            url = self.GetFixedURL(parent, url)
            m += [(MenuLabel('UI/Browser/OpenLinkInNewTab'),
                   self.UrlHandlerDelegate, (parent, 'NewView', url, True))]
            m += [(MenuLabel('UI/Common/Open'), self.UrlHandlerDelegate,
                   (parent, 'GoTo', url, False))]
        if url.lower().startswith('http'):
            m += [(MenuLabel('/Carbon/UI/Commands/CopyURL'), self.CopyUrl,
                   (url, ))]
        return m
Esempio n. 27
0
    def SetSelectionByID(self, objectIDs):
        self.SetActiveHardGroup(None)
        self.selection = []
        self.selectionObjs = []
        bp = sm.StartService('michelle').GetBallpark()
        dunObjects = self.GetDunObjects()
        sleepTime = 0
        for objectID in objectIDs:
            objectWasAdded = False
            while not objectWasAdded and sleepTime < 5000:
                for slimItem in dunObjects:
                    if slimItem.dunObjectID == objectID:
                        self.AddSelected(slimItem.itemID)
                        objectWasAdded = True

                if not objectWasAdded:
                    sleepTime += 200
                    blue.synchro.SleepWallclock(200)
                    dunObjects = self.GetDunObjects()

            if not objectWasAdded:
                self.LogError(
                    'scenarioMgr could not add objectID', objectID,
                    "to the selection--can't find it in the dungeon!")
                log.LogTraceback()
Esempio n. 28
0
def GetQuote(blueprintTypeID, activityID, materialLevel=0):
    blueprint = cfg.invbptypes.Get(blueprintTypeID)
    skills = util.Rowset(['skillTypeID', 'level'])
    materials = util.Rowset(['materialTypeID', 'quantity', 'waste'])
    extras = util.Rowset(['extraTypeID', 'quantity', 'damage'])
    matIdx = {}
    if activityID == const.activityManufacturing:
        for row in cfg.invtypematerials.get(blueprint.productTypeID, []):
            matIdx[row.materialTypeID] = row.quantity

    if (blueprintTypeID, activityID) in cfg.ramtyperequirements:
        for row in cfg.ramtyperequirements[blueprintTypeID, activityID]:
            reqType = cfg.invtypes.Get(row.requiredTypeID)
            if reqType.categoryID == const.categorySkill:
                skills.append([row.requiredTypeID, row.quantity])
                if row.damagePerJob or row.recycle:
                    log.LogTraceback(
                        'Bogus skill data in facItemTypeRequirements: %s' %
                        row)
            else:
                if row.recycle:
                    for deduct in cfg.invtypematerials.get(
                            row.requiredTypeID, []):
                        if deduct.materialTypeID in matIdx:
                            matIdx[deduct.materialTypeID] -= deduct.quantity
                        else:
                            matIdx[deduct.materialTypeID] = deduct.quantity

                    if row.damagePerJob != 1.0:
                        log.LogTraceback(
                            'Bogus recycle data in facItemTypeRequirements: %s'
                            % row)
                extras.append(
                    [row.requiredTypeID, row.quantity, row.damagePerJob])

    wasteFactor = blueprint.wasteFactor / 100.0 / (materialLevel + 1)
    for materialTypeID, quantity in matIdx.items():
        if quantity > 0:
            waste = int(round(quantity * wasteFactor))
            materials.append([materialTypeID, quantity, waste])

    quote = util.KeyVal(skills=skills,
                        materials=materials,
                        extras=extras,
                        __doc__='RamQuote for [%s,%s]' %
                        (blueprintTypeID, activityID))
    return quote
    def Write(self, message, jitSession = 1):
        """
            Writes a MachoPacket to our transport, performing elementary packet
            corrections.
        """
        if macho.mode == 'proxy' and jitSession:
            if message.source.addressType == const.ADDRESS_TYPE_CLIENT:
                self._JitSessionToOtherSide(message.source.clientID)
            elif base.IsInClientContext() and session and hasattr(session, 'clientID'):
                clientID = session.clientID
                self._JitSessionToOtherSide(clientID)
                message.contextKey = clientID
                ls = localstorage.GetLocalStorage()
                message.applicationID = ls.get('applicationID', None)
                message.languageID = ls.get('languageID', None)
        if hasattr(self, 'userID'):
            message.userID = self.userID
        if message.source.addressType == const.ADDRESS_TYPE_ANY and not message.command % 2:
            message.source.nodeID = self.machoNet.nodeID
            message.source.addressType = const.ADDRESS_TYPE_NODE
            message.Changed()
        elif message.source.addressType == const.ADDRESS_TYPE_NODE and message.source.nodeID is None:
            message.source.nodeID = self.machoNet.nodeID
            message.Changed()
        thePickle = message.GetPickle()
        if message.command != const.cluster.MACHONETMSG_TYPE_MOVEMENTNOTIFICATION or MACHONET_LOGMOVEMENT:
            self.LogInfo('Write: ', message)
        if self.transportName != 'tcp:packet:machoNet' and message.compressedPart * 100 / len(thePickle) < self.compressionPercentageThreshold and len(thePickle) - message.compressedPart > self.compressionThreshold and not MACHONET_COMPRESSION_DISABLED:
            before = len(thePickle)
            try:
                with bluepy.Timer('machoNet::MachoTransport::Write::Compress'):
                    compressed = zlib.compress(thePickle, 1)
            except zlib.error as e:
                raise RuntimeError('Compression Failure: ' + strx(e))

            after = len(compressed)
            if after > before:
                self.LogInfo('Compress would have exploded data from ', before, ' to ', after, ' bytes.  Sending uncompressed.')
            elif (before - after) * 100 / before <= 5:
                self.LogInfo("Compress didn't help one bit.  Would have compressed data from ", before, ' to ', after, " bytes, which is insignificant.  Sending uncompressed, rather than wasting the recipient's CPU power for nothing.")
            else:
                thePickle = compressed
                self.machoNet.compressedBytes.Add(before - after)
        if self.transportName == 'tcp:packet:client' and macho.mode == 'proxy':
            for objectID, refID in message.oob.get('OID+', {}).iteritems():
                s = self.sessions.get(self.clientID, None)
                if s is not None:
                    s.RegisterMachoObject(objectID, None, refID)

        if self.largePacketLogSpamThreshold != None and len(thePickle) > self.largePacketLogSpamThreshold:
            log.LogTraceback(extraText='Packet larger than the %d byte largePacketLogSpamTreshhold being written out to wire (%d > %d)' % (self.largePacketLogSpamThreshold, len(thePickle), self.largePacketLogSpamThreshold))
        if len(thePickle) > self.dropPacketThreshold:
            if self.transportName == 'tcp:packet:client' or macho.mode == 'server' and (message.destination.addressType == const.ADDRESS_TYPE_CLIENT or message.destination.addressType == const.ADDRESS_TYPE_BROADCAST and message.destination.idtype not in ('nodeID', '+nodeID')):
                self.machoNet.LogError('Attempted to send a deadly (len=', len(thePickle), ') packet to client(s), PACKET DROPPED')
                self.machoNet.LogError('Packet =', repr(message)[:1024])
                self.machoNet.LogError('Pickle starts with =', repr(thePickle)[:1024])
                return
        self.transport.Write(thePickle)
        self.machoNet.dataSent.Add(len(thePickle))
Esempio n. 30
0
    def _MakeShipActive(self, shipID, shipState):
        self.LoadItem(session.charid)
        uthread.Lock(self, 'makeShipActive')
        self.shipIDBeingDisembarked = self.shipID
        try:
            if self.shipID == shipID:
                return
            while not session.IsItSafe():
                self.LogInfo('MakeShipActive - session is mutating. Sleeping for 250ms')
                blue.pyos.synchro.SleepSim(250)

            if shipID is None:
                log.LogTraceback('Unexpectedly got shipID = None')
                return
            charItem = self.dogmaItems[session.charid]
            oldShipID = charItem.locationID
            if oldShipID == shipID:
                return
            self.UpdateRemoteDogmaLocation()
            oldShipID = self.shipID
            self.shipID = shipID
            if shipState is not None:
                self.instanceCache, self.instanceFlagQuantityCache, self.wbData = shipState
            else:
                try:
                    self.instanceCache, self.instanceFlagQuantityCache, self.wbData = self.remoteShipMgr.ActivateShip(shipID, oldShipID)
                except Exception:
                    self.shipID = oldShipID
                    raise 

            charItems = charItem.GetFittedItems()
            self.scatterAttributeChanges = False
            try:
                self.LoadItem(self.shipID)
                if oldShipID is not None:
                    self.UnfitItemFromLocation(oldShipID, session.charid)
                for skill in charItems.itervalues():
                    for effectID in skill.activeEffects.keys():
                        self.StopEffect(effectID, skill.itemID)

                if shipID is not None:
                    self.OnCharacterEmbarkation(session.charid, shipID, switching=oldShipID is not None)
                    for skill in charItems.itervalues():
                        self.StartPassiveEffects(skill.itemID, skill.typeID)

                    shipInv = self.broker.invCache.GetInventoryFromId(shipID, locationID=session.stationid2)
                    self.LoadShipFromInventory(shipID, shipInv)
                    self.SetWeaponBanks(self.shipID, self.wbData)
                    sm.ChainEvent('ProcessActiveShipChanged', shipID, oldShipID)
                    self.UnloadItem(oldShipID)
                    if oldShipID:
                        sm.ScatterEvent('OnCapacityChange', oldShipID)
            finally:
                self.scatterAttributeChanges = True

            self.ClearInstanceCache()
        finally:
            self.shipIDBeingDisembarked = None
            uthread.UnLock(self, 'makeShipActive')