Esempio n. 1
0
    def refresh(self, stuff):
        """
        Displays fitting

        Sends data to d.Display.refresh where the rows and columns are set up, then does a
        bit of post-processing (colors)
        """
        self.Freeze()
        d.Display.refresh(self, stuff)

        sFit = Fit.getInstance()
        fit = sFit.getFit(self.activeFitID)
        slotMap = {}

        # test for too many modules (happens with t3s / CCP change in slot layout)
        for slotType in Slot.getTypes():
            slot = Slot.getValue(slotType)
            slotMap[slot] = fit.getSlotsFree(slot) < 0

        for i, mod in enumerate(self.mods):
            self.SetItemBackgroundColour(i, self.GetBackgroundColour())

            #  only consider changing color if we're dealing with a Module
            if type(mod) is Module:
                hasRestrictionOverriden = getattr(mod, 'restrictionOverridden',
                                                  None)
                # If module had broken fitting restrictions but now doesn't,
                # ensure it is now valid, and remove restrictionOverridden
                # variable. More in #1519
                if not fit.ignoreRestrictions and hasRestrictionOverriden:
                    clean = False
                    if mod.fits(fit, False):
                        if not mod.hardpoint:
                            clean = True
                        elif fit.getHardpointsFree(mod.hardpoint) >= 0:
                            clean = True
                    if clean:
                        del mod.restrictionOverridden
                        hasRestrictionOverriden = not hasRestrictionOverriden

                if slotMap[
                        mod.
                        slot] or hasRestrictionOverriden:  # Color too many modules as red
                    self.SetItemBackgroundColour(i, wx.Colour(204, 51, 51))
                elif sFit.serviceFittingOptions[
                        "colorFitBySlot"]:  # Color by slot it enabled
                    self.SetItemBackgroundColour(i, self.slotColour(mod.slot))

            # Set rack face to bold
            if isinstance(mod, Rack) and \
                    sFit.serviceFittingOptions["rackSlots"] and \
                    sFit.serviceFittingOptions["rackLabels"]:
                self.font.SetWeight(wx.FONTWEIGHT_BOLD)
                self.SetItemFont(i, self.font)
            else:
                self.font.SetWeight(wx.FONTWEIGHT_NORMAL)
                self.SetItemFont(i, self.font)

        self.Thaw()
        self.itemCount = self.GetItemCount()
Esempio n. 2
0
    def getText(self, stuff):
        if isinstance(stuff, Drone):
            return "%dx %s" % (stuff.amount, stuff.item.name)
        elif isinstance(stuff, Fighter):
            return "%d/%d %s" % \
                   (stuff.amountActive, stuff.getModifiedItemAttr("fighterSquadronMaxSize"), stuff.item.name)
        elif isinstance(stuff, Cargo):
            return "%dx %s" % (stuff.amount, stuff.item.name)
        elif isinstance(stuff, Fit):
            if self.projectedView:
                # we need a little more information for the projected view
                fitID = self.mainFrame.getActiveFit()
                info = stuff.getProjectionInfo(fitID)

                if info:
                    return "%dx %s (%s)" % (stuff.getProjectionInfo(
                        fitID).amount, stuff.name, stuff.ship.item.name)

                pyfalog.warning(
                    "Projected View trying to display things that aren't there. stuff: {}, info: {}",
                    repr(stuff), info)
                return "<unknown>"
            else:
                return "%s (%s)" % (stuff.name, stuff.ship.item.name)
        elif isinstance(stuff, Rack):
            if FitSvc.getInstance().serviceFittingOptions["rackLabels"]:
                if stuff.slot == Slot.MODE:
                    return u'─ Tactical Mode ─'
                else:
                    return u'─ {} Slots ─'.format(
                        Slot.getName(stuff.slot).capitalize())
            else:
                return ""
        elif isinstance(stuff, Module):
            if stuff.isEmpty:
                return "%s Slot" % Slot.getName(stuff.slot).capitalize()
            else:
                return stuff.item.name
        elif isinstance(stuff, Implant):
            return stuff.item.name
        elif isinstance(stuff, TargetResists):
            name = getattr(stuff, "name")
            if name is None:
                pyfalog.warning("no name for TargetResists instance")
                name = "?"
            return name
        else:
            item = getattr(stuff, "item", stuff)

            if FitSvc.getInstance(
            ).serviceFittingOptions["showMarketShortcuts"]:
                marketShortcut = getattr(item, "marketShortcut", None)

                if marketShortcut:
                    # use unicode subscript to display shortcut value
                    shortcut = unichr(marketShortcut + 8320) + u" "
                    del item.marketShortcut
                    return shortcut + item.name

            return item.name
Esempio n. 3
0
    def getText(self, stuff):
        if isinstance(stuff, Drone):
            return "%dx %s" % (stuff.amount, stuff.item.name)
        elif isinstance(stuff, Fighter):
            return "%d/%d %s" % \
                   (stuff.amountActive, stuff.getModifiedItemAttr("fighterSquadronMaxSize"), stuff.item.name)
        elif isinstance(stuff, Cargo):
            return "%dx %s" % (stuff.amount, stuff.item.name)
        elif isinstance(stuff, Fit):
            if self.projectedView:
                # we need a little more information for the projected view
                fitID = self.mainFrame.getActiveFit()
                info = stuff.getProjectionInfo(fitID)

                if info:
                    return "%dx %s (%s)" % (stuff.getProjectionInfo(fitID).amount, stuff.name, stuff.ship.item.name)

                pyfalog.warning("Projected View trying to display things that aren't there. stuff: {}, info: {}", repr(stuff),
                                info)
                return "<unknown>"
            else:
                return "%s (%s)" % (stuff.name, stuff.ship.item.name)
        elif isinstance(stuff, Rack):
            if FitSvc.getInstance().serviceFittingOptions["rackLabels"]:
                if stuff.slot == Slot.MODE:
                    return '─ Tactical Mode ─'
                else:
                    return '─ {} {} Slot{}─'.format(stuff.num, Slot.getName(stuff.slot).capitalize(), '' if stuff.num == 1 else 's')
            else:
                return ""
        elif isinstance(stuff, Module):
            if self.projectedView:
                # check for projected abyssal name
                name_check = stuff.item.name[0:-2]
                type = WhProjector.abyssal_mapping.get(name_check, None)
                if type:
                    sMkt = Market.getInstance()
                    type = sMkt.getItem(type)
                    return "{} {}".format(type.name, stuff.item.name[-1:])

            if stuff.isEmpty:
                return "%s Slot" % Slot.getName(stuff.slot).capitalize()
            else:
                return stuff.item.name
        elif isinstance(stuff, Implant):
            return stuff.item.name
        else:
            item = getattr(stuff, "item", stuff)

            if FitSvc.getInstance().serviceFittingOptions["showMarketShortcuts"]:
                marketShortcut = getattr(item, "marketShortcut", None)

                if marketShortcut:
                    # use unicode subscript to display shortcut value
                    shortcut = chr(marketShortcut + 8320) + " "
                    del item.marketShortcut
                    return shortcut + item.name

            return item.name
Esempio n. 4
0
    def refresh(self, stuff):
        """
        Displays fitting

        Sends data to d.Display.refresh where the rows and columns are set up, then does a
        bit of post-processing (colors)
        """
        self.Freeze()
        d.Display.refresh(self, stuff)

        sFit = Fit.getInstance()
        fit = sFit.getFit(self.activeFitID)
        slotMap = {}

        # test for too many modules (happens with t3s / CCP change in slot layout)
        for slotType in Slot.getTypes():
            slot = Slot.getValue(slotType)
            slotMap[slot] = fit.getSlotsFree(slot) < 0

        for i, mod in enumerate(self.mods):
            self.SetItemBackgroundColour(i, self.GetBackgroundColour())

            #  only consider changing color if we're dealing with a Module
            if type(mod) is Module:
                hasRestrictionOverriden = getattr(mod, 'restrictionOverridden', None)
                # If module had broken fitting restrictions but now doesn't,
                # ensure it is now valid, and remove restrictionOverridden
                # variable. More in #1519
                if not fit.ignoreRestrictions and hasRestrictionOverriden:
                    clean = False
                    if mod.fits(fit, False):
                        if not mod.hardpoint:
                            clean = True
                        elif fit.getHardpointsFree(mod.hardpoint) >= 0:
                            clean = True
                    if clean:
                        del mod.restrictionOverridden
                        hasRestrictionOverriden = not hasRestrictionOverriden

                if slotMap[mod.slot] or hasRestrictionOverriden:  # Color too many modules as red
                    self.SetItemBackgroundColour(i, wx.Colour(204, 51, 51))
                elif sFit.serviceFittingOptions["colorFitBySlot"]:  # Color by slot it enabled
                    self.SetItemBackgroundColour(i, self.slotColour(mod.slot))

            # Set rack face to bold
            if isinstance(mod, Rack) and \
                    sFit.serviceFittingOptions["rackSlots"] and \
                    sFit.serviceFittingOptions["rackLabels"]:
                self.font.SetWeight(wx.FONTWEIGHT_BOLD)
                self.SetItemFont(i, self.font)
            else:
                self.font.SetWeight(wx.FONTWEIGHT_NORMAL)
                self.SetItemFont(i, self.font)

        self.Thaw()
        self.itemCount = self.GetItemCount()
Esempio n. 5
0
    def refresh(self, stuff):
        """
        Displays fitting

        Sends data to d.Display.refresh where the rows and columns are set up, then does a
        bit of post-processing (colors)
        """
        self.Freeze()
        d.Display.refresh(self, stuff)

        sFit = Fit.getInstance()
        fit = sFit.getFit(self.activeFitID)
        slotMap = {}

        # test for too many modules (happens with t3s / CCP change in slot layout)
        for slotType in Slot.getTypes():
            slot = Slot.getValue(slotType)
            slotMap[slot] = fit.getSlotsFree(slot) < 0

        font = (self.GetClassDefaultAttributes()).font

        for i, mod in enumerate(self.mods):
            self.SetItemBackgroundColour(i, self.GetBackgroundColour())

            #  only consider changing color if we're dealing with a Module
            if type(mod) is Module:
                if slotMap[mod.slot] or getattr(
                        mod, 'restrictionOverridden',
                        None):  # Color too many modules as red
                    self.SetItemBackgroundColour(i, wx.Colour(204, 51, 51))
                elif sFit.serviceFittingOptions[
                        "colorFitBySlot"]:  # Color by slot it enabled
                    self.SetItemBackgroundColour(i, self.slotColour(mod.slot))

            # Set rack face to bold
            if isinstance(mod, Rack) and \
                    sFit.serviceFittingOptions["rackSlots"] and \
                    sFit.serviceFittingOptions["rackLabels"]:
                font.SetWeight(wx.FONTWEIGHT_BOLD)
                self.SetItemFont(i, font)
            else:
                font.SetWeight(wx.FONTWEIGHT_NORMAL)
                self.SetItemFont(i, font)

        self.Thaw()
        self.itemCount = self.GetItemCount()

        if 'wxMac' in wx.PlatformInfo:
            try:
                self.MakeSnapshot()
            except Exception as e:
                pyfalog.critical("Failed to make snapshot")
                pyfalog.critical(e)
Esempio n. 6
0
    def refresh(self, stuff):
        """
        Displays fitting

        Sends data to d.Display.refresh where the rows and columns are set up, then does a
        bit of post-processing (colors)
        """
        self.Freeze()
        d.Display.refresh(self, stuff)

        sFit = Fit.getInstance()
        fit = sFit.getFit(self.activeFitID)
        slotMap = {}

        # test for too many modules (happens with t3s / CCP change in slot layout)
        for slotType in Slot.getTypes():
            slot = Slot.getValue(slotType)
            slotMap[slot] = fit.getSlotsFree(slot) < 0

        font = (self.GetClassDefaultAttributes()).font

        for i, mod in enumerate(self.mods):
            self.SetItemBackgroundColour(i, self.GetBackgroundColour())

            #  only consider changing color if we're dealing with a Module
            if type(mod) is Module:
                if slotMap[mod.slot] or getattr(mod, 'restrictionOverridden', None):  # Color too many modules as red
                    self.SetItemBackgroundColour(i, wx.Colour(204, 51, 51))
                elif sFit.serviceFittingOptions["colorFitBySlot"]:  # Color by slot it enabled
                    self.SetItemBackgroundColour(i, self.slotColour(mod.slot))

            # Set rack face to bold
            if isinstance(mod, Rack) and \
                    sFit.serviceFittingOptions["rackSlots"] and \
                    sFit.serviceFittingOptions["rackLabels"]:
                font.SetWeight(wx.FONTWEIGHT_BOLD)
                self.SetItemFont(i, font)
            else:
                font.SetWeight(wx.FONTWEIGHT_NORMAL)
                self.SetItemFont(i, font)

        self.Thaw()
        self.itemCount = self.GetItemCount()

        if 'wxMac' in wx.PlatformInfo:
            try:
                self.MakeSnapshot()
            except Exception as e:
                pyfalog.critical("Failed to make snapshot")
                pyfalog.critical(e)
Esempio n. 7
0
    def getText(self, stuff):
        if isinstance(stuff, Drone):
            return "%dx %s" % (stuff.amount, stuff.item.name)
        elif isinstance(stuff, Fighter):
            return "%d/%d %s" % (
                stuff.amountActive,
                stuff.getModifiedItemAttr("fighterSquadronMaxSize"),
                stuff.item.name)
        elif isinstance(stuff, Cargo):
            return "%dx %s" % (stuff.amount, stuff.item.name)
        elif isinstance(stuff, s_Fit):
            if self.projectedView:
                # we need a little more information for the projected view
                fitID = self.mainFrame.getActiveFit()
                return "%dx %s (%s)" % (stuff.getProjectionInfo(fitID).amount,
                                        stuff.name, stuff.ship.item.name)
            else:
                return "%s (%s)" % (stuff.name, stuff.ship.item.name)
        elif isinstance(stuff, Rack):
            if s_Fit.getInstance().serviceFittingOptions["rackLabels"]:
                if stuff.slot == Slot.MODE:
                    return u'─ Tactical Mode ─'
                else:
                    return u'─ {} Slots ─'.format(
                        Slot.getName(stuff.slot).capitalize())
            else:
                return ""
        elif isinstance(stuff, Module):
            if stuff.isEmpty:
                return "%s Slot" % Slot.getName(stuff.slot).capitalize()
            else:
                return stuff.item.name
        elif isinstance(stuff, Implant):
            return stuff.item.name
        else:
            item = getattr(stuff, "item", stuff)

            if s_Fit.getInstance(
            ).serviceFittingOptions["showMarketShortcuts"]:
                marketShortcut = getattr(item, "marketShortcut", None)

                if marketShortcut:
                    # use unicode subscript to display shortcut value
                    shortcut = unichr(marketShortcut + 8320) + u" "
                    del item.marketShortcut
                    return shortcut + item.name

            return item.name
Esempio n. 8
0
    def getImageId(self, stuff):
        if isinstance(stuff, Drone):
            return -1
        elif isinstance(stuff, Fit):
            return self.shipImage
        elif isinstance(stuff, Rack):
            return -1
        elif isinstance(stuff, Implant):
            if stuff.character:  # if it has a character as it's parent
                return self.fittingView.imageList.GetImageIndex(
                    "character_small", "gui")
            else:
                return self.shipImage
        elif isinstance(stuff, Module):
            if stuff.isEmpty:
                return self.fittingView.imageList.GetImageIndex(
                    "slot_%s_small" % Slot.getName(stuff.slot).lower(), "gui")
            else:
                return self.loadIconFile(
                    stuff.item.icon.iconFile if stuff.item.icon else "")
        elif isinstance(stuff, TargetResists):
            return self.fittingView.imageList.GetImageIndex(
                "explosive_small", "gui")

        item = getattr(stuff, "item", stuff)
        if not hasattr(item, "icon"):
            pyfalog.critical("item class %s has no .icon attribute" %
                             (type(stuff).__name__, ))
            return -1
        return self.loadIconFile(item.icon.iconFile if item.icon else "")
Esempio n. 9
0
    def _exportEftBase(fit):
        offineSuffix = " /OFFLINE"
        export = "[%s, %s]\n" % (fit.ship.item.name, fit.name)
        stuff = {}
        sFit = Fit.getInstance()
        for module in fit.modules:
            slot = module.slot
            if slot not in stuff:
                stuff[slot] = []
            curr = module.item.name if module.item else (
                "[Empty %s slot]" %
                Slot.getName(slot).capitalize() if slot is not None else "")
            if module.charge and sFit.serviceFittingOptions["exportCharges"]:
                curr += ", %s" % module.charge.name
            if module.state == State.OFFLINE:
                curr += offineSuffix
            curr += "\n"
            stuff[slot].append(curr)

        for slotType in EFT_SLOT_ORDER:
            data = stuff.get(slotType)
            if data is not None:
                export += "\n"
                for curr in data:
                    export += curr

        if len(fit.drones) > 0:
            export += "\n\n"
            for drone in fit.drones:
                export += "%s x%s\n" % (drone.item.name, drone.amount)

        if len(fit.fighters) > 0:
            export += "\n\n"
            for fighter in fit.fighters:
                export += "%s x%s\n" % (fighter.item.name,
                                        fighter.amountActive)

        if export[-1] == "\n":
            export = export[:-1]

        return export
Esempio n. 10
0
    def getImageId(self, stuff):
        if isinstance(stuff, Drone):
            return -1
        elif isinstance(stuff, Fit):
            return self.shipImage
        elif isinstance(stuff, Rack):
            return -1
        elif isinstance(stuff, Implant):
            if stuff.character:  # if it has a character as it's parent
                return self.fittingView.imageList.GetImageIndex("character_small", "gui")
            else:
                return self.shipImage
        elif isinstance(stuff, Module):
            if stuff.isEmpty:
                return self.fittingView.imageList.GetImageIndex("slot_%s_small" % Slot.getName(stuff.slot).lower(),
                                                                "gui")
            else:
                return self.loadIconFile(stuff.item.iconID or "")

        item = getattr(stuff, "item", stuff)
        return self.loadIconFile(item.iconID)
Esempio n. 11
0
    def getImageId(self, stuff):
        if isinstance(stuff, Drone):
            return -1
        elif isinstance(stuff, Fit):
            return self.shipImage
        elif isinstance(stuff, Rack):
            return -1
        elif isinstance(stuff, Implant):
            if stuff.character:  # if it has a character as it's parent
                return self.fittingView.imageList.GetImageIndex("character_small", "gui")
            else:
                return self.shipImage
        elif isinstance(stuff, Module):
            if stuff.isEmpty:
                return self.fittingView.imageList.GetImageIndex("slot_%s_small" % Slot.getName(stuff.slot).lower(),
                                                                "gui")
            else:
                return self.loadIconFile(stuff.item.icon.iconFile if stuff.item.icon else "")

        item = getattr(stuff, "item", stuff)
        return self.loadIconFile(item.icon.iconFile if item.icon else "")
Esempio n. 12
0
def exportXml(iportuser, *fits):
    doc = xml.dom.minidom.Document()
    fittings = doc.createElement("fittings")
    # fit count
    fit_count = len(fits)
    fittings.setAttribute("count", "%s" % fit_count)
    doc.appendChild(fittings)
    sFit = svcFit.getInstance()

    for i, fit in enumerate(fits):
        try:
            fitting = doc.createElement("fitting")
            fitting.setAttribute("name", fit.name)
            fittings.appendChild(fitting)
            description = doc.createElement("description")
            # -- 170327 Ignored description --
            try:
                notes = fit.notes  # unicode

                if notes:
                    notes = notes[:397] + '...' if len(notes) > 400 else notes

                description.setAttribute(
                    "value",
                    re.sub("(\r|\n|\r\n)+", "<br>", notes)
                    if notes is not None else "")
            except Exception as e:
                pyfalog.warning("read description is failed, msg=%s\n" %
                                e.args)

            fitting.appendChild(description)
            shipType = doc.createElement("shipType")
            shipType.setAttribute("value", fit.ship.name)
            fitting.appendChild(shipType)

            charges = {}
            slotNum = {}
            for module in fit.modules:
                if module.isEmpty:
                    continue

                slot = module.slot

                if slot == Slot.SUBSYSTEM:
                    # Order of subsystem matters based on this attr. See GH issue #130
                    slotId = module.getModifiedItemAttr("subSystemSlot") - 125
                else:
                    if slot not in slotNum:
                        slotNum[slot] = 0

                    slotId = slotNum[slot]
                    slotNum[slot] += 1

                hardware = doc.createElement("hardware")
                hardware.setAttribute("type", module.item.name)
                slotName = Slot.getName(slot).lower()
                slotName = slotName if slotName != "high" else "hi"
                hardware.setAttribute("slot",
                                      "%s slot %d" % (slotName, slotId))
                fitting.appendChild(hardware)

                if module.charge and sFit.serviceFittingOptions[
                        "exportCharges"]:
                    if module.charge.name not in charges:
                        charges[module.charge.name] = 0
                    # `or 1` because some charges (ie scripts) are without qty
                    charges[module.charge.name] += module.numCharges or 1

            for drone in fit.drones:
                hardware = doc.createElement("hardware")
                hardware.setAttribute("qty", "%d" % drone.amount)
                hardware.setAttribute("slot", "drone bay")
                hardware.setAttribute("type", drone.item.name)
                fitting.appendChild(hardware)

            for fighter in fit.fighters:
                hardware = doc.createElement("hardware")
                hardware.setAttribute("qty", "%d" % fighter.amountActive)
                hardware.setAttribute("slot", "fighter bay")
                hardware.setAttribute("type", fighter.item.name)
                fitting.appendChild(hardware)

            for cargo in fit.cargo:
                if cargo.item.name not in charges:
                    charges[cargo.item.name] = 0
                charges[cargo.item.name] += cargo.amount

            for name, qty in list(charges.items()):
                hardware = doc.createElement("hardware")
                hardware.setAttribute("qty", "%d" % qty)
                hardware.setAttribute("slot", "cargo")
                hardware.setAttribute("type", name)
                fitting.appendChild(hardware)
        except Exception as e:
            pyfalog.error("Failed on fitID: %d, message: %s" % e.message)
            continue
        finally:
            if iportuser:
                processing_notify(
                    iportuser, IPortUser.PROCESS_EXPORT | IPortUser.ID_UPDATE,
                    (i, "convert to xml (%s/%s) %s" %
                     (i + 1, fit_count, fit.ship.name)))
    return doc.toprettyxml()
Esempio n. 13
0
    def getText(self, stuff):
        if isinstance(stuff, Drone):
            return "%dx %s" % (stuff.amount, stuff.item.name)
        elif isinstance(stuff, Fighter):
            return "%d/%d %s" % \
                   (stuff.amountActive, stuff.getModifiedItemAttr("fighterSquadronMaxSize"), stuff.item.name)
        elif isinstance(stuff, Cargo):
            return "%dx %s" % (stuff.amount, stuff.item.name)
        elif isinstance(stuff, Fit):
            if self.projectedView:
                # we need a little more information for the projected view
                fitID = self.mainFrame.getActiveFit()
                info = stuff.getProjectionInfo(fitID)

                if info:
                    return "%dx %s (%s)" % (stuff.getProjectionInfo(
                        fitID).amount, stuff.name, stuff.ship.item.name)

                pyfalog.warning(
                    "Projected View trying to display things that aren't there. stuff: {}, info: {}",
                    repr(stuff), info)
                return "<unknown>"
            else:
                return "%s (%s)" % (stuff.name, stuff.ship.item.name)
        elif isinstance(stuff, Rack):
            if FitSvc.getInstance().serviceFittingOptions["rackLabels"]:
                if stuff.slot == Slot.MODE:
                    return '─ Tactical Mode ─'
                else:
                    return '─ {} {} Slot{}─'.format(
                        stuff.num,
                        Slot.getName(stuff.slot).capitalize(),
                        '' if stuff.num == 1 else 's')
            else:
                return ""
        elif isinstance(stuff, Module):
            if self.projectedView:
                # check for projected abyssal name
                name_check = stuff.item.name[0:-2]
                type = WhProjector.abyssal_mapping.get(name_check, None)
                if type:
                    sMkt = Market.getInstance()
                    type = sMkt.getItem(type)
                    return "{} {}".format(type.name, stuff.item.name[-1:])

            if stuff.isEmpty:
                return "%s Slot" % Slot.getName(stuff.slot).capitalize()
            else:
                return stuff.item.name
        elif isinstance(stuff, Implant):
            return stuff.item.name
        else:
            item = getattr(stuff, "item", stuff)

            if FitSvc.getInstance(
            ).serviceFittingOptions["showMarketShortcuts"]:
                marketShortcut = getattr(item, "marketShortcut", None)

                if marketShortcut:
                    # use unicode subscript to display shortcut value
                    shortcut = chr(marketShortcut + 8320) + " "
                    del item.marketShortcut
                    return shortcut + item.name

            return item.name
Esempio n. 14
0
File: xml.py Progetto: bsmr-eve/Pyfa
def exportXml(iportuser, *fits):
    doc = xml.dom.minidom.Document()
    fittings = doc.createElement("fittings")
    # fit count
    fit_count = len(fits)
    fittings.setAttribute("count", "%s" % fit_count)
    doc.appendChild(fittings)
    sFit = svcFit.getInstance()

    for i, fit in enumerate(fits):
        try:
            fitting = doc.createElement("fitting")
            fitting.setAttribute("name", fit.name)
            fittings.appendChild(fitting)
            description = doc.createElement("description")
            # -- 170327 Ignored description --
            try:
                notes = fit.notes  # unicode

                if notes:
                    notes = notes[:397] + '...' if len(notes) > 400 else notes

                description.setAttribute(
                    "value", re.sub("(\r|\n|\r\n)+", "<br>", notes) if notes is not None else ""
                )
            except Exception as e:
                pyfalog.warning("read description is failed, msg=%s\n" % e.args)

            fitting.appendChild(description)
            shipType = doc.createElement("shipType")
            shipType.setAttribute("value", fit.ship.name)
            fitting.appendChild(shipType)

            charges = {}
            slotNum = {}
            for module in fit.modules:
                if module.isEmpty:
                    continue

                slot = module.slot

                if slot == Slot.SUBSYSTEM:
                    # Order of subsystem matters based on this attr. See GH issue #130
                    slotId = module.getModifiedItemAttr("subSystemSlot") - 125
                else:
                    if slot not in slotNum:
                        slotNum[slot] = 0

                    slotId = slotNum[slot]
                    slotNum[slot] += 1

                hardware = doc.createElement("hardware")
                hardware.setAttribute("type", module.item.name)
                slotName = Slot.getName(slot).lower()
                slotName = slotName if slotName != "high" else "hi"
                hardware.setAttribute("slot", "%s slot %d" % (slotName, slotId))
                fitting.appendChild(hardware)

                if module.charge and sFit.serviceFittingOptions["exportCharges"]:
                    if module.charge.name not in charges:
                        charges[module.charge.name] = 0
                    # `or 1` because some charges (ie scripts) are without qty
                    charges[module.charge.name] += module.numCharges or 1

            for drone in fit.drones:
                hardware = doc.createElement("hardware")
                hardware.setAttribute("qty", "%d" % drone.amount)
                hardware.setAttribute("slot", "drone bay")
                hardware.setAttribute("type", drone.item.name)
                fitting.appendChild(hardware)

            for fighter in fit.fighters:
                hardware = doc.createElement("hardware")
                hardware.setAttribute("qty", "%d" % fighter.amountActive)
                hardware.setAttribute("slot", "fighter bay")
                hardware.setAttribute("type", fighter.item.name)
                fitting.appendChild(hardware)

            for cargo in fit.cargo:
                if cargo.item.name not in charges:
                    charges[cargo.item.name] = 0
                charges[cargo.item.name] += cargo.amount

            for name, qty in list(charges.items()):
                hardware = doc.createElement("hardware")
                hardware.setAttribute("qty", "%d" % qty)
                hardware.setAttribute("slot", "cargo")
                hardware.setAttribute("type", name)
                fitting.appendChild(hardware)
        except Exception as e:
            pyfalog.error("Failed on fitID: %d, message: %s" % e.message)
            continue
        finally:
            if iportuser:
                processing_notify(
                    iportuser, IPortUser.PROCESS_EXPORT | IPortUser.ID_UPDATE,
                    (i, "convert to xml (%s/%s) %s" % (i + 1, fit_count, fit.ship.name))
                )
    return doc.toprettyxml()
Esempio n. 15
0
    def MakeSnapshot(self, maxColumns=1337):

        if self.FVsnapshot:
            del self.FVsnapshot

        tbmp = wx.EmptyBitmap(16, 16)
        tdc = wx.MemoryDC()
        tdc.SelectObject(tbmp)
        font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        tdc.SetFont(font)

        columnsWidths = []
        for i in range(len(self.DEFAULT_COLS)):
            columnsWidths.append(0)

        sFit = Fit.getInstance()
        try:
            fit = sFit.getFit(self.activeFitID)
        except Exception as e:
            pyfalog.critical("Failed to get fit")
            pyfalog.critical(e)

        if fit is None:
            return

        slotMap = {}
        for slotType in Slot.getTypes():
            slot = Slot.getValue(slotType)
            slotMap[slot] = fit.getSlotsFree(slot) < 0

        padding = 2
        isize = 16
        headerSize = max(isize, tdc.GetTextExtent("W")[0]) + padding * 2

        maxRowHeight = isize
        rows = 0
        for st in self.mods:
            for i, col in enumerate(self.activeColumns):
                if i > maxColumns:
                    break
                name = col.getText(st)

                if not isinstance(name, basestring):
                    name = ""

                nx, ny = tdc.GetTextExtent(name)
                imgId = col.getImageId(st)
                cw = 0
                if imgId != -1:
                    cw += isize + padding
                if name != "":
                    cw += nx + 4 * padding

                if imgId == -1 and name == "":
                    cw += isize + padding

                maxRowHeight = max(ny, maxRowHeight)
                columnsWidths[i] = max(columnsWidths[i], cw)

            rows += 1

        render = wx.RendererNative.Get()

        # Fix column widths (use biggest between header or items)

        for i, col in enumerate(self.activeColumns):
            if i > maxColumns:
                break

            name = col.columnText
            imgId = col.imageId

            if not isinstance(name, basestring):
                name = ""

            opts = wx.HeaderButtonParams()

            if name != "":
                opts.m_labelText = name

            if imgId != -1:
                opts.m_labelBitmap = wx.EmptyBitmap(isize, isize)

            width = render.DrawHeaderButton(self, tdc, (0, 0, 16, 16), sortArrow=wx.HDR_SORT_ICON_NONE, params=opts)

            columnsWidths[i] = max(columnsWidths[i], width)

        tdc.SelectObject(wx.NullBitmap)

        maxWidth = padding * 2

        for i in range(len(self.DEFAULT_COLS)):
            if i > maxColumns:
                break
            maxWidth += columnsWidths[i]

        mdc = wx.MemoryDC()
        mbmp = wx.EmptyBitmap(maxWidth, maxRowHeight * rows + padding * 4 + headerSize)

        mdc.SelectObject(mbmp)

        mdc.SetBackground(wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW)))
        mdc.Clear()

        mdc.SetFont(font)
        mdc.SetTextForeground(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT))

        cx = padding
        for i, col in enumerate(self.activeColumns):
            if i > maxColumns:
                break

            name = col.columnText
            imgId = col.imageId

            if not isinstance(name, basestring):
                name = ""

            opts = wx.HeaderButtonParams()
            opts.m_labelAlignment = wx.ALIGN_LEFT
            if name != "":
                opts.m_labelText = name

            if imgId != -1:
                bmp = col.bitmap
                opts.m_labelBitmap = bmp

            render.DrawHeaderButton(self, mdc, (cx, padding, columnsWidths[i], headerSize), wx.CONTROL_CURRENT, sortArrow=wx.HDR_SORT_ICON_NONE, params=opts)

            cx += columnsWidths[i]

        brush = wx.Brush(wx.Colour(224, 51, 51))
        pen = wx.Pen(wx.Colour(224, 51, 51))

        mdc.SetPen(pen)
        mdc.SetBrush(brush)

        cy = padding * 2 + headerSize
        for st in self.mods:
            cx = padding

            if slotMap[st.slot]:
                mdc.DrawRectangle(cx, cy, maxWidth - cx, maxRowHeight)

            for i, col in enumerate(self.activeColumns):
                if i > maxColumns:
                    break

                name = col.getText(st)
                if not isinstance(name, basestring):
                    name = ""

                imgId = col.getImageId(st)
                tcx = cx

                if imgId != -1:
                    self.imageList.Draw(imgId, mdc, cx, cy, wx.IMAGELIST_DRAW_TRANSPARENT, False)
                    tcx += isize + padding

                if name != "":
                    nx, ny = mdc.GetTextExtent(name)
                    rect = wx.Rect()
                    rect.top = cy
                    rect.left = cx + 2 * padding
                    rect.width = nx
                    rect.height = maxRowHeight + padding
                    mdc.DrawLabel(name, rect, wx.ALIGN_CENTER_VERTICAL)
                    tcx += nx + padding

                cx += columnsWidths[i]

            cy += maxRowHeight

        mdc.SelectObject(wx.NullBitmap)

        self.FVsnapshot = mbmp
Esempio n. 16
0
File: eft.py Progetto: bsmr-eve/Pyfa
def exportEft(fit, options):
    # EFT formatted export is split in several sections, each section is
    # separated from another using 2 blank lines. Sections might have several
    # sub-sections, which are separated by 1 blank line
    sections = []

    header = '[{}, {}]'.format(fit.ship.item.name, fit.name)

    # Section 1: modules, rigs, subsystems, services
    modsBySlotType = {}
    sFit = svcFit.getInstance()
    for module in fit.modules:
        modsBySlotType.setdefault(module.slot, []).append(module)
    modSection = []

    mutants = {}  # Format: {reference number: module}
    mutantReference = 1
    for slotType in SLOT_ORDER:
        rackLines = []
        modules = modsBySlotType.get(slotType, ())
        for module in modules:
            if module.item:
                mutated = bool(module.mutators)
                # if module was mutated, use base item name for export
                if mutated:
                    modName = module.baseItem.name
                else:
                    modName = module.item.name
                if mutated and options & Options.MUTATIONS.value:
                    mutants[mutantReference] = module
                    mutationSuffix = ' [{}]'.format(mutantReference)
                    mutantReference += 1
                else:
                    mutationSuffix = ''
                modOfflineSuffix = ' {}'.format(OFFLINE_SUFFIX) if module.state == State.OFFLINE else ''
                if module.charge and sFit.serviceFittingOptions['exportCharges']:
                    rackLines.append('{}, {}{}{}'.format(
                        modName, module.charge.name, modOfflineSuffix, mutationSuffix))
                else:
                    rackLines.append('{}{}{}'.format(modName, modOfflineSuffix, mutationSuffix))
            else:
                rackLines.append('[Empty {} slot]'.format(
                    Slot.getName(slotType).capitalize() if slotType is not None else ''))
        if rackLines:
            modSection.append('\n'.join(rackLines))
    if modSection:
        sections.append('\n\n'.join(modSection))

    # Section 2: drones, fighters
    minionSection = []
    droneLines = []
    for drone in sorted(fit.drones, key=lambda d: d.item.name):
        droneLines.append('{} x{}'.format(drone.item.name, drone.amount))
    if droneLines:
        minionSection.append('\n'.join(droneLines))
    fighterLines = []
    for fighter in sorted(fit.fighters, key=lambda f: f.item.name):
        fighterLines.append('{} x{}'.format(fighter.item.name, fighter.amountActive))
    if fighterLines:
        minionSection.append('\n'.join(fighterLines))
    if minionSection:
        sections.append('\n\n'.join(minionSection))

    # Section 3: implants, boosters
    if options & Options.IMPLANTS.value:
        charSection = []
        implantLines = []
        for implant in fit.implants:
            implantLines.append(implant.item.name)
        if implantLines:
            charSection.append('\n'.join(implantLines))
        boosterLines = []
        for booster in fit.boosters:
            boosterLines.append(booster.item.name)
        if boosterLines:
            charSection.append('\n'.join(boosterLines))
        if charSection:
            sections.append('\n\n'.join(charSection))

    # Section 4: cargo
    cargoLines = []
    for cargo in sorted(
        fit.cargo,
        key=lambda c: (c.item.group.category.name, c.item.group.name, c.item.name)
    ):
        cargoLines.append('{} x{}'.format(cargo.item.name, cargo.amount))
    if cargoLines:
        sections.append('\n'.join(cargoLines))

    # Section 5: mutated modules' details
    mutationLines = []
    if mutants and options & Options.MUTATIONS.value:
        for mutantReference in sorted(mutants):
            mutant = mutants[mutantReference]
            mutationLines.append(renderMutant(mutant, firstPrefix='[{}] '.format(mutantReference), prefix='  '))
    if mutationLines:
        sections.append('\n'.join(mutationLines))

    return '{}\n\n{}'.format(header, '\n\n\n'.join(sections))
Esempio n. 17
0
File: eft.py Progetto: poklj/Pyfa
def exportEft(fit, options):
    # EFT formatted export is split in several sections, each section is
    # separated from another using 2 blank lines. Sections might have several
    # sub-sections, which are separated by 1 blank line
    sections = []

    header = '[{}, {}]'.format(fit.ship.item.name, fit.name)

    # Section 1: modules, rigs, subsystems, services
    modsBySlotType = {}
    sFit = svcFit.getInstance()
    for module in fit.modules:
        modsBySlotType.setdefault(module.slot, []).append(module)
    modSection = []

    mutants = {}  # Format: {reference number: module}
    mutantReference = 1
    for slotType in SLOT_ORDER:
        rackLines = []
        modules = modsBySlotType.get(slotType, ())
        for module in modules:
            if module.item:
                mutated = bool(module.mutators)
                # if module was mutated, use base item name for export
                if mutated:
                    modName = module.baseItem.name
                else:
                    modName = module.item.name
                if mutated and options & Options.MUTATIONS.value:
                    mutants[mutantReference] = module
                    mutationSuffix = ' [{}]'.format(mutantReference)
                    mutantReference += 1
                else:
                    mutationSuffix = ''
                modOfflineSuffix = ' {}'.format(
                    OFFLINE_SUFFIX) if module.state == State.OFFLINE else ''
                if module.charge and sFit.serviceFittingOptions[
                        'exportCharges']:
                    rackLines.append('{}, {}{}{}'.format(
                        modName, module.charge.name, modOfflineSuffix,
                        mutationSuffix))
                else:
                    rackLines.append('{}{}{}'.format(modName, modOfflineSuffix,
                                                     mutationSuffix))
            else:
                rackLines.append('[Empty {} slot]'.format(
                    Slot.getName(slotType).capitalize(
                    ) if slotType is not None else ''))
        if rackLines:
            modSection.append('\n'.join(rackLines))
    if modSection:
        sections.append('\n\n'.join(modSection))

    # Section 2: drones, fighters
    minionSection = []
    droneLines = []
    for drone in sorted(fit.drones, key=lambda d: d.item.name):
        droneLines.append('{} x{}'.format(drone.item.name, drone.amount))
    if droneLines:
        minionSection.append('\n'.join(droneLines))
    fighterLines = []
    for fighter in sorted(fit.fighters, key=lambda f: f.item.name):
        fighterLines.append('{} x{}'.format(fighter.item.name,
                                            fighter.amountActive))
    if fighterLines:
        minionSection.append('\n'.join(fighterLines))
    if minionSection:
        sections.append('\n\n'.join(minionSection))

    # Section 3: implants, boosters
    if options & Options.IMPLANTS.value:
        charSection = []
        implantLines = []
        for implant in fit.implants:
            implantLines.append(implant.item.name)
        if implantLines:
            charSection.append('\n'.join(implantLines))
        boosterLines = []
        for booster in fit.boosters:
            boosterLines.append(booster.item.name)
        if boosterLines:
            charSection.append('\n'.join(boosterLines))
        if charSection:
            sections.append('\n\n'.join(charSection))

    # Section 4: cargo
    cargoLines = []
    for cargo in sorted(
            fit.cargo,
            key=lambda c:
        (c.item.group.category.name, c.item.group.name, c.item.name)):
        cargoLines.append('{} x{}'.format(cargo.item.name, cargo.amount))
    if cargoLines:
        sections.append('\n'.join(cargoLines))

    # Section 5: mutated modules' details
    mutationLines = []
    if mutants and options & Options.MUTATIONS.value:
        for mutantReference in sorted(mutants):
            mutant = mutants[mutantReference]
            mutationLines.append(
                renderMutant(mutant,
                             firstPrefix='[{}] '.format(mutantReference),
                             prefix='  '))
    if mutationLines:
        sections.append('\n'.join(mutationLines))

    return '{}\n\n{}'.format(header, '\n\n\n'.join(sections))
Esempio n. 18
0
    def MakeSnapshot(self, maxColumns=1337):
        if self.FVsnapshot:
            self.FVsnapshot = None

        tbmp = wx.Bitmap(16, 16)
        tdc = wx.MemoryDC()
        tdc.SelectObject(tbmp)
        tdc.SetFont(self.font)

        columnsWidths = []
        for i in range(len(self.DEFAULT_COLS)):
            columnsWidths.append(0)

        sFit = Fit.getInstance()
        try:
            fit = sFit.getFit(self.activeFitID)
        except Exception as e:
            pyfalog.critical("Failed to get fit")
            pyfalog.critical(e)
            return

        if fit is None:
            return

        slotMap = {}
        for slotType in Slot.getTypes():
            slot = Slot.getValue(slotType)
            slotMap[slot] = fit.getSlotsFree(slot) < 0

        padding = 2
        isize = 16
        headerSize = max(isize, tdc.GetTextExtent("W")[0]) + padding * 2

        maxRowHeight = isize
        rows = 0
        for st in self.mods:
            for i, col in enumerate(self.activeColumns):
                if i > maxColumns:
                    break
                name = col.getText(st)

                if not isinstance(name, str):
                    name = ""

                nx, ny = tdc.GetTextExtent(name)
                imgId = col.getImageId(st)
                cw = 0
                if imgId != -1:
                    cw += isize + padding
                if name != "":
                    cw += nx + 4 * padding

                if imgId == -1 and name == "":
                    cw += isize + padding

                maxRowHeight = max(ny, maxRowHeight)
                columnsWidths[i] = max(columnsWidths[i], cw)

            rows += 1

        render = wx.RendererNative.Get()

        # Fix column widths (use biggest between header or items)

        for i, col in enumerate(self.activeColumns):
            if i > maxColumns:
                break

            name = col.columnText
            imgId = col.imageId

            if not isinstance(name, str):
                name = ""

            opts = wx.HeaderButtonParams()

            if name != "":
                opts.m_labelText = name

            if imgId != -1:
                opts.m_labelBitmap = wx.Bitmap(isize, isize)

            width = render.DrawHeaderButton(self,
                                            tdc, (0, 0, 16, 16),
                                            sortArrow=wx.HDR_SORT_ICON_NONE,
                                            params=opts)

            columnsWidths[i] = max(columnsWidths[i], width)

        tdc.SelectObject(wx.NullBitmap)

        maxWidth = padding * 2

        for i in range(len(self.DEFAULT_COLS)):
            if i > maxColumns:
                break
            maxWidth += columnsWidths[i]

        mdc = wx.MemoryDC()
        mbmp = wx.Bitmap(maxWidth,
                         maxRowHeight * rows + padding * 4 + headerSize)

        mdc.SelectObject(mbmp)

        mdc.SetBackground(
            wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)))
        mdc.Clear()

        mdc.SetFont(self.font)
        mdc.SetTextForeground(
            wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT))

        cx = padding
        for i, col in enumerate(self.activeColumns):
            if i > maxColumns:
                break

            name = col.columnText
            imgId = col.imageId

            if not isinstance(name, str):
                name = ""

            opts = wx.HeaderButtonParams()
            opts.m_labelAlignment = wx.ALIGN_LEFT
            if name != "":
                opts.m_labelText = name

            if imgId != -1:
                bmp = col.bitmap
                opts.m_labelBitmap = bmp

            render.DrawHeaderButton(
                self,
                mdc, (cx, padding, columnsWidths[i], headerSize),
                wx.CONTROL_CURRENT,
                sortArrow=wx.HDR_SORT_ICON_NONE,
                params=opts)

            cx += columnsWidths[i]

        brush = wx.Brush(wx.Colour(224, 51, 51))
        pen = wx.Pen(wx.Colour(224, 51, 51))

        mdc.SetPen(pen)
        mdc.SetBrush(brush)

        cy = padding * 2 + headerSize
        for st in self.mods:
            cx = padding

            if slotMap[st.slot]:
                mdc.DrawRectangle(cx, cy, maxWidth - cx, maxRowHeight)

            for i, col in enumerate(self.activeColumns):
                if i > maxColumns:
                    break

                name = col.getText(st)
                if not isinstance(name, str):
                    name = ""

                imgId = col.getImageId(st)
                tcx = cx

                if imgId != -1:
                    self.imageList.Draw(imgId, mdc, cx, cy,
                                        wx.IMAGELIST_DRAW_TRANSPARENT, False)
                    tcx += isize + padding

                if name != "":
                    nx, ny = mdc.GetTextExtent(name)
                    rect = wx.Rect()
                    rect.top = cy
                    rect.left = cx + 2 * padding
                    rect.width = nx
                    rect.height = maxRowHeight + padding
                    mdc.DrawLabel(name, rect, wx.ALIGN_CENTER_VERTICAL)
                    tcx += nx + padding

                cx += columnsWidths[i]

            cy += maxRowHeight

        mdc.SelectObject(wx.NullBitmap)

        self.FVsnapshot = mbmp
Esempio n. 19
0
    def exportXml(cls, callback=None, *fits):
        doc = xml.dom.minidom.Document()
        fittings = doc.createElement("fittings")
        doc.appendChild(fittings)
        sFit = Fit.getInstance()

        for i, fit in enumerate(fits):
            try:
                fitting = doc.createElement("fitting")
                fitting.setAttribute("name", fit.name)
                fittings.appendChild(fitting)
                description = doc.createElement("description")
                description.setAttribute("value", "")
                fitting.appendChild(description)
                shipType = doc.createElement("shipType")
                shipType.setAttribute("value", fit.ship.item.name)
                fitting.appendChild(shipType)

                charges = {}
                slotNum = {}
                for module in fit.modules:
                    if module.isEmpty:
                        continue

                    slot = module.slot

                    if slot == Slot.SUBSYSTEM:
                        # Order of subsystem matters based on this attr. See GH issue #130
                        slotId = module.getModifiedItemAttr(
                            "subSystemSlot") - 125
                    else:
                        if slot not in slotNum:
                            slotNum[slot] = 0

                        slotId = slotNum[slot]
                        slotNum[slot] += 1

                    hardware = doc.createElement("hardware")
                    hardware.setAttribute("type", module.item.name)
                    slotName = Slot.getName(slot).lower()
                    slotName = slotName if slotName != "high" else "hi"
                    hardware.setAttribute("slot",
                                          "%s slot %d" % (slotName, slotId))
                    fitting.appendChild(hardware)

                    if module.charge and sFit.serviceFittingOptions[
                            "exportCharges"]:
                        if module.charge.name not in charges:
                            charges[module.charge.name] = 0
                        # `or 1` because some charges (ie scripts) are without qty
                        charges[module.charge.name] += module.numCharges or 1

                for drone in fit.drones:
                    hardware = doc.createElement("hardware")
                    hardware.setAttribute("qty", "%d" % drone.amount)
                    hardware.setAttribute("slot", "drone bay")
                    hardware.setAttribute("type", drone.item.name)
                    fitting.appendChild(hardware)

                for cargo in fit.cargo:
                    if cargo.item.name not in charges:
                        charges[cargo.item.name] = 0
                    charges[cargo.item.name] += cargo.amount

                for name, qty in charges.items():
                    hardware = doc.createElement("hardware")
                    hardware.setAttribute("qty", "%d" % qty)
                    hardware.setAttribute("slot", "cargo")
                    hardware.setAttribute("type", name)
                    fitting.appendChild(hardware)
            except:
                print("Failed on fitID: %d" % fit.ID)
                continue
            finally:
                if callback:
                    wx.CallAfter(callback, i)

        return doc.toprettyxml()