コード例 #1
0
def askSaveSchematic(initialDir, displayName, fileFormat):
    return askSaveFile(initialDir,
                       title=_('Save this schematic...'),
                       defaultName=displayName + "." + fileFormat,
                       filetype=_('Minecraft Schematics (*.{0})\0*.{0}\0\0').format(fileFormat),
                       suffix=fileFormat,
    )
コード例 #2
0
ファイル: clone.py プロジェクト: Crayder/MCEdit-Unified
    def perform(self, recordUndo=True):
        if self.level.saving:
            alert(_("Cannot perform action while saving is taking place"))
            return

        if recordUndo:
            self.canUndo = True
            self.undoLevel = self.extractUndo(self.level, BoundingBox(self.destPoint, self.sourceBox.size))

        blocksToCopy = None
        if not (self.copyAir and self.copyWater):
            blocksToCopy = range(pymclevel.materials.id_limit)
            if not self.copyAir:
                blocksToCopy.remove(0)
            if not self.copyWater:
                blocksToCopy.remove(8)
            if not self.copyWater:
                blocksToCopy.remove(9)

        with setWindowCaption("Copying - "):
            i = self.level.copyBlocksFromIter(
                self.sourceLevel,
                self.sourceBox,
                self.destPoint,
                blocksToCopy,
                create=True,
                biomes=self.copyBiomes,
                staticCommands=self.staticCommands,
                moveSpawnerPos=self.moveSpawnerPos,
                regenerateUUID=self.regenerateUUID,
                first=False,
            )
            showProgress(_("Copying {0:n} blocks...").format(self.sourceBox.volume), i)
コード例 #3
0
ファイル: player.py プロジェクト: Iciciliser/MCEdit-Unified
    def perform(self, recordUndo=True):
        if self.level.saving:
            alert(_("Cannot perform action while saving is taking place"))
            return
        try:
            level = self.tool.editor.level
            try:
                self.undoPos = level.getPlayerPosition(self.player)
                self.undoDim = level.getPlayerDimension(self.player)
                self.undoYP = level.getPlayerOrientation(self.player)
            except Exception as e:
                log.info(_("Couldn't get player position! ({0!r})").format(e))

            yaw, pitch = self.yp
            if yaw is not None and pitch is not None:
                level.setPlayerOrientation((yaw, pitch), self.player)
            level.setPlayerPosition(self.pos, self.player)
            level.setPlayerDimension(level.dimNo, self.player)
            self.tool.playerPos[tuple(self.pos)] = self.player
            self.tool.revPlayerPos[self.player] = self.pos
            self.tool.markerList.invalidate()
            self.canUndo = True

        except pymclevel.PlayerNotFound as e:
            print "Player move failed: ", e
コード例 #4
0
    def __init__(self, mcedit, *args, **kwargs):
        kwargs['rect'] = mcedit.rect
        albow.Widget.__init__(self, *args, **kwargs)
        self.anchor = 'tlbr'
        self.mcedit = mcedit
        self.root = self.get_root()

        helpColumn = []

        label = albow.Label(_("{0}/{1}/{2}/{3}/{4}/{5} to move").format(
            config.keys.forward.get(),
            config.keys.left.get(),
            config.keys.back.get(),
            config.keys.right.get(),
            config.keys.up.get(),
            config.keys.down.get(),
        ))
        label.anchor = 'whrt'
        label.align = 'r'
        helpColumn.append(label)

        def addHelp(text):
            label = albow.Label(text)
            label.anchor = 'whrt'
            label.align = "r"
            helpColumn.append(label)

        addHelp(_("{0} to slow down").format(config.keys.brake.get()))
        addHelp("Right-click to toggle camera control")
        addHelp("Mousewheel to control tool distance")
        addHelp(_("Hold {0} for details").format(config.keys.showBlockInfo.get()))

        helpColumn = albow.Column(helpColumn, align="r")
        helpColumn.topright = self.topright
        helpColumn.anchor = "whrt"
        # helpColumn.is_gl_container = True
        self.add(helpColumn)

        keysColumn = [albow.Label("")]
        buttonsColumn = [panels.ControlPanel.getHeader()]

        shortnames = []
        for world in self.mcedit.recentWorlds():
            shortname = os.path.basename(world)
            try:
                if pymclevel.MCInfdevOldLevel.isLevel(world):
                    lev = pymclevel.MCInfdevOldLevel(world, readonly=True)
                    shortname = lev.LevelName
                    if lev.LevelName != lev.displayName:
                        shortname = u"{0} ({1})".format(lev.LevelName, lev.displayName)
            except Exception, e:
                logging.warning(
                    'Couldn\'t get name from recent world: {0!r}'.format(e))

            if shortname == "level.dat":
                shortname = os.path.basename(os.path.dirname(world))

            if len(shortname) > 40:
                shortname = shortname[:37] + "..."
            shortnames.append(shortname)
コード例 #5
0
ファイル: options.py プロジェクト: Crayder/MCEdit-Unified
 def togglePortable(self):
     if sys.platform == "darwin":
         return False
     textChoices = [
         _("This will make your MCEdit \"portable\" by moving your settings and schematics into the same folder as {0}. Continue?").format(
             (sys.platform == "darwin" and _("the MCEdit application") or _("MCEditData"))),
         _("This will move your settings and schematics to your Documents folder. Continue?"),
     ]
     useExisting = False
     
     alertText = textChoices[directories.portable]
     if albow.ask(alertText) == "OK":
         if [directories.hasPreviousPortableInstallation, directories.hasPreviousFixedInstallation][directories.portable]():
             asked = albow.ask("Found a previous " + ["portable", "fixed"][directories.portable] + " installation", responses=["Use", "Overwrite", "Cancel"])
             if asked == "Use":
                 useExisting = True
             elif asked == "Overwrite":
                 useExisting = False
             elif asked == "Cancel":
                 return False
         try:
             [directories.goPortable, directories.goFixed][directories.portable](useExisting)
         except Exception, e:
             traceback.print_exc()
             albow.alert(_(u"Error while moving files: {0}").format(repr(e)))
コード例 #6
0
ファイル: player.py プロジェクト: Alexhb61/MCEdit-Unified
    def perform(self, recordUndo=True):
        if self.level.saving:
            alert(_("Cannot perform action while saving is taking place"))
            return

        if self.player == "Player":
            answer = ask(_("Are you sure you want to delete the default player?"), ["Yes", "Cancel"])
            if answer == "Cancel":
                return

        if recordUndo:
            self.undoTag = self.level.getPlayerTag(self.player)

        self.level.players.remove(self.player)
        if self.tool.panel:
            if self.player != "Player":
                self.tool.panel.players.remove(version_utils.getPlayerNameFromUUID(self.player))
            else:
                self.tool.panel.players.remove("Player")

            while self.tool.panel.table.index >= len(self.tool.panel.players):
                self.tool.panel.table.index -= 1
            if len(self.tool.panel.players) == 0:
                self.tool.hidePanel()
                self.tool.showPanel()
        self.tool.markerList.invalidate()

        pos = self.tool.revPlayerPos[self.player]
        del self.tool.playerPos[pos]
        if self.player != "Player":
            del self.tool.playerTexture[self.player]
        else:
            del self.level.root_tag["Data"]["Player"]
        del self.tool.revPlayerPos[self.player]
        self.canUndo = True
コード例 #7
0
def askSaveSchematic(initialDir, displayName, fileFormat):
    dt = datetime.now().strftime("%Y-%m-%d--%H-%M-%S")
    return askSaveFile(initialDir,
                       title=_('Save this schematic...'),
                       defaultName=displayName + "_" + dt + "." + fileFormat,
                       filetype=_('Minecraft Schematics (*.{0})\0*.{0}\0\0').format(fileFormat),
                       suffix=fileFormat,
    )
コード例 #8
0
 def _alertException(*args, **kw):
     try:
         return func(*args, **kw)
     except root.Cancel:
         alert("Canceled.")
     except pymclevel.infiniteworld.SessionLockLost as e:
         alert(e.message + _("\n\nYour changes cannot be saved."))
     except Exception, e:
         logging.exception("Exception:")
         ask(_("Error during {0}: {1!r}").format(func, e)[:1000], ["OK"], cancel=0)
コード例 #9
0
ファイル: clone.py プロジェクト: Crayder/MCEdit-Unified
    def statusText(self):
        if self.destPoint is None:
            return "Click to set this item down."
        if self.draggingFace is not None:
            return _("Mousewheel to move along the third axis. Hold {0} to only move along one axis.").format(
                _(config.keys.snapCloneToAxis.get())
            )

        return (
            "Click and drag to reposition the item. Double-click to pick it up. Click Clone or press Enter to confirm."
        )
コード例 #10
0
ファイル: tree.py プロジェクト: Nerocat/MCEdit-Unified
def setup_map_types_item(mp=None):
    if not mp:
        mp = item_types_map
    map_types_item = {}
    for k, v in mp.items():
        if v[0] in map_types_item.keys():
            _v = map_types_item.pop(v[0])
            map_types_item[u"%s (%s)"%(_(v[0]), _v[0].__name__)] = _v
            map_types_item[u"%s (%s)"%(_(v[0]), k.__name__)] = (k, v[1], v[2])
        else:
            map_types_item[v[0]] = (k, v[1], v[2])
    return map_types_item
コード例 #11
0
def askCreateWorld(initialDir):
    defaultName = name = _("Untitled World")
    i = 0
    while exists(join(initialDir, name)):
        i += 1
        name = defaultName + " " + str(i)

    return askSaveFile(initialDir,
                       title=_('Name this new world.'),
                       defaultName=name,
                       filetype=_('Minecraft World\0*.*\0\0'),
                       suffix="",
    )
コード例 #12
0
ファイル: clone.py プロジェクト: Crayder/MCEdit-Unified
    def perform(self, recordUndo=True):
        if self.level.saving:
            alert(_("Cannot perform action while saving is taking place"))
            return
        with setWindowCaption("COPYING - "):
            self.editor.freezeStatus(_("Copying %0.1f million blocks") % (float(self._dirtyBox.volume) / 1048576.0,))
            if recordUndo:
                chunks = set()
                for op in self.blockCopyOps:
                    chunks.update(op.dirtyBox().chunkPositions)
                self.undoLevel = self.extractUndoChunks(self.level, chunks)

            [i.perform(False) for i in self.blockCopyOps]
            [i.perform(recordUndo) for i in self.selectionOps]
            self.canUndo = True
コード例 #13
0
 def estimateText(self):
     delta = (datetime.now() - self.startTime)
     progressPercent = (int(self.progressFraction * 10000))
     if progressPercent > 10000:
         progressPercent = 10000
     left = delta * (10000 - progressPercent) / (progressPercent or 1)
     return _("Time left: {0}").format(left)
コード例 #14
0
 def build_field(itm):
     fields = []
     if type(itm) in field_types.keys():
         f, bounds = field_types[type(itm)]
         if bounds:
             fields = [f(ref=AttrRef(itm, 'value'), min=bounds[0], max=bounds[1]),]
         else:
             fields = [f(ref=AttrRef(itm, 'value')),]
     elif type(itm) in array_types.keys():
         idx = 0
         for _itm in itm.value.tolist():
             f, bounds = array_types[type(itm)]
             fields.append(f(ref=ItemRef(itm.value, idx)))
             idx += 1
     elif type(itm) in (TAG_Compound, TAG_List):
         for _itm in itm.value:
             fields.append(Label("%s"%(_itm.name or "%s #%03d"%(itm.name or _("Item"), itm.value.index(_itm))), align='l', doNotTranslate=True))
             fields += NBTExplorerToolPanel.build_field(_itm)
     elif type(itm) not in (str, unicode):
         if type(getattr(itm, 'value', itm)) not in (str, unicode, int, float):
             fld = Label
             kw = {'align': 'l'}
         else:
             fld = TextFieldWrapped
             kw = {}
         fields = [fld("%s"%getattr(itm, 'value', itm), doNotTranslate=True, **kw),]
     else:
         fields = [TextFieldWrapped("%s"%itm, doNotTranslata=True),]
     return fields
コード例 #15
0
ファイル: mcplatform.py プロジェクト: LaChal/mcedit
def askOpenFileWin32(title, schematics, initialDir):
    try:
        # if schematics:
        f = ('Levels and Schematics\0*.mclevel;*.dat;*.mine;*.mine.gz;*.schematic;*.zip;*.schematic.gz;*.inv\0' +
              '*.*\0*.*\0\0')
        #        else:
#            f = ('Levels (*.mclevel, *.dat;*.mine;*.mine.gz;)\0' +
#                 '*.mclevel;*.dat;*.mine;*.mine.gz;*.zip;*.lvl\0' +
#                 '*.*\0*.*\0\0')

        (filename, customfilter, flags) = win32gui.GetOpenFileNameW(
            hwndOwner=display.get_wm_info()['window'],
            InitialDir=initialDir,
            Flags=(win32con.OFN_EXPLORER
                   | win32con.OFN_NOCHANGEDIR
                   | win32con.OFN_FILEMUSTEXIST
                   | win32con.OFN_LONGNAMES
                   # |win32con.OFN_EXTENSIONDIFFERENT
                   ),
            Title=title,
            Filter=_(f),
            )
    except Exception, e:
        print "Open File: ", e
        pass
コード例 #16
0
ファイル: options.py プロジェクト: Dominic001/MCEdit-Unified
 def dismiss(self, *args, **kwargs):
     """Used to change the language."""
     lng = config.settings.langCode.get()
     try:
         o, n, sc = albow.translate.setLang(lng)
     except:
         o, n, sc = albow.translate.setLang(self.langs[lng])
     if not sc and n != "en_US":
         albow.alert(_("{} is not a valid language").format("%s [%s]" % (self.sgnal[n], n)))
         if o == n:
             o = "en_US"
         config.settings.langCode.set(o)
         albow.translate.setLang(o)
     elif o != n:
         editor = self.mcedit.editor
         if editor and editor.unsavedEdits:
             result = albow.ask("You must restart MCEdit to see language changes", ["Save and Restart", "Restart", "Later"])
         else:
             result = albow.ask("You must restart MCEdit to see language changes", ["Restart", "Later"])
         if result == "Save and Restart":
             editor.saveFile()
             self.mcedit.restart()
         elif result == "Restart":
             self.mcedit.restart()
         elif result == "Later":
             pass
     Dialog.dismiss(self, *args, **kwargs)
コード例 #17
0
def loadFile(fName):
    if not fName:
        fName = mcplatform.askOpenFile(title=_("Select a NBT (.dat) file..."), suffixes=['dat',])
    if fName:
        if not os.path.isfile(fName):
            alert("The selected object is not a file.\nCan't load it.")
            return
        dontSaveRootTag = False
        nbtObject = load(fName)
        if fName.endswith('.schematic'):
            nbtObject = TAG_Compound(name='Data', value=nbtObject)
            dontSaveRootTag = True
            dataKeyName = 'Data'
        elif nbtObject.get('Data', None):
            dataKeyName = 'Data'
        elif nbtObject.get('data', None):
            dataKeyName = 'data'
        else:
            nbtObject.name = 'Data'
            dataKeyName = 'Data'
            dontSaveRootTag = True
            nbtObject = TAG_Compound([nbtObject,])
#        dontSaveRootTag = not fName.endswith('.schematic')
        return nbtObject, dataKeyName, dontSaveRootTag, fName
    return [None,] * 4
コード例 #18
0
ファイル: clone.py プロジェクト: Crayder/MCEdit-Unified
    def toolSelected(self):
        box = self.selectionBox()
        if box is None:
            self.editor.toolbar.selectTool(-1)
            return

        if box.volume > self.maxBlocks:
            self.editor.mouseLookOff()
            alert(
                _("Selection exceeds {0:n} blocks. Increase the block buffer setting and try again.").format(
                    self.maxBlocks
                )
            )
            self.editor.toolbar.selectTool(-1)
            return

        self.rotation = 0
        self.repeatCount = 1
        self._scaleFactor = 1.0

        if self.placeImmediately:
            self.destPoint = box.origin
        else:
            self.destPoint = None

        self.updateSchematic()
        self.cloneCameraDistance = max(self.cloneCameraDistance, self.safeToolDistance())
        self.showPanel()
コード例 #19
0
ファイル: player.py プロジェクト: Iciciliser/MCEdit-Unified
    def editNBTData(self):
        player = self.selectedPlayer
        if player == 'Player (Single Player)':
            alert("Not yet implemented.\nUse the NBT Explorer to edit this player.")
        elif player == '[No players]':
            return
        else:
            player = self.level.getPlayerTag(self.selectedPlayer)
            if player is not None:
                self.pages.remove_page(self.nbtpage)

                def close():
                    self.pages.show_page(self.col)

                self.nbttree = NBTExplorerToolPanel(self.tool.editor, nbtObject=player, fileName=None,
                                              savePolicy=-1, dataKeyName=None,
                                              height=self.max_height, no_header=True, close_text="Go Back",
                                              close_action=close, load_text=None,
                                              copy_data=False)

                self.nbtpage = Column([self.nbttree,])
                self.nbtpage.shrink_wrap()
                self.pages.add_page("NBT Data", self.nbtpage)
                self.pages.show_page(self.nbtpage)
            else:
                alert(_("Unable to load player %s" % self.selectedPlayer()))
コード例 #20
0
 def editNBTData(self):
     player = self.selectedPlayer
     if player == 'Player (Single Player)':
         alert("Not yet implemented.\nUse the NBT Explorer to edit this player.")
     elif player == '[No players]':
         return
     else:
         path = os.path.join(os.path.split(self.level.filename)[0], 'playerdata')
         if not os.path.exists(path):
             path = os.path.join(os.path.split(self.level.filename)[0], 'players')
         if player + '.dat' in os.listdir(path):
             fName = os.path.join(path, player + '.dat')
             nbtObject, dataKeyName, dontSaveRootTag, fn = loadFile(fName)
             self.pages.remove_page(self.nbtpage)
             def close():
                 self.pages.show_page(self.col)
             self.nbttree = NBTExplorerToolPanel(self.tool.editor, nbtObject=nbtObject, fileName=fName,
                                           dontSaveRootTag=dontSaveRootTag, dataKeyName=dataKeyName,
                                           height=self.max_height, no_header=True, close_text="Go Back",
                                           close_action=close, load_text=None)
             self.nbtpage = Column([self.nbttree,])
             self.nbtpage.shrink_wrap()
             self.pages.add_page("NBT Data", self.nbtpage)
             self.pages.show_page(self.nbtpage)
         #elif self.selectedPlayer.isNew:
         else:
             alert(_("Error while getting player file.\n%s not found.")%(player + '.dat'), doNotTranslate=True)
コード例 #21
0
ファイル: mcplatform.py プロジェクト: fhfuih/MCEdit-Unified
    def run_dlg():
        chooser = gtk.FileChooserDialog(title,
                                        None, gtk.FILE_CHOOSER_ACTION_SAVE,
                                        (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                        gtk.STOCK_OPEN, gtk.RESPONSE_OK))
    
        chooser.set_default_response(gtk.RESPONSE_OK)
        chooser.set_current_folder(initialDir)
        chooser.set_current_name("world")  # For some reason the Windows isn't closing if this line ins missing or the parameter is ""

        # Add custom Filter
        file_filter = gtk.FileFilter()
        file_filter.set_name(_("Levels and Schematics"))
        for suffix in suffixes:
            file_filter.add_pattern("*." + suffix)
        chooser.add_filter(file_filter)

        # Add "All files" Filter
        file_filter = gtk.FileFilter()
        file_filter.set_name("All files")
        file_filter.add_pattern("*")
        chooser.add_filter(file_filter)

        response = chooser.run()
        if response == gtk.RESPONSE_OK:
            fls.append(chooser.get_filename())
        else:
            fls.append(None)
        chooser.destroy()
        gtk.main_quit()
コード例 #22
0
ファイル: mcplatform.py プロジェクト: fhfuih/MCEdit-Unified
def askOpenFileWin32(title, schematics, initialDir, suffixes=None):
    try:
        if not suffixes:
            f = (_('Levels and Schematics') + '\0*.mclevel;*.dat;*.mine;*.mine.gz;*.schematic;*.zip;*.schematic.gz;*.inv;*.nbt\0' +
                 '*.*\0*.*\0\0')
        else:
            f = "All\0"
            for suffix in suffixes:
                f += "*." + suffix + ";"
            f += "\0*.*\0\0"

        filename, customfilter, flags = win32gui.GetOpenFileNameW(
            hwndOwner=display.get_wm_info()['window'],
            InitialDir=initialDir,
            Flags=(win32con.OFN_EXPLORER
                   | win32con.OFN_NOCHANGEDIR
                   | win32con.OFN_FILEMUSTEXIST
                   | win32con.OFN_LONGNAMES
                   ),
            Title=title,
            Filter=f,
        )
    except Exception:
        pass
    else:
        return filename
コード例 #23
0
 def __init__(self, inventory, data):
     Panel.__init__(self)
     self.inventory = inventory
     slot, id, count, damage = data
     self.former_id_text = id
     self.slot = slot
     self.id = TextFieldWrapped(text=id, doNotTranslate=True, width=300)
     #&# Prototype for blocks/items names
     self.menu = None
     m = Menu("", [""])
     h = m.font.get_linesize()
     self.menu = Menu("", [""], scrolling=True, scroll_items=(self.root.local_to_global(self.root.bottomleft)[1] - self.root.local_to_global(self.bottomleft)[1] - (m.margin * 2)) / h)
     del m
     self.id.change_action = self.text_entered
     self.id.escape_action = self.close_menu
     self.menu.key_down = self.id.key_down
     #&#
     self.count = IntField(text="%s"%count, min=-64, max=64)
     self.damage = IntField(text="%s"%damage, min=-32768, max=32767)
     header = Label(_("Inventory Slot #%s")%slot, doNotTranslate=True)
     row = Row([Label("id"), self.id,
                Label("Count"), self.count,
                Label("Damage"), self.damage,
                ])
     buttons = Row([Button("Save", action=self.dismiss), Button("Cancel", action=self.cancel)])
     col = Column([header, row, buttons], spacing=2)
     self.add(col)
     self.shrink_wrap()
コード例 #24
0
ファイル: filter.py プロジェクト: LaChal/MCEdit-Unified
 def tryImport(name):
     try:
         return __import__(name)
     except Exception, e:
         print traceback.format_exc()
         alert(_(u"Exception while importing filter module {}. See console for details.\n\n{}").format(name, e))
         return object()
コード例 #25
0
    def toolSelected(self):
        box = self.selectionBox()
        if box is None:
            self.editor.toolbar.selectTool(-1)
            return

        if box.volume > self.maxBlocks:
            self.editor.mouseLookOff()
            alert(
                _("Selection exceeds {0:n} blocks. Increase the block buffer setting and try again."
                  ).format(self.maxBlocks))
            self.editor.toolbar.selectTool(-1)
            return

        self.rotation = 0
        self.repeatCount = 1
        self._scaleFactor = 1.0

        if self.placeImmediately:
            self.destPoint = box.origin
        else:
            self.destPoint = None

        self.updateSchematic()
        self.cloneCameraDistance = max(self.cloneCameraDistance,
                                       self.safeToolDistance())
        self.showPanel()
コード例 #26
0
ファイル: options.py プロジェクト: Techius/MCEdit-Unified
    def togglePortable(self):
        if sys.platform == "darwin":
            return False
        textChoices = [
            _("This will make your MCEdit \"portable\" by moving your settings and schematics into the same folder as {0}. Continue?").format(
                (sys.platform == "darwin" and _("the MCEdit application") or _("MCEditData"))),
            _("This will move your settings and schematics to your Documents folder. Continue?"),
        ]

        alertText = textChoices[directories.portable]
        if albow.ask(alertText) == "OK":
            try:
                [directories.goPortable, directories.goFixed][directories.portable]()
            except Exception, e:
                traceback.print_exc()
                albow.alert(_(u"Error while moving files: {0}").format(repr(e)))
コード例 #27
0
ファイル: filter.py プロジェクト: LaChal/MCEdit-Unified
    def reload(self):
        for i in list(self.subwidgets):
            self.remove(i)

        tool = self.tool

        if len(tool.filterModules) is 0:
            self.add(Label("No filter modules found!"))
            self.shrink_wrap()
            return

        if self.selectedFilterName is None or self.selectedFilterName not in tool.filterNames:
            self.selectedFilterName = tool.filterNames[0]

        self.filterOptionsPanel = None
        while self.filterOptionsPanel is None:
            module = self.tool.filterModules[self.selectedFilterName]
            try:
                self.filterOptionsPanel = FilterModuleOptions(self.tool, module)
            except Exception, e:
                alert(_("Error creating filter inputs for {0}: {1}").format(module, e))
                traceback.print_exc()
                self.tool.filterModules.pop(self.selectedFilterName)
                self.selectedFilterName = tool.filterNames[0]

            if len(tool.filterNames) == 0:
                raise ValueError("No filters loaded!")
コード例 #28
0
    def mouseDown(self, evt, pos, direction):
        pos = map(lambda p, d: p + d, pos, direction)
        op = PlayerSpawnMoveOperation(self, pos)
        try:
            op.perform()

            self.editor.addOperation(op)
            self.editor.addUnsavedEdit()
            self.markerList.invalidate()

        except SpawnPositionInvalid, e:
            if "Okay" != ask(str(e), responses=["Okay", "Fix it for me!"]):
                level = self.editor.level
                status = ""
                if not okayAt63(level, pos):
                    level.setBlockAt(pos[0], 63, pos[2], 1)
                    status += _("Block added at y=63.\n")

                if 59 < pos[1] < 63:
                    pos[1] = 63
                    status += _("Spawn point moved upward to y=63.\n")

                if not okayAboveSpawn(level, pos):
                    if pos[1] > 63 or pos[1] < 59:
                        lpos = (pos[0], pos[1] - 1, pos[2])
                        if level.blockAt(*pos) == 0 and level.blockAt(*lpos) != 0 and okayAboveSpawn(level, lpos):
                            pos = lpos
                            status += _("Spawn point shifted down by one block.\n")
                    if not okayAboveSpawn(level, pos):
                        for i in range(1, 4):
                            level.setBlockAt(pos[0], pos[1] + i, pos[2], 0)

                            status += _("Blocks above spawn point cleared.\n")

                self.editor.invalidateChunks([(pos[0] // 16, pos[2] // 16)])
                op = PlayerSpawnMoveOperation(self, pos)
                try:
                    op.perform()
                except SpawnPositionInvalid, e:
                    alert(str(e))
                    return

                self.editor.addOperation(op)
                self.editor.addUnsavedEdit()
                self.markerList.invalidate()
                if len(status):
                    alert(_("Spawn point fixed. Changes: \n\n") + status)
コード例 #29
0
def askOpenFile(title='Select a Minecraft level....', schematics=False, suffixes=None):
    title = _(title)
    global lastSchematicsDir, lastSaveDir

    if not suffixes:
        suffixes = ["mclevel", "dat", "mine", "mine.gz", "mcworld"]
        suffixesChanged = False
    else:
        suffixesChanged = True
    initialDir = lastSaveDir or minecraftSaveFileDir
    if schematics:
        initialDir = lastSchematicsDir or directories.schematicsDir

    def _askOpen(_suffixes):
        if schematics:
            _suffixes.append("schematic")
            _suffixes.append("schematic.gz")
            _suffixes.append("zip")

            _suffixes.append("inv")
            
            _suffixes.append("nbt")

            # BO support
            _suffixes.append("bo2")
            _suffixes.append("bo3")
            _suffixes.sort()

        if sys.platform == "win32":  # !#
            if suffixesChanged:
                sendSuffixes = _suffixes
            else:
                sendSuffixes = None
            return askOpenFileWin32(title, schematics, initialDir, sendSuffixes)

        elif hasGtk and not platChooser:  # !# #Linux (When GTK 2.4 or newer is installed)
            return askOpenFileGtk(title, _suffixes, initialDir)

        else:
            log.debug("Calling internal file chooser.")
            log.debug("'initialDir' is %s (%s)" % (repr(initialDir), type(initialDir)))
            try:
                iDir = initialDir.encode(enc)
            except Exception as e:
                iDir = initialDir
                log.debug("Could not encode 'initialDir' %s" % repr(initialDir))
                log.debug("Encode function returned: %s" % e)
            if "All files (*.*)" not in _suffixes and "*.* (*.*)" not in _suffixes:
                _suffixes.append("All files (*.*)")
            return request_old_filename(suffixes=_suffixes, directory=iDir)

    filename = _askOpen(suffixes)
    if filename:
        if schematics:
            lastSchematicsDir = dirname(filename)
        else:
            lastSaveDir = dirname(filename)

    return filename
コード例 #30
0
ファイル: mcplatform.py プロジェクト: fhfuih/MCEdit-Unified
def askOpenFile(title='Select a Minecraft level....', schematics=False, suffixes=None):
    title = _(title)
    global lastSchematicsDir, lastSaveDir

    if not suffixes:
        suffixes = ["mclevel", "dat", "mine", "mine.gz"]
        suffixesChanged = False
    else:
        suffixesChanged = True
    initialDir = lastSaveDir or minecraftSaveFileDir
    if schematics:
        initialDir = lastSchematicsDir or directories.schematicsDir

    def _askOpen(_suffixes):
        if schematics:
            _suffixes.append("schematic")
            _suffixes.append("schematic.gz")
            _suffixes.append("zip")

            _suffixes.append("inv")
            
            _suffixes.append("nbt")

            # BO support
            _suffixes.append("bo2")
            _suffixes.append("bo3")
            _suffixes.sort()

        if sys.platform == "win32":  # !#
            if suffixesChanged:
                sendSuffixes = _suffixes
            else:
                sendSuffixes = None
            return askOpenFileWin32(title, schematics, initialDir, sendSuffixes)

        elif hasGtk and not platChooser:  # !# #Linux (When GTK 2.4 or newer is installed)
            return askOpenFileGtk(title, _suffixes, initialDir)

        else:
            log.debug("Calling internal file chooser.")
            log.debug("'initialDir' is %s (%s)" % (repr(initialDir), type(initialDir)))
            try:
                iDir = initialDir.encode(enc)
            except Exception as e:
                iDir = initialDir
                log.debug("Could not encode 'initialDir' %s" % repr(initialDir))
                log.debug("Encode function returned: %s" % e)
            if "All files (*.*)" not in _suffixes and "*.* (*.*)" not in _suffixes:
                _suffixes.append("All files (*.*)")
            return request_old_filename(suffixes=_suffixes, directory=iDir)

    filename = _askOpen(suffixes)
    if filename:
        if schematics:
            lastSchematicsDir = dirname(filename)
        else:
            lastSaveDir = dirname(filename)

    return filename
コード例 #31
0
    def statusText(self):
        if not self.panel:
            return ""
        player = self.panel.selectedPlayer
        if player == "Player":
            return "Click to move the player"

        return _("Click to move the player \"{0}\"").format(player)
コード例 #32
0
 def _func(*args, **kw):
     try:
         func(*args, **kw)
     except Exception, e:
         print traceback.format_exc()
         alert(
             _(u"Exception during filter operation. See console for details.\n\n{0}"
               ).format(e))
コード例 #33
0
    def __init__(self, editor):
        GLBackground.__init__(self)
        nudgeLabel = Label("Nudge", margin=8)

        self.editor = editor
        self.add(nudgeLabel)
        self.shrink_wrap()
        self.root = self.get_root()

        # tooltipBacking = Panel()
        # tooltipBacking.bg_color = (0, 0, 0, 0.6)
        keys = [_(config.keys[config.convert(k)].get()) for k in ("forward", "back", "left", "right", "up", "down", "fast nudge")]
        if keys[6] == "None":
            keys[6] = "Right mouse"

        nudgeLabel.tooltipText = _("Click and hold.  While holding, use the movement keys ({0}/{1}/{2}/{3}/{4}/{5}) to nudge. Left mouse to nudge a block.\n{6} to nudge a greater distance.").format(
            *keys)
コード例 #34
0
ファイル: player.py プロジェクト: Neui/MCEdit-Unified
    def mouseDown(self, evt, pos, direction):
        pos = map(lambda p, d: p + d, pos, direction)
        op = PlayerSpawnMoveOperation(self, pos)
        try:
            self.editor.addOperation(op)
            if op.canUndo:
                self.editor.addUnsavedEdit()
            self.markerList.invalidate()

        except SpawnPositionInvalid, e:
            if "Okay" != ask(str(e), responses=["Okay", "Fix it for me!"]):
                level = self.editor.level
                status = ""
                if not okayAt63(level, pos):
                    level.setBlockAt(pos[0], 63, pos[2], 1)
                    status += _("Block added at y=63.\n")

                if 59 < pos[1] < 63:
                    pos[1] = 63
                    status += _("Spawn point moved upward to y=63.\n")

                if not okayAboveSpawn(level, pos):
                    if pos[1] > 63 or pos[1] < 59:
                        lpos = (pos[0], pos[1] - 1, pos[2])
                        if level.blockAt(*pos) == 0 and level.blockAt(*lpos) != 0 and okayAboveSpawn(level, lpos):
                            pos = lpos
                            status += _("Spawn point shifted down by one block.\n")
                    if not okayAboveSpawn(level, pos):
                        for i in range(1, 4):
                            level.setBlockAt(pos[0], pos[1] + i, pos[2], 0)

                            status += _("Blocks above spawn point cleared.\n")

                self.editor.invalidateChunks([(pos[0] // 16, pos[2] // 16)])
                op = PlayerSpawnMoveOperation(self, pos)
                try:
                    self.editor.addOperation(op)
                    if op.canUndo:
                        self.editor.addUnsavedEdit()
                    self.markerList.invalidate()
                except SpawnPositionInvalid, e:
                    alert(str(e))
                    return

                if len(status):
                    alert(_("Spawn point fixed. Changes: \n\n") + status)
コード例 #35
0
ファイル: player.py プロジェクト: LaChal/MCEdit-Unified
    def statusText(self):
        if not self.panel:
            return ""
        player = self.panel.selectedPlayer
        if player == "Player":
            return "Click to move the player"

        return _("Click to move the player \"{0}\"").format(player)
コード例 #36
0
    def perform(self, recordUndo=True):
        if self.level.saving:
            alert(_("Cannot perform action while saving is taking place"))
            return
        with setWindowCaption("COPYING - "):
            self.editor.freezeStatus(
                _("Copying %0.1f million blocks") %
                (float(self._dirtyBox.volume) / 1048576., ))
            if recordUndo:
                chunks = set()
                for op in self.blockCopyOps:
                    chunks.update(op.dirtyBox().chunkPositions)
                self.undoLevel = self.extractUndoChunks(self.level, chunks)

            [i.perform(False) for i in self.blockCopyOps]
            [i.perform(recordUndo) for i in self.selectionOps]
            self.canUndo = True
コード例 #37
0
 def tryImport(name):
     try:
         return __import__(name)
     except Exception, e:
         print traceback.format_exc()
         alert(
             _(u"Exception while importing filter module {}. See console for details.\n\n{}"
               ).format(name, e))
         return object()
コード例 #38
0
def askSaveSchematic(initialDir, displayName, fileFormat):
    return askSaveFile(
        initialDir,
        title='Save this schematic...',
        defaultName=displayName + "." + fileFormat,
        filetype=_('Minecraft Schematics (*.{0})\0*.{0}\0\0').format(
            fileFormat),
        suffix=fileFormat,
    )
コード例 #39
0
 def check_for_version(self):
     new_version = release.check_for_new_version(self.version_info)
     if new_version is not False:
         answer = albow.ask(
             _('Version {} is available').format(new_version["tag_name"]),
             [
                 'Download',
                 'View',
                 'Ignore'
             ],
             default=1,
             cancel=2
         )
         if answer == "View":
             platform_open(new_version["html_url"])
         elif answer == "Download":
             platform_open(new_version["asset"]["browser_download_url"])
             albow.alert(_(' {} should now be downloading via your browser. You will still need to extract the downloaded file to use the updated version.').format(new_version["asset"]["name"]))
コード例 #40
0
    def __init__(self, editor, nbtObject=None, fileName=None, savePolicy=0, dataKeyName='Data', close_text="Close",
                 load_text="Open", **kwargs):
        """..."""
        Panel.__init__(self)
        self.editor = editor
        self.nbtObject = nbtObject
        self.fileName = fileName
        self.savePolicy = savePolicy
        self.displayed_item = None
        self.dataKeyName = dataKeyName
        self.copy_data = kwargs.get('copy_data', True)
        self.init_data()
        btns = []
        if load_text:
            btns.append(Button(load_text, action=self.editor.nbtTool.loadFile))
        btns += [
            Button({True: "Save", False: "OK"}[fileName != None], action=kwargs.get('ok_action', self.save_NBT),
                   tooltipText="Save your change in the NBT data."),
            Button("Reset", action=kwargs.get('reset_action', self.reset),
                   tooltipText="Reset ALL your changes in the NBT data."),
        ]
        if close_text:
            btns.append(Button(close_text, action=kwargs.get('close_action', self.close)))

        btnRow = Row(btns, margin=1, spacing=4)

        btnRow.shrink_wrap()
        self.btnRow = btnRow

        if kwargs.get('no_header', False):
            self.max_height = max_height = kwargs.get('height', editor.mainViewport.height - editor.toolbar.height -
                                                      editor.subwidgets[0].height) - (
                                               self.margin * 2) - btnRow.height - 2
        else:
            title = _("NBT Explorer")
            if fileName:
                title += " - %s" % os.path.split(fileName)[-1]
            header = Label(title, doNotTranslate=True)
            self.max_height = max_height = kwargs.get('height', editor.mainViewport.height - editor.toolbar.height -
                                                      editor.subwidgets[0].height) - header.height - (
                                               self.margin * 2) - btnRow.height - 2
        self.setCompounds()
        self.tree = NBTTree(height=max_height - btnRow.height - 2, inner_width=250, data=self.data,
                            compound_types=self.compounds,
                            copyBuffer=editor.nbtCopyBuffer, draw_zebra=False, _parent=self, styles=bullet_styles)
        self.tree.update_side_panel = self.update_side_panel
        self.side_panel_width = 350
        row = [self.tree, Column([Label("", width=self.side_panel_width), ], margin=0)]
        self.displayRow = Row(row, height=max_height, margin=0, spacing=0)
        if kwargs.get('no_header', False):
            self.add(Column([self.displayRow, btnRow], margin=0))
        else:
            self.add(Column([header, self.displayRow, btnRow], margin=0))
        self.shrink_wrap()
        self.side_panel = None
        # &# Prototype for Blocks/item names
        mclangres.buildResources(lang=getLang())
コード例 #41
0
ファイル: tree.py プロジェクト: Nerocat/MCEdit-Unified
 def __init__(self, type_string, types=map_types_item, ok_action=None):
     self.type_string = type_string
     self.ok_action = ok_action
     title = Label("Choose default data")
     self.t, widget, self.v = types[type_string]
     self.n = u""
     w_name = TextFieldWrapped(ref=AttrRef(self, 'n'))
     self.w_value = self.get_widget(widget)
     col = Column([Column([title,]), Label(_("Item Type: %s")%type_string, doNotTranslate=True), Row([Label("Name"), w_name], margin=0), Row([Label("Value"), self.w_value], margin=0), Row([Button("OK", action=ok_action or self.dismiss_ok), Button("Cancel", action=self.dismiss)], margin=0)], margin=0, spacing=2)
     Dialog.__init__(self, client=col)
コード例 #42
0
    def perform(self, recordUndo=True):
        if self.level.saving:
            alert(_("Cannot perform action while saving is taking place"))
            return

        if self.player == "Player (Single Player)":
            answer = ask(
                _("Are you sure you want to delete the default player?"),
                ["Yes", "Cancel"])
            if answer == "Cancel":
                return
            self.player = "Player"

        if recordUndo:
            self.undoTag = self.level.getPlayerTag(self.player)

        self.level.players.remove(self.player)
        if self.tool.panel:
            if self.player != "Player":
                #self.tool.panel.players.remove(player_cache.getPlayerNameFromUUID(self.player))
                #self.tool.panel.players.remove(self.playercache.getPlayerInfo(self.player)[0])
                str()
            else:
                self.tool.panel.players.remove("Player (Single Player)")

            while self.tool.panel.table.index >= len(self.tool.panel.players):
                self.tool.panel.table.index -= 1
            #if len(self.tool.panel.players) == 0:
            #    self.tool.hidePanel()
            #    self.tool.showPanel()
            self.tool.hidePanel()
            self.tool.showPanel()
        self.tool.markerList.invalidate()
        self.tool.movingPlayer = None

        pos = self.tool.revPlayerPos[self.editor.level.dimNo][self.player]
        del self.tool.playerPos[self.editor.level.dimNo][pos]
        if self.player != "Player":
            del self.tool.playerTexture[self.player]
        else:
            del self.level.root_tag["Data"]["Player"]
        del self.tool.revPlayerPos[self.editor.level.dimNo][self.player]
        self.canUndo = True
コード例 #43
0
def askSaveSchematic(initialDir, displayName, fileFormats):
    fileFormat = buildFileTypes(fileFormats)
    
    dt = datetime.now().strftime("%Y-%m-%d--%H-%M-%S")
    return askSaveFile(initialDir,
                       title=_('Save this schematic...'),
                       defaultName=displayName + "_" + dt + "." + fileFormats[0][fileFormats[0].keys()[1]][0],
                       filetype=fileFormat,
                       suffix=fileFormat,
                       )
コード例 #44
0
ファイル: player.py プロジェクト: Neui/MCEdit-Unified
    def perform(self, recordUndo=True):
        if self.level.saving:
            alert(_("Cannot perform action while saving is taking place"))
            return
        try:
            level = self.tool.editor.level
            try:
                self.undoPos = level.getPlayerPosition(self.player)
                self.undoDim = level.getPlayerDimension(self.player)
                self.undoYP = level.getPlayerOrientation(self.player)
            except Exception, e:
                log.info(_("Couldn't get player position! ({0!r})").format(e))

            yaw, pitch = self.yp
            if yaw is not None and pitch is not None:
                level.setPlayerOrientation((yaw, pitch), self.player)
            level.setPlayerPosition(self.pos, self.player)
            level.setPlayerDimension(level.dimNo, self.player)
            self.tool.markerList.invalidate()
            self.canUndo = True
コード例 #45
0
ファイル: nbtexplorer.py プロジェクト: Nerocat/MCEdit-Unified
def loadFile(fName):
    if not fName:
        fName = mcplatform.askOpenFile(title=_("Select a NBT (.dat) file..."),
                                       suffixes=[
                                           'dat',
                                       ])
    if fName:
        if not os.path.isfile(fName):
            alert("The selected object is not a file.\nCan't load it.")
            return
        savePolicy = 0
        data = open(fName).read()

        if struct.Struct('<i').unpack(data[:4])[0] in (3, 4):
            if struct.Struct('<i').unpack(data[4:8])[0] != len(data[8:]):
                raise NBTFormatError()
            with littleEndianNBT():
                nbtObject = load(buf=data[8:])
            savePolicy = 1
        elif struct.Struct('<i').unpack(data[:4])[0] in (1, 2):
            alert(_("Old PE level.dat, unsupported at the moment."))
        else:
            nbtObject = load(buf=data)
        if fName.endswith('.schematic'):
            nbtObject = TAG_Compound(name='Data', value=nbtObject)
            savePolicy = -1
            dataKeyName = 'Data'
        elif nbtObject.get('Data', None):
            dataKeyName = 'Data'
        elif nbtObject.get('data', None):
            dataKeyName = 'data'
        else:
            nbtObject.name = 'Data'
            dataKeyName = 'Data'
            if savePolicy == 0:
                savePolicy = -1
            nbtObject = TAG_Compound([
                nbtObject,
            ])
        return nbtObject, dataKeyName, savePolicy, fName
    return [None] * 4
コード例 #46
0
    def relightChunks(self):

        def _relightChunks():
            for i in self.editor.level.generateLightsIter(self.selectedChunks()):
                yield i

        with setWindowCaption("RELIGHTING - "):
            showProgress(_("Lighting {0} chunks...").format(len(self.selectedChunks())),
                         _relightChunks(), cancel=True)

            self.editor.invalidateChunks(self.selectedChunks())
            self.editor.addUnsavedEdit()
コード例 #47
0
    def togglePortable(self):
        if sys.platform == "darwin":
            return False
        textChoices = [
            _("This will make your MCEdit \"portable\" by moving your settings and schematics into the same folder as {0}. Continue?"
              ).format(
                  (sys.platform == "darwin" and _("the MCEdit application")
                   or _("MCEditData"))),
            _("This will move your settings and schematics to your Documents folder. Continue?"
              ),
        ]

        alertText = textChoices[directories.portable]
        if albow.ask(alertText) == "OK":
            try:
                [directories.goPortable,
                 directories.goFixed][directories.portable]()
            except Exception, e:
                traceback.print_exc()
                albow.alert(
                    _(u"Error while moving files: {0}").format(repr(e)))
コード例 #48
0
ファイル: options.py プロジェクト: zzz1999/MCEdit-Unified
    def togglePortable(self):
        if sys.platform == "darwin":
            return False
        textChoices = [
            _("This will make your MCEdit \"portable\" by moving your settings and schematics into the same folder as {0}. Continue?"
              ).format(
                  (sys.platform == "darwin" and _("the MCEdit application")
                   or _("MCEditData"))),
            _("This will move your settings and schematics to your Documents folder. Continue?"
              ),
        ]
        useExisting = False

        alertText = textChoices[directories.portable]
        if albow.ask(alertText) == "OK":
            if [
                    directories.hasPreviousPortableInstallation,
                    directories.hasPreviousFixedInstallation
            ][directories.portable]():
                asked = albow.ask("Found a previous %s installation" %
                                  ["portable", "fixed"][directories.portable],
                                  responses=["Use", "Overwrite", "Cancel"])
                if asked == "Use":
                    useExisting = True
                elif asked == "Overwrite":
                    useExisting = False
                elif asked == "Cancel":
                    return False
            try:
                [directories.goPortable,
                 directories.goFixed][directories.portable](useExisting)
            except Exception as e:
                traceback.print_exc()
                albow.alert(
                    _(u"Error while moving files: {0}").format(repr(e)))
        else:
            self.goPortableButton.selectedChoice = self.saveOldPortable

        self.goPortableButton.tooltipText = self.portableButtonTooltip()
        return True
コード例 #49
0
    def worldTooltipText(self):
        if self.pickBlockKey == 1:
            try:
                if self.editor.blockFaceUnderCursor is None:
                    return
                pos = self.editor.blockFaceUnderCursor[0]
                blockID = self.editor.level.blockAt(*pos)
                blockdata = self.editor.level.blockDataAt(*pos)
                return _("Click to use {0} ({1}:{2})").format(
                    self.editor.level.materials.blockWithID(blockID, blockdata).name, blockID, blockdata)

            except Exception, e:
                return repr(e)
コード例 #50
0
    def _alertException(*args, **kw):
        try:
            return func(*args, **kw)
        except root.Cancel:
            alert("Canceled.")
        except pymclevel.infiniteworld.SessionLockLost as e:
            alert(e.message + _("\n\nYour changes cannot be saved."))

        except Exception, e:
            logging.exception("Exception:")
            if ask(_("Error during {0}: {1!r}").format(func, e)[:1000],
                   ["Report Error", "Okay"],
                   default=1,
                   cancel=0) == "Report Error":
                try:
                    import squash_python

                    squash_python.get_client().recordException(*sys.exc_info())
                except ImportError:
                    pass
                except Exception:
                    logging.exception("Error while recording exception data:")
コード例 #51
0
def setWindowCaption(prefix):
    caption = display.get_caption()[0]
    prefix = _(prefix)
    if type(prefix) == unicode:
        prefix = prefix.encode("utf8")
    class ctx:
        def __enter__(self):
            display.set_caption(prefix + caption)

        def __exit__(self, *args):
            display.set_caption(caption)

    return ctx()
コード例 #52
0
ファイル: chunk.py プロジェクト: zzz1999/MCEdit-Unified
 def worldTooltipText(self):
     box = self.editor.selectionTool.selectionBoxInProgress()
     if box:
         box = box.chunkBox(self.editor.level)
         l, w = box.length // 16, box.width // 16
         return _("%s x %s chunks") % (l, w)
     else:
         if config.settings.viewMode.get() == "Chunk":
             point, face = self.editor.chunkViewport.blockFaceUnderCursor
         else:
             point, face = self.editor.mainViewport.blockFaceUnderCursor
         if point:
             return "Chunk ({}, {})".format(point[0] // 16, point[2] // 16)
コード例 #53
0
ファイル: player.py プロジェクト: Neui/MCEdit-Unified
 def redo(self):
     if not (self.redoPos is None):
         level = self.tool.editor.level
         try:
             self.undoPos = level.getPlayerPosition(self.player)
             self.undoDim = level.getPlayerDimension(self.player)
             self.undoYP = level.getPlayerOrientation(self.player)
         except Exception, e:
             log.info(_("Couldn't get player position! ({0!r})").format(e))
         level.setPlayerPosition(self.redoPos, self.player)
         level.setPlayerDimension(self.redoDim, self.player)
         level.setPlayerOrientation(self.redoYP, self.player)
         self.tool.markerList.invalidate()
コード例 #54
0
ファイル: nbtexplorer.py プロジェクト: Nerocat/MCEdit-Unified
    def __init__(self, inventory, data, *args, **kwargs):
        Dialog.__init__(self, *args, **kwargs)
        self.inventory = inventory
        slot, id, count, damage = data
        self.former_id_text = id
        self.slot = slot
        self.id = TextFieldWrapped(text=str(id),
                                   doNotTranslate=True,
                                   width=300)
        self.id.change_action = self.text_entered
        self.id.escape_action = self.cancel
        self.id.enter_action = self.ok
        self.count = IntField(text="%s" % count, min=0, max=64)
        self.damage = IntField(text="%s" % damage, min=0, max=os.sys.maxint)
        header = Label(_("Inventory Slot #%s") % slot, doNotTranslate=True)
        row = Row([
            Label("id"),
            self.id,
            Label("Count"),
            self.count,
            Label("Damage"),
            self.damage,
        ])

        self.matching_items = [
            mclangres.translate(k) for k in map_items.keys()
        ]
        self.matching_items.sort()
        self.selected_item_index = None
        if id in self.matching_items:
            self.selected_item_index = self.matching_items.index(id)
        self.tableview = tableview = TableView(
            columns=[TableColumn("", 415, 'l')])
        tableview.num_rows = lambda: len(self.matching_items)
        tableview.row_data = lambda x: (self.matching_items[x], )
        tableview.row_is_selected = lambda x: x == self.selected_item_index
        tableview.click_row = self.select_tablerow

        buttons = Row([
            Button("Save", action=self.dismiss),
            Button("Cancel", action=self.cancel)
        ])
        col = Column([header, row, tableview, buttons], spacing=2)
        self.add(col)
        self.shrink_wrap()

        try:
            self.tableview.rows.scroll_to_item(self.selected_item_index)
        except Exception, e:
            print e
            pass
コード例 #55
0
    def perform(self, recordUndo=True):
        if self.level.saving:
            alert(_("Cannot perform action while saving is taking place"))
            return

        if self.player == "Player":
            answer = ask(
                _("Are you sure you want to delete the default player?"),
                ["Yes", "Cancel"])
            if answer == "Cancel":
                return

        if recordUndo:
            self.undoTag = self.level.getPlayerTag(self.player)

        self.level.players.remove(self.player)
        if self.tool.panel:
            if self.player != "Player":
                self.tool.panel.players.remove(
                    version_utils.getPlayerNameFromUUID(self.player))
            else:
                self.tool.panel.players.remove("Player")

            while self.tool.panel.table.index >= len(self.tool.panel.players):
                self.tool.panel.table.index -= 1
            if len(self.tool.panel.players) == 0:
                self.tool.hidePanel()
                self.tool.showPanel()
        self.tool.markerList.invalidate()

        pos = self.tool.revPlayerPos[self.player]
        del self.tool.playerPos[pos]
        if self.player != "Player":
            del self.tool.playerTexture[self.player]
        else:
            del self.level.root_tag["Data"]["Player"]
        del self.tool.revPlayerPos[self.player]
        self.canUndo = True
コード例 #56
0
    def perform(self, recordUndo=True):
        if self.toolPanel.nbtObject:

            orgNBT = self.toolPanel.nbtObject[self.toolPanel.dataKeyName]
            newNBT = self.toolPanel.data

            if "%s"%orgNBT != "%s"%newNBT:
                if self.level.saving:
                    alert(_("Cannot perform action while saving is taking place"))
                    return
                if recordUndo:
                    self.canUndo = True
                    self.undoLevel = self.extractUndo()
                self.toolPanel.nbtObject[self.toolPanel.dataKeyName] = self.toolPanel.data
コード例 #57
0
ファイル: clone.py プロジェクト: kareshok/MCEdit-Unified
    def perform(self, recordUndo=True):
        if self.level.saving:
            alert(_("Cannot perform action while saving is taking place"))
            return

        if recordUndo:
            self.canUndo = True
            self.undoLevel = self.extractUndo(self.level, BoundingBox(self.destPoint, self.sourceBox.size))

        blocksToCopy = None
        if not (self.copyAir and self.copyWater):
            blocksToCopy = range(pymclevel.materials.id_limit)
            if not self.copyAir:
                blocksToCopy.remove(0)
            if not self.copyWater:
                blocksToCopy.remove(8)
            if not self.copyWater:
                blocksToCopy.remove(9)

        with setWindowCaption("Copying - "):
            i = self.level.copyBlocksFromIter(self.sourceLevel, self.sourceBox, self.destPoint, blocksToCopy,
                                              create=True, biomes=self.copyBiomes, staticCommands=self.staticCommands, moveSpawnerPos=self.moveSpawnerPos, regenerateUUID=self.regenerateUUID, first=False)
            showProgress(_("Copying {0:n} blocks...").format(self.sourceBox.volume), i)
コード例 #58
0
    def cancel(self, *args, **kwargs):
        Changes = False
        self.reshowNumberFields()
        for key in self.saveOldConfig.keys():
            if key.get() != self.saveOldConfig[key]:
                Changes = True
        oldLanguage = self.saveOldConfig[config.settings.langCode]
        if config.settings.langCode.get() != oldLanguage:
            Changes = True
        newPortable = self.portableVar.get()
        if newPortable != self.saveOldPortable:
            Changes = True
        if not Changes:
            Dialog.dismiss(self, *args, **kwargs)
            return

        result = albow.ask("Do you want to save your changes?",
                           ["Save", "Don't Save", "Cancel"])
        if result == "Cancel":
            return
        if result == "Save":
            self.dismiss(*args, **kwargs)
            return

        if config.settings.langCode.get() != oldLanguage:
            self.languageButton.selectedChoice = self.sgnal[oldLanguage]
            self.changeLanguage()

        if _(newPortable) != _(self.saveOldPortable):
            self.portableVar.set(newPortable)
            self.togglePortable()

        for key in self.saveOldConfig.keys():
            key.set(self.saveOldConfig[key])

        config.save()
        Dialog.dismiss(self, *args, **kwargs)
コード例 #59
0
 def take_screenshot(self):
     try:
         os.mkdir(os.path.join(directories.getCacheDir(), "screenshots"))
     except OSError:
         pass
     screenshot_name = os.path.join(directories.getCacheDir(), "screenshots", time.strftime("%Y-%m-%d (%I-%M-%S-%p)")+".png")
     pygame.image.save(pygame.display.get_surface(), screenshot_name)
     self.diag = Dialog()
     lbl = Label(_("Screenshot taken and saved as '%s'")%screenshot_name, doNotTranslate=True)
     folderBtn = Button("Open Folder", action=self.open_screenshots_folder)
     btn = Button("Ok", action=self.screenshot_notify)
     buttonsRow = Row((btn,folderBtn))
     col = Column((lbl,buttonsRow))
     self.diag.add(col)
     self.diag.shrink_wrap()
     self.diag.present()