def getSubMenu(self, context, selection, rootMenu, i, pitem): msw = True if "wxMSW" in wx.PlatformInfo else False sMkt = Market.getInstance() effdata = sMkt.getSystemWideEffects() self.idmap = {} sub = wx.Menu() for swType in sorted(effdata): subItem = wx.MenuItem(sub, wx.ID_ANY, swType) grandSub = wx.Menu() subItem.SetSubMenu(grandSub) sub.AppendItem(subItem) for swData in sorted(effdata[swType], key=lambda tpl: tpl[2]): wxid = ContextMenu.nextID() swObj, swName, swClass = swData self.idmap[wxid] = (swObj, swName) grandSubItem = wx.MenuItem(grandSub, wxid, swClass) if msw: rootMenu.Bind(wx.EVT_MENU, self.handleSelection, grandSubItem) else: grandSub.Bind(wx.EVT_MENU, self.handleSelection, grandSubItem) grandSub.AppendItem(grandSubItem) return sub
def expandLookup(self, event): tree = self.availableImplantsTree sMkt = Market.getInstance() parent = event.Item child, _ = tree.GetFirstChild(parent) text = tree.GetItemText(child) if text == "dummy" or text == "itemdummy": tree.Delete(child) # if the dummy item is a market group, replace with actual market groups if text == "dummy": # Add 'real stoof!' instead currentMktGrp = sMkt.getMarketGroup(tree.GetPyData(parent), eager="children") for childMktGrp in sMkt.getMarketGroupChildren(currentMktGrp): iconId = self.addMarketViewImage(sMkt.getIconByMarketGroup(childMktGrp)) childId = tree.AppendItem(parent, childMktGrp.name, iconId, data=wx.TreeItemData(childMktGrp.ID)) if sMkt.marketGroupHasTypesCheck(childMktGrp) is False: tree.AppendItem(childId, "dummy") else: tree.AppendItem(childId, "itemdummy") # replace dummy with actual items if text == "itemdummy": currentMktGrp = sMkt.getMarketGroup(tree.GetPyData(parent)) items = sMkt.getItemsByMarketGroup(currentMktGrp) for item in items: iconId = self.addMarketViewImage(item.icon.iconFile) tree.AppendItem(parent, item.name, iconId, data=wx.TreeItemData(item)) tree.SortChildren(parent)
def run(self): # wait 1 second just in case a lot of modifications get made time.sleep(1) if self.stopRunning: return sMkt = Market.getInstance() sFit = Fit.getInstance() settings = HTMLExportSettings.getInstance() minimal = settings.getMinimalEnabled() dnaUrl = "https://o.smium.org/loadout/dna/" if minimal: HTML = self.generateMinimalHTML(sMkt, sFit, dnaUrl) else: HTML = self.generateFullHTML(sMkt, sFit, dnaUrl) try: FILE = open(settings.getPath(), "w") FILE.write(HTML.encode('utf-8')) FILE.close() except IOError: print("Failed to write to " + settings.getPath()) pass if self.callback: wx.CallAfter(self.callback, -1)
def display(self, srcContext, selection): if self.mainFrame.getActiveFit() is None or srcContext not in ( "fittingModule", "projectedModule"): return False modules = selection if srcContext == "fittingModule" else ( selection[0], ) validCharges = None checkedTypes = set() for mod in modules: # loop through modules and gather list of valid charges if mod.item.ID in checkedTypes: continue checkedTypes.add(mod.item.ID) currCharges = mod.getValidCharges() if len(currCharges) > 0: if validCharges is not None and validCharges != currCharges: return False validCharges = currCharges self.module = mod if validCharges is None: return False self.modules = modules self.charges = list( filter( lambda charge: Market.getInstance().getPublicityByItem(charge), validCharges)) return len(self.charges) > 0
def spawnMenu(self): sel = self.GetFirstSelected() menu = None sFit = Fit.getInstance() fit = sFit.getFit(self.mainFrame.getActiveFit()) if not fit: return if sel != -1: implant = fit.appliedImplants[sel] sMkt = Market.getInstance() sourceContext = "implantItem" if fit.implantSource == ImplantLocation.FIT else "implantItemChar" itemContext = sMkt.getCategoryByItem(implant.item).name menu = ContextMenu.getMenu((implant,), (sourceContext, itemContext)) elif sel == -1 and fit.implantSource == ImplantLocation.FIT: fitID = self.mainFrame.getActiveFit() if fitID is None: return context = (("implantView",),) menu = ContextMenu.getMenu([], *context) if menu is not None: self.PopupMenu(menu)
def spawnMenu(self): if self.activeFitID is None: return sMkt = Market.getInstance() selection = [] sel = self.GetFirstSelected() contexts = [] while sel != -1 and sel not in self.blanks: mod = self.mods[self.GetItemData(sel)] if not mod.isEmpty: srcContext = "fittingModule" itemContext = sMkt.getCategoryByItem(mod.item).name fullContext = (srcContext, itemContext) if srcContext not in tuple(fCtxt[0] for fCtxt in contexts): contexts.append(fullContext) if mod.charge is not None: srcContext = "fittingCharge" itemContext = sMkt.getCategoryByItem(mod.charge).name fullContext = (srcContext, itemContext) if srcContext not in tuple(fCtxt[0] for fCtxt in contexts): contexts.append(fullContext) selection.append(mod) sel = self.GetNextSelected(sel) sFit = Fit.getInstance() fit = sFit.getFit(self.activeFitID) contexts.append(("fittingShip", "Ship" if not fit.isStructure else "Citadel")) menu = ContextMenu.getMenu(selection, *contexts) self.PopupMenu(menu)
def RefreshBoosterFits(self, event=None): sFit = Fit.getInstance() sMkt = Market.getInstance() fitList = sFit.getBoosterFits() for id_ in self.fleet: choice = self.fleet[id_]['chFit'] chCurrSelection = choice.GetSelection() chCurrData = -1 if chCurrSelection != -1: chCurrData = choice.GetClientData(chCurrSelection) chCurrSelString = choice.GetString(chCurrSelection) choice.Clear() currSelFound = False choice.Append("None", -1) for fit in fitList: fit_id, name, type_ = fit ship = sMkt.getItem(type_) choice.Append(ship.name + ': ' + name, fit_id) if chCurrData == fit_id: currSelFound = True if chCurrSelection == -1: choice.SetSelection(0) else: if currSelFound: choice.SetStringSelection(chCurrSelString) else: choice.SetSelection(0)
def refreshPanel(self, fit): if fit is not None: self.fit = fit # Compose a list of all the data we need & request it typeIDs = [] typeIDs.append(fit.ship.item.ID) for mod in fit.modules: if not mod.isEmpty: typeIDs.append(mod.itemID) for drone in fit.drones: for _ in range(drone.amount): typeIDs.append(drone.itemID) for fighter in fit.fighters: for _ in range(fighter.amountActive): typeIDs.append(fighter.itemID) for cargo in fit.cargo: for _ in range(cargo.amount): typeIDs.append(cargo.itemID) sMkt = Market.getInstance() sMkt.getPrices(typeIDs, self.processPrices) self.labelEMStatus.SetLabel("Updating prices...") else: self.labelEMStatus.SetLabel("") self.labelPriceShip.SetLabel("0.0 ISK") self.labelPriceFittings.SetLabel("0.0 ISK") self.labelPriceTotal.SetLabel("0.0 ISK") self._cachedFittings = self._cachedShip = self._cachedTotal = 0 self.panel.Layout()
def groupHasFits(self, groupID): sMkt = Market.getInstance() grp = sMkt.getGroup(groupID) items = sMkt.getItemsByGroup(grp) for item in items: if self.countFitsWithShip(item.ID) > 0: return True return False
def importCrest(str): fit = json.loads(str) sMkt = Market.getInstance() f = Fit() f.name = fit['name'] try: try: f.ship = Ship(sMkt.getItem(fit['ship']['id'])) except ValueError: f.ship = Citadel(sMkt.getItem(fit['ship']['id'])) except: return None items = fit['items'] items.sort(key=lambda k: k['flag']) moduleList = [] for module in items: try: item = sMkt.getItem(module['type']['id'], eager="group.category") if module['flag'] == INV_FLAG_DRONEBAY: d = Drone(item) d.amount = module['quantity'] f.drones.append(d) elif module['flag'] == INV_FLAG_CARGOBAY: c = Cargo(item) c.amount = module['quantity'] f.cargo.append(c) else: try: m = Module(item) # When item can't be added to any slot (unknown item or just charge), ignore it except ValueError: continue # Add subsystems before modules to make sure T3 cruisers have subsystems installed if item.category.name == "Subsystem": if m.fits(f): f.modules.append(m) else: if m.isValidState(State.ACTIVE): m.state = State.ACTIVE moduleList.append(m) except: continue # Recalc to get slot numbers correct for T3 cruisers Fit.getInstance().recalc(f) for module in moduleList: if module.fits(f): f.modules.append(module) return f
def spawnMenu(self): sel = self.GetFirstSelected() if sel != -1: drone = self.drones[sel] sMkt = Market.getInstance() sourceContext = "droneItem" itemContext = sMkt.getCategoryByItem(drone.item).name menu = ContextMenu.getMenu((drone, ), (sourceContext, itemContext)) self.PopupMenu(menu)
def spawnMenu(self): sel = self.GetFirstSelected() if sel != -1: fighter = self.fighters[sel] sMkt = Market.getInstance() sourceContext = "fighterItem" itemContext = sMkt.getCategoryByItem(fighter.item).name menu = ContextMenu.getMenu((fighter, ), (sourceContext, itemContext)) self.PopupMenu(menu)
def scheduleSearch(self, event=None): sMkt = Market.getInstance() search = self.searchBox.GetLineText(0) # Make sure we do not count wildcard as search symbol realsearch = search.replace("*", "") # Show nothing if query is too short if len(realsearch) < 3: self.clearSearch() return sMkt.searchItems(search, self.populateSearch, ["Implant"])
def spawnMenu(self): sel = self.GetFirstSelected() if sel != -1: sFit = Fit.getInstance() fit = sFit.getFit(self.mainFrame.getActiveFit()) cargo = fit.cargo[sel] sMkt = Market.getInstance() sourceContext = "cargoItem" itemContext = sMkt.getCategoryByItem(cargo.item).name menu = ContextMenu.getMenu((cargo, ), (sourceContext, itemContext)) self.PopupMenu(menu)
def spawnMenu(self, item): self.skillTreeListCtrl.SelectItem(item) if self.skillTreeListCtrl.GetChildrenCount(item) > 0: return char = self.charEditor.entityEditor.getActiveEntity() sMkt = Market.getInstance() if char.name not in ("All 0", "All 5"): self.levelChangeMenu.selection = sMkt.getItem(self.skillTreeListCtrl.GetPyData(item)) self.PopupMenu(self.levelChangeMenu) else: self.statsMenu.selection = sMkt.getItem(self.skillTreeListCtrl.GetPyData(item)) self.PopupMenu(self.statsMenu)
def delayedText(self, mod, display, colItem): sMkt = Market.getInstance() def callback(item): price = sMkt.getPriceNow(item.ID) text = formatAmount(price.price, 3, 3, 9, currency=True) if price.price else "" if price.failed: text += " (!)" colItem.SetText(text) display.SetItem(colItem) sMkt.waitForPrice(mod.item, callback)
def __init__(self, parent): d.Display.__init__(self, parent) sMkt = Market.getInstance() self.things = sMkt.getItemsWithOverrides() self.items = self.things self.searchBox = parent.Parent.Parent.searchBox # Bind search actions self.searchBox.Bind(SBox.EVT_TEXT_ENTER, self.scheduleSearch) self.searchBox.Bind(SBox.EVT_SEARCH_BTN, self.scheduleSearch) self.searchBox.Bind(SBox.EVT_CANCEL_BTN, self.clearSearch) self.searchBox.Bind(SBox.EVT_TEXT, self.scheduleSearch) self.update(self.items)
def getText(self, stuff): if stuff.item is None or stuff.item.group.name == "Ship Modifiers": return "" sMkt = Market.getInstance() price = sMkt.getPriceNow(stuff.item.ID) if not price or not price.price or not price.isValid: return False price = price.price # Set new price variable with what we need if isinstance(stuff, Drone) or isinstance(stuff, Cargo): price *= stuff.amount return formatAmount(price, 3, 3, 9, currency=True)
def OnClear(self, event): dlg = wx.MessageDialog( self, "Are you sure you want to delete all overrides?", "Confirm Delete", wx.YES | wx.NO | wx.ICON_EXCLAMATION) if dlg.ShowModal() == wx.ID_YES: sMkt = Market.getInstance() items = sMkt.getItemsWithOverrides() # We can't just delete overrides, as loaded items will still have # them assigned. Deleting them from the database won't propagate # them due to the eve/user database disconnect. We must loop through # all items that have overrides and remove them for item in items: for _, x in item.overrides.items(): item.deleteOverride(x.attr) self.itemView.updateItems(True) self.pg.Clear()
def OnExport(self, event): sMkt = Market.getInstance() items = sMkt.getItemsWithOverrides() defaultFile = "pyfa_overrides.csv" dlg = wx.FileDialog(self, "Save Overrides As...", wildcard="pyfa overrides (*.csv)|*.csv", style=wx.FD_SAVE, defaultFile=defaultFile) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() with open(path, 'wb') as csvfile: writer = csv.writer(csvfile) for item in items: for key, override in item.overrides.iteritems(): writer.writerow( [item.ID, override.attrID, override.value])
def __init__(self, parent): wx.Panel.__init__(self, parent) vbox = wx.BoxSizer(wx.VERTICAL) self.SetSizer(vbox) # Add a search box on top self.search = SearchBox(self) vbox.Add(self.search, 0, wx.EXPAND) self.splitter = wx.SplitterWindow(self, style=wx.SP_LIVE_UPDATE) vbox.Add(self.splitter, 1, wx.EXPAND) # Grab market service instance and create child objects self.sMkt = Market.getInstance() self.searchMode = False self.marketView = MarketTree(self.splitter, self) self.itemView = ItemView(self.splitter, self) self.splitter.SplitHorizontally(self.marketView, self.itemView) self.splitter.SetMinimumPaneSize(250) # Setup our buttons for metaGroup selection # Same fix as for search box on macs, # need some pixels of extra space or everything clips and is ugly p = wx.Panel(self) box = wx.BoxSizer(wx.HORIZONTAL) p.SetSizer(box) vbox.Add(p, 0, wx.EXPAND) self.metaButtons = [] for name in self.sMkt.META_MAP.keys(): btn = wx.ToggleButton(p, wx.ID_ANY, name.capitalize(), style=wx.BU_EXACTFIT) setattr(self, name, btn) box.Add(btn, 1, wx.ALIGN_CENTER) btn.Bind(wx.EVT_TOGGLEBUTTON, self.toggleMetaButton) btn.metaName = name self.metaButtons.append(btn) # Make itemview to set toggles according to list contents self.itemView.setToggles() p.SetMinSize((wx.SIZE_AUTO_WIDTH, btn.GetSize()[1] + 5))
def importSets(self, text): sMkt = Market.getInstance() lines = text.splitlines() newSets = [] errors = 0 current = None lookup = {} for i, line in enumerate(lines): line = line.strip() try: if line == '' or line[0] == "#": # comments / empty string continue if line[:1] == "[" and line[-1:] == "]": current = es_ImplantSet(line[1:-1]) newSets.append(current) else: item = sMkt.getItem(line) current.implants.append(es_Implant(item)) except: errors += 1 continue for implant_set in self.getImplantSetList(): lookup[implant_set.name] = implant_set for implant_set in newSets: if implant_set.name in lookup: match = lookup[implant_set.name] for implant in implant_set.implants: match.implants.append(es_Implant(implant.item)) else: eds_queries.save(implant_set) eds_queries.commit() lenImports = len(newSets) if lenImports == 0: raise ImportError("No patterns found for import") if errors > 0: raise ImportError("%d sets imported from clipboard; %d errors" % (lenImports, errors))
def spawnMenu(self): sel = self.GetFirstSelected() menu = None if sel != -1: item = self.get(sel) if item is None: return sMkt = Market.getInstance() if isinstance(item, es_Drone): srcContext = "projectedDrone" itemContext = sMkt.getCategoryByItem(item.item).name context = ((srcContext, itemContext), ) elif isinstance(item, es_Fighter): srcContext = "projectedFighter" itemContext = sMkt.getCategoryByItem(item.item).name context = ((srcContext, itemContext), ) elif isinstance(item, es_Module): modSrcContext = "projectedModule" modItemContext = sMkt.getCategoryByItem(item.item).name modFullContext = (modSrcContext, modItemContext) if item.charge is not None: chgSrcContext = "projectedCharge" chgItemContext = sMkt.getCategoryByItem(item.charge).name chgFullContext = (chgSrcContext, chgItemContext) context = (modFullContext, chgFullContext) else: context = (modFullContext, ) else: fitSrcContext = "projectedFit" fitItemContext = item.name context = ((fitSrcContext, fitItemContext), ) context = context + (("projected", ), ) menu = ContextMenu.getMenu((item, ), *context) elif sel == -1: fitID = self.mainFrame.getActiveFit() if fitID is None: return context = (("projected", ), ) menu = ContextMenu.getMenu([], *context) if menu is not None: self.PopupMenu(menu)
def display(self, srcContext, selection): validContexts = ("marketItemMisc", "fittingModule", "fittingCharge", "droneItem", "implantItem", "boosterItem", "projectedModule", "projectedDrone", "projectedCharge", "cargoItem", "implantItemChar", "fighterItem", "projectedDrone") if srcContext not in validContexts or selection is None or len( selection) < 1: return False sMkt = Market.getInstance() item = getattr(selection[0], "item", selection[0]) mktGrp = sMkt.getMarketGroupByItem(item) # 1663 is Special Edition Festival Assets, we don't have root group for it if mktGrp is None or mktGrp.ID == 1663: return False doit = not selection[ 0].isEmpty if srcContext == "fittingModule" else True return doit
def display(self, srcContext, selection): if self.mainFrame.getActiveFit() is None or srcContext not in ( "fittingModule", ): return False # Check if list of variations is same for all of selection # If not - don't show the menu mkt = Market.getInstance() self.variations = None for i in selection: variations = mkt.getVariationsByItems([i.item]) if self.variations is None: self.variations = variations else: if variations != self.variations: return False self.selection = selection if len(self.variations) == 1: return False # no variations from current module return True
def importXml(text, callback=None, encoding="utf-8"): sMkt = Market.getInstance() doc = xml.dom.minidom.parseString(text.encode(encoding)) fittings = doc.getElementsByTagName("fittings").item(0) fittings = fittings.getElementsByTagName("fitting") fits = [] for i, fitting in enumerate(fittings): f = Fit() f.name = fitting.getAttribute("name") # <localized hint="Maelstrom">Maelstrom</localized> shipType = fitting.getElementsByTagName("shipType").item( 0).getAttribute("value") try: try: f.ship = Ship(sMkt.getItem(shipType)) except ValueError: f.ship = Citadel(sMkt.getItem(shipType)) except: continue hardwares = fitting.getElementsByTagName("hardware") moduleList = [] for hardware in hardwares: try: moduleName = hardware.getAttribute("type") try: item = sMkt.getItem(moduleName, eager="group.category") except: continue if item: if item.category.name == "Drone": d = Drone(item) d.amount = int(hardware.getAttribute("qty")) f.drones.append(d) elif hardware.getAttribute("slot").lower() == "cargo": # although the eve client only support charges in cargo, third-party programs # may support items or "refits" in cargo. Support these by blindly adding all # cargo, not just charges c = Cargo(item) c.amount = int(hardware.getAttribute("qty")) f.cargo.append(c) else: try: m = Module(item) # When item can't be added to any slot (unknown item or just charge), ignore it except ValueError: continue # Add subsystems before modules to make sure T3 cruisers have subsystems installed if item.category.name == "Subsystem": if m.fits(f): m.owner = f f.modules.append(m) else: if m.isValidState(State.ACTIVE): m.state = State.ACTIVE moduleList.append(m) except KeyboardInterrupt: continue # Recalc to get slot numbers correct for T3 cruisers Fit.getInstance().recalc(f) for module in moduleList: if module.fits(f): module.owner = f f.modules.append(module) fits.append(f) if callback: wx.CallAfter(callback, None) return fits
def __init__(self, parent): wx.Panel.__init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.TAB_TRAVERSAL) self.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW)) pmainSizer = wx.BoxSizer(wx.HORIZONTAL) availableSizer = wx.BoxSizer(wx.VERTICAL) self.searchBox = SearchBox(self) self.itemView = ItemView(self) self.itemView.Hide() availableSizer.Add(self.searchBox, 0, wx.EXPAND) availableSizer.Add(self.itemView, 1, wx.EXPAND) ''' self.availableImplantsSearch = wx.SearchCtrl(self, wx.ID_ANY, style=wx.TE_PROCESS_ENTER) self.availableImplantsSearch.ShowCancelButton(True) availableSizer.Add(self.availableImplantsSearch, 0, wx.BOTTOM | wx.EXPAND, 2) ''' self.availableImplantsTree = wx.TreeCtrl(self, wx.ID_ANY, style=wx.TR_DEFAULT_STYLE | wx.TR_HIDE_ROOT) root = self.availableRoot = self.availableImplantsTree.AddRoot("Available") self.availableImplantsImageList = wx.ImageList(16, 16) self.availableImplantsTree.SetImageList(self.availableImplantsImageList) availableSizer.Add(self.availableImplantsTree, 1, wx.EXPAND) pmainSizer.Add(availableSizer, 1, wx.ALL | wx.EXPAND, 5) buttonSizer = wx.BoxSizer(wx.VERTICAL) buttonSizer.AddSpacer((0, 0), 1) self.btnAdd = GenBitmapButton(self, wx.ID_ADD, BitmapLoader.getBitmap("fit_add_small", "gui"), style=wx.BORDER_NONE) buttonSizer.Add(self.btnAdd, 0) self.btnRemove = GenBitmapButton(self, wx.ID_REMOVE, BitmapLoader.getBitmap("fit_delete_small", "gui"), style=wx.BORDER_NONE) buttonSizer.Add(self.btnRemove, 0) buttonSizer.AddSpacer((0, 0), 1) pmainSizer.Add(buttonSizer, 0, wx.EXPAND, 0) characterImplantSizer = wx.BoxSizer(wx.VERTICAL) self.pluggedImplantsTree = AvailableImplantsView(self) characterImplantSizer.Add(self.pluggedImplantsTree, 1, wx.ALL | wx.EXPAND, 5) pmainSizer.Add(characterImplantSizer, 1, wx.EXPAND, 5) self.SetSizer(pmainSizer) # Populate the market tree sMkt = Market.getInstance() for mktGrp in sMkt.getImplantTree(): iconId = self.addMarketViewImage(sMkt.getIconByMarketGroup(mktGrp)) childId = self.availableImplantsTree.AppendItem(root, mktGrp.name, iconId, data=wx.TreeItemData(mktGrp.ID)) if sMkt.marketGroupHasTypesCheck(mktGrp) is False: self.availableImplantsTree.AppendItem(childId, "dummy") self.availableImplantsTree.SortChildren(self.availableRoot) # Bind the event to replace dummies by real data self.availableImplantsTree.Bind(wx.EVT_TREE_ITEM_EXPANDING, self.expandLookup) self.availableImplantsTree.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.itemSelected) self.itemView.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.itemSelected) # Bind add & remove buttons self.btnAdd.Bind(wx.EVT_BUTTON, self.itemSelected) self.btnRemove.Bind(wx.EVT_BUTTON, self.removeItem) # We update with an empty list first to set the initial size for Layout(), then update later with actual # implants for character. This helps with sizing issues. self.pluggedImplantsTree.update([]) self.bindContext() self.Layout() self.update()
def importEftCfg(shipname, contents, callback=None): """Handle import from EFT config store file""" # Check if we have such ship in database, bail if we don't sMkt = Market.getInstance() try: sMkt.getItem(shipname) except: return [] # empty list is expected # If client didn't take care of encoding file contents into Unicode, # do it using fallback encoding ourselves if isinstance(contents, str): contents = unicode(contents, "cp1252") fits = [] # List for fits fitIndices = [] # List for starting line numbers for each fit lines = re.split('[\n\r]+', contents) # Separate string into lines for line in lines: # Detect fit header if line[:1] == "[" and line[-1:] == "]": # Line index where current fit starts startPos = lines.index(line) fitIndices.append(startPos) for i, startPos in enumerate(fitIndices): # End position is last file line if we're trying to get it for last fit, # or start position of next fit minus 1 endPos = len(lines) if i == len(fitIndices) - 1 else fitIndices[i + 1] # Finally, get lines for current fitting fitLines = lines[startPos:endPos] try: # Create fit object f = Fit() # Strip square brackets and pull out a fit name f.name = fitLines[0][1:-1] # Assign ship to fitting try: f.ship = Ship(sMkt.getItem(shipname)) except ValueError: f.ship = Citadel(sMkt.getItem(shipname)) moduleList = [] for x in range(1, len(fitLines)): line = fitLines[x] if not line: continue # Parse line into some data we will need misc = re.match( "(Drones|Implant|Booster)_(Active|Inactive)=(.+)", line) cargo = re.match("Cargohold=(.+)", line) if misc: entityType = misc.group(1) entityState = misc.group(2) entityData = misc.group(3) if entityType == "Drones": droneData = re.match("(.+),([0-9]+)", entityData) # Get drone name and attempt to detect drone number droneName = droneData.group( 1) if droneData else entityData droneAmount = int( droneData.group(2)) if droneData else 1 # Bail if we can't get item or it's not from drone category try: droneItem = sMkt.getItem( droneName, eager="group.category") except: continue if droneItem.category.name != "Drone": continue # Add drone to the fitting d = Drone(droneItem) d.amount = droneAmount if entityState == "Active": d.amountActive = droneAmount elif entityState == "Inactive": d.amountActive = 0 f.drones.append(d) elif entityType == "Implant": # Bail if we can't get item or it's not from implant category try: implantItem = sMkt.getItem( entityData, eager="group.category") except: continue if implantItem.category.name != "Implant": continue # Add implant to the fitting imp = Implant(implantItem) if entityState == "Active": imp.active = True elif entityState == "Inactive": imp.active = False f.implants.append(imp) elif entityType == "Booster": # Bail if we can't get item or it's not from implant category try: boosterItem = sMkt.getItem( entityData, eager="group.category") except: continue # All boosters have implant category if boosterItem.category.name != "Implant": continue # Add booster to the fitting b = Booster(boosterItem) if entityState == "Active": b.active = True elif entityState == "Inactive": b.active = False f.boosters.append(b) # If we don't have any prefixes, then it's a module elif cargo: cargoData = re.match("(.+),([0-9]+)", cargo.group(1)) cargoName = cargoData.group( 1) if cargoData else cargo.group(1) cargoAmount = int( cargoData.group(2)) if cargoData else 1 # Bail if we can't get item try: item = sMkt.getItem(cargoName) except: continue # Add Cargo to the fitting c = Cargo(item) c.amount = cargoAmount f.cargo.append(c) else: withCharge = re.match("(.+),(.+)", line) modName = withCharge.group(1) if withCharge else line chargeName = withCharge.group( 2) if withCharge else None # If we can't get module item, skip it try: modItem = sMkt.getItem(modName) except: continue # Create module m = Module(modItem) # Add subsystems before modules to make sure T3 cruisers have subsystems installed if modItem.category.name == "Subsystem": if m.fits(f): f.modules.append(m) else: m.owner = f # Activate mod if it is activable if m.isValidState(State.ACTIVE): m.state = State.ACTIVE # Add charge to mod if applicable, on any errors just don't add anything if chargeName: try: chargeItem = sMkt.getItem( chargeName, eager="group.category") if chargeItem.category.name == "Charge": m.charge = chargeItem except: pass # Append module to fit moduleList.append(m) # Recalc to get slot numbers correct for T3 cruisers Fit.getInstance().recalc(f) for module in moduleList: if module.fits(f): f.modules.append(module) # Append fit to list of fits fits.append(f) if callback: wx.CallAfter(callback, None) # Skip fit silently if we get an exception except Exception: pass return fits
def importEft(eftString): sMkt = Market.getInstance() offineSuffix = " /OFFLINE" fit = Fit() eftString = eftString.strip() lines = re.split('[\n\r]+', eftString) info = lines[0][1:-1].split(",", 1) if len(info) == 2: shipType = info[0].strip() fitName = info[1].strip() else: shipType = info[0].strip() fitName = "Imported %s" % shipType try: ship = sMkt.getItem(shipType) try: fit.ship = Ship(ship) except ValueError: fit.ship = Citadel(ship) fit.name = fitName except: return # maintain map of drones and their quantities droneMap = {} cargoMap = {} moduleList = [] for i in range(1, len(lines)): ammoName = None extraAmount = None line = lines[i].strip() if not line: continue setOffline = line.endswith(offineSuffix) if setOffline is True: # remove offline suffix from line line = line[:len(line) - len(offineSuffix)] modAmmo = line.split(",") # matches drone and cargo with x{qty} modExtra = modAmmo[0].split(" x") if len(modAmmo) == 2: # line with a module and ammo ammoName = modAmmo[1].strip() modName = modAmmo[0].strip() elif len(modExtra) == 2: # line with drone/cargo and qty extraAmount = modExtra[1].strip() modName = modExtra[0].strip() else: # line with just module modName = modExtra[0].strip() try: # get item information. If we are on a Drone/Cargo line, throw out cargo item = sMkt.getItem(modName, eager="group.category") except: # if no data can be found (old names) continue if item.category.name == "Drone": extraAmount = int( extraAmount) if extraAmount is not None else 1 if modName not in droneMap: droneMap[modName] = 0 droneMap[modName] += extraAmount if len(modExtra) == 2 and item.category.name != "Drone": extraAmount = int( extraAmount) if extraAmount is not None else 1 if modName not in cargoMap: cargoMap[modName] = 0 cargoMap[modName] += extraAmount elif item.category.name == "Implant": fit.implants.append(Implant(item)) # elif item.category.name == "Subsystem": # try: # subsystem = Module(item) # except ValueError: # continue # # if subsystem.fits(fit): # fit.modules.append(subsystem) else: try: m = Module(item) except ValueError: continue # Add subsystems before modules to make sure T3 cruisers have subsystems installed if item.category.name == "Subsystem": if m.fits(fit): fit.modules.append(m) else: if ammoName: try: ammo = sMkt.getItem(ammoName) if m.isValidCharge(ammo) and m.charge is None: m.charge = ammo except: pass if setOffline is True and m.isValidState(State.OFFLINE): m.state = State.OFFLINE elif m.isValidState(State.ACTIVE): m.state = State.ACTIVE moduleList.append(m) # Recalc to get slot numbers correct for T3 cruisers Fit.getInstance().recalc(fit) for m in moduleList: if m.fits(fit): m.owner = fit if not m.isValidState(m.state): print("Error: Module", m, "cannot have state", m.state) fit.modules.append(m) for droneName in droneMap: d = Drone(sMkt.getItem(droneName)) d.amount = droneMap[droneName] fit.drones.append(d) for cargoName in cargoMap: c = Cargo(sMkt.getItem(cargoName)) c.amount = cargoMap[cargoName] fit.cargo.append(c) return fit
def importDna(string): sMkt = Market.getInstance() ids = map(int, re.findall(r'\d+', string)) for id in ids: try: try: try: Ship(sMkt.getItem(sMkt.getItem(id))) except ValueError: Citadel(sMkt.getItem(sMkt.getItem(id))) except ValueError: Citadel(sMkt.getItem(id)) string = string[string.index(str(id)):] break except: pass string = string[:string.index("::") + 2] info = string.split(":") f = Fit() try: try: f.ship = Ship(sMkt.getItem(int(info[0]))) except ValueError: f.ship = Citadel(sMkt.getItem(int(info[0]))) f.name = "{0} - DNA Imported".format(f.ship.item.name) except UnicodeEncodeError: def logtransform(s): if len(s) > 10: return s[:10] + "..." return s logger.exception("Couldn't import ship data %r", [logtransform(s) for s in info]) return None moduleList = [] for itemInfo in info[1:]: if itemInfo: itemID, amount = itemInfo.split(";") item = sMkt.getItem(int(itemID), eager="group.category") if item.category.name == "Drone": d = Drone(item) d.amount = int(amount) f.drones.append(d) elif item.category.name == "Charge": c = Cargo(item) c.amount = int(amount) f.cargo.append(c) else: for i in xrange(int(amount)): try: m = Module(item) except: continue # Add subsystems before modules to make sure T3 cruisers have subsystems installed if item.category.name == "Subsystem": if m.fits(f): f.modules.append(m) else: m.owner = f if m.isValidState(State.ACTIVE): m.state = State.ACTIVE moduleList.append(m) # Recalc to get slot numbers correct for T3 cruisers Fit.getInstance().recalc(f) for module in moduleList: if module.fits(f): module.owner = f if module.isValidState(State.ACTIVE): module.state = State.ACTIVE f.modules.append(module) return f