예제 #1
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
예제 #2
0
 def build_pos(items):
     rows = []
     pos = items[0]
     rows.append(Row([Label("X", align='l'), FloatField(ref=AttrRef(pos[0], 'value'))]))
     rows.append(Row([Label("Y", align='l'), FloatField(ref=AttrRef(pos[1], 'value'))]))
     rows.append(Row([Label("Z", align='l'), FloatField(ref=AttrRef(pos[2], 'value'))]))
     return rows
예제 #3
0
 def build_rotation(items):
     rows = []
     rotation = items[0]
     rows.append(
         Row([
             Label("Y", align='l'),
             FloatField(ref=AttrRef(rotation[0], 'value'))
         ]))
     rows.append(
         Row([
             Label("X", align='l'),
             FloatField(ref=AttrRef(rotation[1], 'value'))
         ]))
     return rows
예제 #4
0
    def __init__(self, materials, blockInfo=None, ref=None, recentBlocks=None, *a, **kw):
        self.allowWildcards = False
        Panel.__init__(self, *a, **kw)

        self.bg_color = (1, 1, 1, 0.25)
        self._ref = ref
        if blockInfo is None and ref is not None:
            blockInfo = ref.get()
        blockInfo = blockInfo or materials.Air

        if recentBlocks is not None:
            self.recentBlocks = recentBlocks
        else:
            self.recentBlocks = []

        self.blockView = thumbview.BlockThumbView(materials, blockInfo, size=(48, 48))
        self.blockLabel = ValueDisplay(ref=AttrRef(self, 'labelText'), width=180, align="l")
        row = Row((self.blockView, self.blockLabel), align="b")

        # col = Column( (self.blockButton, self.blockNameLabel) )
        self.add(row)
        self.shrink_wrap()

        # self.blockLabel.bottom = self.blockButton.bottom
        # self.blockLabel.centerx = self.blockButton.centerx

        # self.add(self.blockLabel)

        self.materials = materials
        self.blockInfo = blockInfo
        # self._ref = ref
        self.updateRecentBlockView()
예제 #5
0
    def __init__(self, tool):
        Panel.__init__(self)
        self.tool = tool
        self.autoPlaceCheckBox = CheckBox(
            ref=AttrRef(tool, "placeImmediately"))
        self.autoPlaceLabel = Label("Place Immediately")
        self.autoPlaceLabel.mouse_down = self.autoPlaceCheckBox.mouse_down

        tooltipText = "When the clone tool is chosen, place the clone at the selection right away."
        self.autoPlaceLabel.tooltipText = self.autoPlaceCheckBox.tooltipText = tooltipText

        spaceLabel = Label("")
        cloneNudgeLabel = Label("Clone Fast Nudge Settings")
        cloneNudgeCheckBox = CheckBoxLabel(
            "Move by the width of selection ",
            ref=config.fastNudgeSettings.cloneWidth,
            tooltipText="Moves clone by his width")
        cloneNudgeNumber = IntInputRow(
            "Width of clone movement: ",
            ref=config.fastNudgeSettings.cloneWidthNumber,
            width=100,
            min=2,
            max=50)

        row = Row((self.autoPlaceCheckBox, self.autoPlaceLabel))
        col = Column((Label("Clone Options"), row, spaceLabel, cloneNudgeLabel,
                      cloneNudgeCheckBox, cloneNudgeNumber,
                      Button("OK", action=self.dismiss)))

        self.add(col)
        self.shrink_wrap()
예제 #6
0
def addNumField(page,
                optionName,
                oName,
                val,
                min_value=None,
                max_value=None,
                increment=0.1):
    if isinstance(val, float):
        field_type = FloatField
        if isinstance(increment, int):
            increment = float(increment)
    else:
        field_type = IntField
        if increment == 0.1:
            increment = 1
        if isinstance(increment, float):
            increment = int(round(increment))

    if min_value == max_value:
        min_value = None
        max_value = None

    field = field_type(value=val, width=200, min=min_value, max=max_value)
    field._increment = increment
    page.optionDict[optionName] = AttrRef(field, 'value')

    row = Row([Label(oName, doNotTranslate=True), field])
    return row
예제 #7
0
 def createField(self, key, value):
     """
     Creates a field matching the input type.
     :param key, key to store the value in, also the name of the label if type is float or int.
     :param value, default value for the field.
     """
     doNotTranslate = bool(hasattr(self.tool.brushMode, "trn"))
     check_value = value
     mi = 0
     ma = 100
     if key in ('W', 'H', 'L'):
         reference = AttrRef(self.tool, key)
     else:
         reference = ItemRef(self.tool.options, key)
     if isinstance(check_value, tuple):
         check_value = value[0]
         mi = value[1]
         ma = value[2]
     if isinstance(check_value, Block):
         if key not in self.tool.recentBlocks:
             self.tool.recentBlocks[key] = []
         wcb = getattr(self.tool.brushMode, 'wildcardBlocks', [])
         aw = False
         if key in wcb:
             aw = True
         field = BlockButton(self.tool.editor.level.materials,
                             ref=reference,
                             recentBlocks=self.tool.recentBlocks[key],
                             allowWildcards=aw)
     elif isinstance(check_value, types.MethodType):
         field = Button(key, action=value)
     else:
         if doNotTranslate:
             key = self.tool.brushMode.trn._(key)
             value = self.tool.brushMode.trn._(value)
         if isinstance(check_value, int):
             field = IntInputRow(key,
                                 ref=reference,
                                 width=50,
                                 min=mi,
                                 max=ma,
                                 doNotTranslate=doNotTranslate)
         elif isinstance(check_value, float):
             field = FloatInputRow(key,
                                   ref=reference,
                                   width=50,
                                   min=mi,
                                   max=ma,
                                   doNotTranslate=doNotTranslate)
         elif isinstance(check_value, bool):
             field = CheckBoxLabel(key,
                                   ref=reference,
                                   doNotTranslate=doNotTranslate)
         elif isinstance(check_value, str):
             field = Label(value, doNotTranslate=doNotTranslate)
         else:
             print(type(check_value))
             field = None
     return field
예제 #8
0
    def __init__(self, tool, *a, **kw):
        Panel.__init__(self, *a, **kw)

        self.tool = tool

        self.anchor = "whl"

        chunkToolLabel = Label("Selected Chunks:")

        self.chunksLabel = ValueDisplay(ref=AttrRef(self, 'chunkSizeText'), width=115)
        self.chunksLabel.align = "c"
        self.chunksLabel.tooltipText = "..."

        extractButton = Button("Extract")
        extractButton.tooltipText = "Extract these chunks to individual chunk files"
        extractButton.action = tool.extractChunks
        extractButton.highlight_color = (255, 255, 255)

        deselectButton = Button("Deselect",
                                tooltipText=None,
                                action=tool.editor.deselect,
        )

        createButton = Button("Create")
        createButton.tooltipText = "Create new chunks within the selection."
        createButton.action = tool.createChunks
        createButton.highlight_color = (0, 255, 0)

        destroyButton = Button("Delete")
        destroyButton.tooltipText = "Delete the selected chunks from disk. Minecraft will recreate them the next time you are near."
        destroyButton.action = tool.destroyChunks

        pruneButton = Button("Prune")
        pruneButton.tooltipText = "Prune the world, leaving only the selected chunks. Any chunks outside of the selection will be removed, and empty region files will be deleted from disk"
        pruneButton.action = tool.pruneChunks

        relightButton = Button("Relight")
        relightButton.tooltipText = "Recalculate light values across the selected chunks"
        relightButton.action = tool.relightChunks
        relightButton.highlight_color = (255, 255, 255)

        repopButton = Button("Repop")
        repopButton.tooltipText = "Mark the selected chunks for repopulation. The next time you play Minecraft, the chunks will have trees, ores, and other features regenerated."
        repopButton.action = tool.repopChunks
        repopButton.highlight_color = (255, 200, 155)

        dontRepopButton = Button("Don't Repop")
        dontRepopButton.tooltipText = "Unmark the selected chunks. They will not repopulate the next time you play the game."
        dontRepopButton.action = tool.dontRepopChunks
        dontRepopButton.highlight_color = (255, 255, 255)

        col = Column((
        chunkToolLabel, self.chunksLabel, deselectButton, createButton, destroyButton, pruneButton, relightButton,
        extractButton, repopButton, dontRepopButton))
        # col.right = self.width - 10;
        self.width = col.width
        self.height = col.height
        #self.width = 120
        self.add(col)
예제 #9
0
 def __init__(self, tool):
     ToolOptions.__init__(self, name='Panel.FilterToolOptions')
     self.tool = tool
     
     self.notifications_disabled = False
     
     disable_error_popup = CheckBoxLabel("Disable Error Notification",
                                         ref=AttrRef(self, 'notifications_disabled'))
     ok_button = Button("Ok", action=self.dismiss)
     
     col = Column((disable_error_popup, ok_button,), spacing=2)
     self.add(col)
     self.shrink_wrap()
예제 #10
0
파일: clone.py 프로젝트: PavelHejny/mcedit
    def __init__(self, tool):
        Panel.__init__(self)
        self.tool = tool
        self.autoPlaceCheckBox = CheckBox(ref=AttrRef(tool, "placeImmediately"))
        self.autoPlaceLabel = Label("Place Immediately")
        self.autoPlaceLabel.mouse_down = self.autoPlaceCheckBox.mouse_down

        tooltipText = "When the clone tool is chosen, place the clone at the selection right away."
        self.autoPlaceLabel.tooltipText = self.autoPlaceCheckBox.tooltipText = tooltipText

        row = Row((self.autoPlaceCheckBox, self.autoPlaceLabel))
        col = Column((Label("Clone Options"), row, Button("OK", action=self.dismiss)))

        self.add(col)
        self.shrink_wrap()
예제 #11
0
    def __init__(self, tool):
        Panel.__init__(self)
        self.tool = tool
        self.spawnProtectionCheckBox = CheckBox(ref=AttrRef(tool, "spawnProtection"))
        self.spawnProtectionLabel = Label("Spawn Position Safety")
        self.spawnProtectionLabel.mouse_down = self.spawnProtectionCheckBox.mouse_down

        tooltipText = "Minecraft will randomly move your spawn point if you try to respawn in a column where there are no blocks at Y=63 and Y=64. Only uncheck this box if Minecraft is changed."
        self.spawnProtectionLabel.tooltipText = self.spawnProtectionCheckBox.tooltipText = tooltipText

        row = Row((self.spawnProtectionCheckBox, self.spawnProtectionLabel))
        col = Column((Label("Spawn Point Options"), row, Button("OK", action=self.dismiss)))

        self.add(col)
        self.shrink_wrap()
예제 #12
0
def addNumField(page, optionName, val, min=None, max=None):
    if isinstance(val, float):
        ftype = FloatField
    else:
        ftype = IntField

    if min == max:
        min = None
        max = None

    field = ftype(value=val, width=100, min=min, max=max)
    page.optionDict[optionName] = AttrRef(field, 'value')

    row = Row([Label(optionName), field])
    return row
예제 #13
0
    def __init__(self, editor):
        Panel.__init__(self, name='Panel.ControlPanel')
        self.editor = editor

        self.bg_color = (0, 0, 0, 0.8)

        header = self.getHeader()
        keysColumn = [Label("")]
        buttonsColumn = [header]

        hotkeys = ([
            (config.keys.newWorld.get(), "Create New World",
             editor.mcedit.createNewWorld),
            (config.keys.quickLoad.get(), "Quick Load", editor.askLoadWorld),
            (config.keys.open.get(), "Open...", editor.askOpenFile),
            (config.keys.save.get(), "Save", editor.saveFile),
            (config.keys.saveAs.get(), "Save As", editor.saveAs),
            (config.keys.reloadWorld.get(), "Reload", editor.reload),
            (config.keys.closeWorld.get(), "Close", editor.closeEditor),
            (config.keys.uploadWorld.get(), "Upload to FTP Server",
             editor.uploadChanges),
            (config.keys.gotoPanel.get(), "Waypoints/Goto",
             editor.showWaypointsDialog),
            (config.keys.worldInfo.get(), "World Info", editor.showWorldInfo),
            (config.keys.undo.get(), "Undo", editor.undo),
            (config.keys.redo.get(), "Redo", editor.redo),
            (config.keys.selectAll.get(), "Select All", editor.selectAll),
            (config.keys.deselect.get(), "Deselect", editor.deselect),
            (config.keys.viewDistance.get(),
             AttrRef(editor,
                     'viewDistanceLabelText'), editor.swapViewDistance),
            (config.keys.quit.get(), "Quit", editor.quit),
        ])

        buttons = HotkeyColumn(hotkeys,
                               keysColumn,
                               buttonsColumn,
                               item_spacing=2)

        sideColumn1 = editor.mcedit.makeSideColumn1()
        sideColumn2 = editor.mcedit.makeSideColumn2()
        spaceLabel = Label("")
        sideColumn = Column((sideColumn1, spaceLabel, sideColumn2))

        self.add(Row([buttons, sideColumn]))
        self.shrink_wrap()
예제 #14
0
    def __init__(self, editor):
        Panel.__init__(self)
        self.editor = editor

        self.bg_color = (0, 0, 0, 0.8)

        header = self.getHeader()
        keysColumn = [Label("")]
        buttonsColumn = [header]

        hotkeys = ([
            (config.keys.newWorld.get(), "Create New World",
             editor.mcedit.createNewWorld),
            (config.keys.quickLoad.get(), "Quick Load", editor.askLoadWorld),
            (config.keys.open.get(), "Open...", editor.askOpenFile),
            (config.keys.save.get(), "Save", editor.saveFile),
            (config.keys.reloadWorld.get(), "Reload", editor.reload),
            (config.keys.closeWorld.get(), "Close", editor.closeEditor),
            (config.keys.gotoPanel.get(), "Goto", editor.showGotoPanel),
            (config.keys.worldInfo.get(), "World Info", editor.showWorldInfo),
            (config.keys.undo.get(), "Undo", editor.undo),
            (config.keys.redo.get(), "Redo", editor.redo),
            (config.keys.selectAll.get(), "Select All", editor.selectAll),
            (config.keys.deselect.get(), "Deselect", editor.deselect),
            (config.keys.viewDistance.get(),
             AttrRef(editor,
                     'viewDistanceLabelText'), editor.swapViewDistance),
            (config.keys.quit.get(), "Quit", editor.quit),
        ])

        buttons = mceutils.HotkeyColumn(hotkeys, keysColumn, buttonsColumn)

        sideColumn = editor.mcedit.makeSideColumn()

        self.add(Row([buttons, sideColumn]))
        self.shrink_wrap()
예제 #15
0
def GeneratorPanel():
    panel = Widget()
    panel.chunkHeight = 64
    panel.grass = True
    panel.simulate = False
    panel.snapshot = False

    jarStorage = MCServerChunkGenerator.getDefaultJarStorage()
    if jarStorage:
        jarStorage.reloadVersions()

    generatorChoice = ChoiceButton(["Minecraft Server", "Flatland"])
    panel.generatorChoice = generatorChoice
    col = [Row((Label("Generator:"), generatorChoice))]
    noVersionsRow = Label(
        "Will automatically download and use the latest version")
    versionContainer = Widget()

    heightinput = IntInputRow("Height: ",
                              ref=AttrRef(panel, "chunkHeight"),
                              min=0,
                              max=255)
    grassinput = CheckBoxLabel("Grass", ref=AttrRef(panel, "grass"))
    flatPanel = Column([heightinput, grassinput], align="l")

    def generatorChoiceChanged():
        serverPanel.visible = generatorChoice.selectedChoice == "Minecraft Server"
        flatPanel.visible = not serverPanel.visible

    generatorChoice.choose = generatorChoiceChanged

    versionChoice = None

    if len(jarStorage.versions):

        def checkForUpdates():
            def _check():
                yield
                jarStorage.downloadCurrentServer(panel.snapshot)
                yield

            showProgress("Checking for server updates...", _check())
            versionChoice.choices = sorted(jarStorage.versions, reverse=True)
            versionChoice.choiceIndex = 0

        versionChoice = ChoiceButton(sorted(jarStorage.versions, reverse=True))
        versionChoice.set_size_for_text(200)
        versionChoiceRow = (Row(
            (Label("Server version:"), versionChoice, Label("or"),
             Button("Check for Updates", action=checkForUpdates))))
        panel.versionChoice = versionChoice
        versionContainer.add(versionChoiceRow)
    else:
        versionContainer.add(noVersionsRow)

    versionContainer.shrink_wrap()

    menu = Menu("Advanced", [("Open Server Storage", "revealStorage"),
                             ("Reveal World Cache", "revealCache"),
                             ("Delete World Cache", "clearCache")])

    def presentMenu():
        i = menu.present(advancedButton.parent, advancedButton.topleft)
        if i != -1:
            (revealStorage, revealCache, clearCache)[i]()

    advancedButton = Button("Advanced...", presentMenu)

    @alertException
    def revealStorage():
        mcplatform.platform_open(jarStorage.cacheDir)

    @alertException
    def revealCache():
        mcplatform.platform_open(MCServerChunkGenerator.worldCacheDir)

    # revealCacheRow = Row((Label("Minecraft Server Storage: "), Button("Open Folder", action=revealCache, tooltipText="Click me to install your own minecraft_server.jar if you have any.")))

    @alertException
    def clearCache():
        MCServerChunkGenerator.clearWorldCache()

    simRow = CheckBoxLabel(
        "Simulate world",
        ref=AttrRef(panel, "simulate"),
        tooltipText=
        "Simulate the world for a few seconds after generating it. Reduces the save file size by processing all of the TileTicks."
    )
    useSnapshotServer = CheckBoxLabel(
        "Use snapshot versions",
        ref=AttrRef(panel, "snapshot"),
        tooltipText="Uses the Latest Snapshot Terrain Generation")

    simRow = Row((simRow, advancedButton), anchor="lrh")
    #deleteCacheRow = Row((Label("Delete Temporary World File Cache?"), Button("Delete Cache!", action=clearCache, tooltipText="Click me if you think your chunks are stale.")))

    serverPanel = Column([useSnapshotServer, versionContainer, simRow],
                         align="l")

    col.append(serverPanel)
    col = Column(col, align="l")
    col.add(flatPanel)
    flatPanel.topleft = serverPanel.topleft
    flatPanel.visible = False
    panel.add(col)

    panel.shrink_wrap()

    def generate(level, arg, useWorldType="DEFAULT"):
        useServer = generatorChoice.selectedChoice == "Minecraft Server"

        if useServer:

            def _createChunks():
                if versionChoice:
                    version = versionChoice.selectedChoice
                else:
                    version = None
                gen = MCServerChunkGenerator(version=version)

                if isinstance(arg, pymclevel.BoundingBox):
                    for i in gen.createLevelIter(level,
                                                 arg,
                                                 simulate=panel.simulate,
                                                 worldType=useWorldType):
                        yield i
                else:
                    for i in gen.generateChunksInLevelIter(
                            level, arg, simulate=panel.simulate):
                        yield i

        else:

            def _createChunks():
                height = panel.chunkHeight
                grass = panel.grass and pymclevel.alphaMaterials.Grass.ID or pymclevel.alphaMaterials.Dirt.ID
                if isinstance(arg, pymclevel.BoundingBox):
                    chunks = list(arg.chunkPositions)
                else:
                    chunks = arg

                if level.dimNo in (-1, 1):
                    maxskylight = 0
                else:
                    maxskylight = 15

                for i, (cx, cz) in enumerate(chunks):

                    yield i, len(chunks)
                    #surface = blockInput.blockInfo

                    #for cx, cz in :
                    try:
                        level.createChunk(cx, cz)
                    except ValueError, e:  # chunk already present
                        print e
                        continue
                    else:
                        ch = level.getChunk(cx, cz)
                        if height > 0:
                            stoneHeight = max(0, height - 5)
                            grassHeight = max(0, height - 1)

                            ch.Blocks[:, :, grassHeight] = grass
                            ch.Blocks[:, :, stoneHeight:
                                      grassHeight] = pymclevel.alphaMaterials.Dirt.ID
                            ch.Blocks[:, :, :
                                      stoneHeight] = pymclevel.alphaMaterials.Stone.ID

                            ch.Blocks[:, :,
                                      0] = pymclevel.alphaMaterials.Bedrock.ID
                            ch.SkyLight[:, :, height:] = maxskylight
                            if maxskylight:
                                ch.HeightMap[:] = height

                        else:
                            ch.SkyLight[:] = maxskylight

                        ch.needsLighting = False
                        ch.dirty = True

        return _createChunks()
예제 #16
0
    def editContainer(self, point, containerID):
        tileEntityTag = self.editor.level.tileEntityAt(*point)
        if tileEntityTag is None:
            tileEntityTag = pymclevel.TileEntity.Create(containerID)
            pymclevel.TileEntity.setpos(tileEntityTag, point)
            self.editor.level.addTileEntity(tileEntityTag)

        if tileEntityTag["id"].value != containerID:
            return

        undoBackupEntityTag = copy.deepcopy(tileEntityTag)

        def itemProp(key):
            # xxx do validation here
            def getter(self):
                if 0 == len(tileEntityTag["Items"]):
                    return 0
                return tileEntityTag["Items"][self.selectedItemIndex][key].value

            def setter(self, val):
                if 0 == len(tileEntityTag["Items"]):
                    return
                self.dirty = True
                tileEntityTag["Items"][self.selectedItemIndex][key].value = val

            return property(getter, setter)

        class ChestWidget(Widget):
            dirty = False
            Slot = itemProp("Slot")
            id = itemProp("id")
            Damage = itemProp("Damage")
            Count = itemProp("Count")
            itemLimit = pymclevel.TileEntity.maxItems.get(containerID, 26)

        def slotFormat(slot):
            slotNames = pymclevel.TileEntity.slotNames.get(containerID)
            if slotNames:
                return slotNames.get(slot, slot)
            return slot

        chestWidget = ChestWidget()
        chestItemTable = TableView(columns=[
            TableColumn("Slot", 60, "l", fmt=slotFormat),
            TableColumn("ID / ID Name", 345, "l"),
            TableColumn("DMG", 50, "l"),
            TableColumn("Count", 65, "l"),

            TableColumn("Name", 260, "l"),
        ])

        def itemName(id, damage):
            try:
                return pymclevel.items.items.findItem(id, damage).name
            except pymclevel.items.ItemNotFound:
                return "Unknown Item"

        def getRowData(i):
            item = tileEntityTag["Items"][i]
            slot, id, damage, count = item["Slot"].value, item["id"].value, item["Damage"].value, item["Count"].value
            return slot, id, damage, count, itemName(id, damage)

        chestWidget.selectedItemIndex = 0

        def selectTableRow(i, evt):
            chestWidget.selectedItemIndex = i

        chestItemTable.num_rows = lambda: len(tileEntityTag["Items"])
        chestItemTable.row_data = getRowData
        chestItemTable.row_is_selected = lambda x: x == chestWidget.selectedItemIndex
        chestItemTable.click_row = selectTableRow

        fieldRow = (
            mceutils.IntInputRow("Slot: ", ref=AttrRef(chestWidget, 'Slot'), min=0, max=26),
            mceutils.TextInputRow("ID / ID Name: ", ref=AttrRef(chestWidget, 'id'), width=300),
            # Text to allow the input of internal item names
            mceutils.IntInputRow("DMG: ", ref=AttrRef(chestWidget, 'Damage'), min=-32768, max=32767),
            mceutils.IntInputRow("Count: ", ref=AttrRef(chestWidget, 'Count'), min=-64, max=64),
        )

        def deleteFromWorld():
            i = chestWidget.selectedItemIndex
            item = tileEntityTag["Items"][i]
            id = item["id"].value
            Damage = item["Damage"].value

            deleteSameDamage = mceutils.CheckBoxLabel("Only delete items with the same damage value")
            deleteBlocksToo = mceutils.CheckBoxLabel("Also delete blocks placed in the world")
            if id not in (8, 9, 10, 11):  # fluid blocks
                deleteBlocksToo.value = True

            w = wrapped_label(
                "WARNING: You are about to modify the entire world. This cannot be undone. Really delete all copies of this item from all land, chests, furnaces, dispensers, dropped items, item-containing tiles, and player inventories in this world?",
                60)
            col = (w, deleteSameDamage)
            if id < 256:
                col += (deleteBlocksToo,)

            d = Dialog(Column(col), ["OK", "Cancel"])

            if d.present() == "OK":
                def deleteItemsIter():
                    i = 0
                    if deleteSameDamage.value:
                        def matches(t):
                            return t["id"].value == id and t["Damage"].value == Damage
                    else:
                        def matches(t):
                            return t["id"].value == id

                    def matches_itementity(e):
                        if e["id"].value != "Item":
                            return False
                        if "Item" not in e:
                            return False
                        t = e["Item"]
                        return matches(t)

                    for player in self.editor.level.players:
                        tag = self.editor.level.getPlayerTag(player)
                        l = len(tag["Inventory"])
                        tag["Inventory"].value = [t for t in tag["Inventory"].value if not matches(t)]

                    for chunk in self.editor.level.getChunks():
                        if id < 256 and deleteBlocksToo.value:
                            matchingBlocks = chunk.Blocks == id
                            if deleteSameDamage.value:
                                matchingBlocks &= chunk.Data == Damage
                            if any(matchingBlocks):
                                chunk.Blocks[matchingBlocks] = 0
                                chunk.Data[matchingBlocks] = 0
                                chunk.chunkChanged()
                                self.editor.invalidateChunks([chunk.chunkPosition])

                        for te in chunk.TileEntities:
                            if "Items" in te:
                                l = len(te["Items"])

                                te["Items"].value = [t for t in te["Items"].value if not matches(t)]
                                if l != len(te["Items"]):
                                    chunk.dirty = True
                        entities = [e for e in chunk.Entities if matches_itementity(e)]
                        if len(entities) != len(chunk.Entities):
                            chunk.Entities.value = entities
                            chunk.dirty = True

                        yield (i, self.editor.level.chunkCount)
                        i += 1

                progressInfo = _("Deleting the item {0} from the entire world ({1} chunks)").format(
                    itemName(chestWidget.id, 0), self.editor.level.chunkCount)

                mceutils.showProgress(progressInfo, deleteItemsIter(), cancel=True)

                self.editor.addUnsavedEdit()
                chestWidget.selectedItemIndex = min(chestWidget.selectedItemIndex, len(tileEntityTag["Items"]) - 1)

        def deleteItem():
            i = chestWidget.selectedItemIndex
            item = tileEntityTag["Items"][i]
            tileEntityTag["Items"].value = [t for t in tileEntityTag["Items"].value if t is not item]
            chestWidget.selectedItemIndex = min(chestWidget.selectedItemIndex, len(tileEntityTag["Items"]) - 1)

        def deleteEnable():
            return len(tileEntityTag["Items"]) and chestWidget.selectedItemIndex != -1

        def addEnable():
            return len(tileEntityTag["Items"]) < chestWidget.itemLimit

        def addItem():
            slot = 0
            for item in tileEntityTag["Items"]:
                if slot == item["Slot"].value:
                    slot += 1
            if slot >= chestWidget.itemLimit:
                return
            item = pymclevel.TAG_Compound()
            item["id"] = pymclevel.TAG_String("minecraft:")
            item["Damage"] = pymclevel.TAG_Short(0)
            item["Slot"] = pymclevel.TAG_Byte(slot)
            item["Count"] = pymclevel.TAG_Byte(1)
            tileEntityTag["Items"].append(item)

        addItemButton = Button("New Item (1.7+)", action=addItem, enable=addEnable)
        deleteItemButton = Button("Delete This Item", action=deleteItem, enable=deleteEnable)
        deleteFromWorldButton = Button("Delete All Instances Of This Item From World", action=deleteFromWorld,
                                       enable=deleteEnable)
        deleteCol = Column((addItemButton, deleteItemButton, deleteFromWorldButton))

        fieldRow = Row(fieldRow)
        col = Column((chestItemTable, fieldRow, deleteCol))

        chestWidget.add(col)
        chestWidget.shrink_wrap()

        Dialog(client=chestWidget, responses=["Done"]).present()
        level = self.editor.level

        class ChestEditOperation(Operation):
            def __init__(self, tool, level):
                self.tool = tool
                self.level = level
                self.undoBackupEntityTag = undoBackupEntityTag
                self.canUndo = False

            def perform(self, recordUndo=True):
                if self.level.saving:
                    alert("Cannot perform action while saving is taking place")
                    return
                level.addTileEntity(tileEntityTag)
                self.canUndo = True

            def undo(self):
                self.redoBackupEntityTag = copy.deepcopy(tileEntityTag)
                level.addTileEntity(self.undoBackupEntityTag)
                return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntityTag), (1, 1, 1))

            def redo(self):
                level.addTileEntity(self.redoBackupEntityTag)
                return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntityTag), (1, 1, 1))

        if chestWidget.dirty:
            op = ChestEditOperation(self.editor, self.editor.level)
            self.editor.addOperation(op)
            if op.canUndo:
                self.editor.addUnsavedEdit()
예제 #17
0
    def makeTabPage(self, tool, inputs, trn=None, **kwargs):
        page = Widget(**kwargs)
        page.is_gl_container = True
        rows = []
        cols = []
        max_height = tool.editor.mainViewport.height - tool.editor.toolbar.height - tool.editor.subwidgets[0].height -\
            self._parent.filterSelectRow.height - self._parent.confirmButton.height - self.pages.tab_height

        page.optionDict = {}
        page.tool = tool
        title = "Tab"

        for optionSpec in inputs:
            optionName = optionSpec[0]
            optionType = optionSpec[1]
            if trn is not None:
                n = trn._(optionName)
            else:
                n = optionName
            if n == optionName:
                oName = _(optionName)
            else:
                oName = n
            if isinstance(optionType, tuple):
                if isinstance(optionType[0], (int, long, float)):
                    if len(optionType) == 3:
                        val, min, max = optionType
                        increment = 0.1
                    elif len(optionType) == 2:
                        min, max = optionType
                        val = min
                        increment = 0.1
                    else:
                        val, min, max, increment = optionType

                    rows.append(
                        addNumField(page, optionName, oName, val, min, max,
                                    increment))

                if isinstance(optionType[0], (str, unicode)):
                    isChoiceButton = False

                    if optionType[0] == "string":
                        kwds = []
                        wid = None
                        val = None
                        for keyword in optionType:
                            if isinstance(
                                    keyword,
                                (str, unicode)) and keyword != "string":
                                kwds.append(keyword)
                        for keyword in kwds:
                            splitWord = keyword.split('=')
                            if len(splitWord) > 1:
                                v = None

                                try:
                                    v = int(splitWord[1])
                                except ValueError:
                                    pass

                                key = splitWord[0]
                                if v is not None:
                                    if key == "width":
                                        wid = v
                                else:
                                    if key == "value":
                                        val = "=".join(splitWord[1:])

                        if val is None:
                            val = ""
                        if wid is None:
                            wid = 200

                        field = TextFieldWrapped(value=val, width=wid)
                        page.optionDict[optionName] = AttrRef(field, 'value')

                        row = Row((Label(oName, doNotTranslate=True), field))
                        rows.append(row)
                    else:
                        isChoiceButton = True

                    if isChoiceButton:
                        if trn is not None:
                            __ = trn._
                        else:
                            __ = _
                        choices = [__("%s" % a) for a in optionType]
                        choiceButton = ChoiceButton(choices,
                                                    doNotTranslate=True)
                        page.optionDict[optionName] = AttrRef(
                            choiceButton, 'selectedChoice')

                        rows.append(
                            Row((Label(oName,
                                       doNotTranslate=True), choiceButton)))

            elif isinstance(optionType, bool):
                cbox = CheckBox(value=optionType)
                page.optionDict[optionName] = AttrRef(cbox, 'value')

                row = Row((Label(oName, doNotTranslate=True), cbox))
                rows.append(row)

            elif isinstance(optionType, (int, float)):
                rows.append(addNumField(self, optionName, oName, optionType))

            elif optionType == "blocktype" or isinstance(
                    optionType, pymclevel.materials.Block):
                blockButton = BlockButton(tool.editor.level.materials)
                if isinstance(optionType, pymclevel.materials.Block):
                    blockButton.blockInfo = optionType

                row = Column((Label(oName, doNotTranslate=True), blockButton))
                page.optionDict[optionName] = AttrRef(blockButton, 'blockInfo')

                rows.append(row)
            elif optionType == "label":
                rows.append(wrapped_label(oName, 50, doNotTranslate=True))

            elif optionType == "string":
                inp = None
                # not sure how to pull values from filters,
                # but leaves it open for the future. Use this variable to set field width.
                if inp is not None:
                    size = inp
                else:
                    size = 200
                field = TextFieldWrapped(value="")
                row = TextInputRow(oName,
                                   ref=AttrRef(field, 'value'),
                                   width=size,
                                   doNotTranslate=True)
                page.optionDict[optionName] = AttrRef(field, 'value')
                rows.append(row)

            elif optionType == "title":
                title = oName

            elif type(
                    optionType) == list and optionType[0].lower() == "nbttree":
                kw = {'close_text': None, 'load_text': None}
                if len(optionType) >= 3:

                    def close():
                        self.pages.show_page(self.pages.pages[optionType[2]])

                    kw['close_action'] = close
                    kw['close_text'] = "Go Back"
                if len(optionType) >= 4:
                    if optionType[3]:
                        kw['load_text'] = optionType[3]
                if hasattr(self.module, 'nbt_ok_action'):
                    kw['ok_action'] = getattr(self.module, 'nbt_ok_action')
                self.nbttree = NBTExplorerToolPanel(self.tool.editor,
                                                    nbtObject=optionType[1],
                                                    height=max_height,
                                                    no_header=True,
                                                    copy_data=False,
                                                    **kw)
                self.module.set_tree(self.nbttree.tree)
                for meth_name in dir(self.module):
                    if meth_name.startswith('nbttree_'):
                        setattr(self.nbttree.tree.treeRow,
                                meth_name.split('nbttree_')[-1],
                                getattr(self.module, meth_name))
                        # elif meth_name.startswith('nbt_'):
                        #     setattr(self.nbttree, meth_name.split('nbt_')[-1], getattr(self.module, meth_name))
                page.optionDict[optionName] = AttrRef(self, 'rebuildTabPage')
                rows.append(self.nbttree)
                self.nbttree.page = len(self.pgs)

            else:
                raise ValueError(("Unknown option type", optionType))

        height = sum(r.height for r in rows) + (len(rows) - 1) * self.spacing

        if height > max_height:
            h = 0
            for i, r in enumerate(rows):
                h += r.height
                if h > height / 2:
                    if rows[:i]:
                        cols.append(Column(rows[:i], spacing=0))
                    rows = rows[i:]
                    break

        if len(rows):
            cols.append(Column(rows, spacing=0))

        if len(cols):
            page.add(Row(cols, spacing=0))
        page.shrink_wrap()

        return title, page, page._rect
예제 #18
0
def showProgress(progressText, progressIterator, cancel=False):
    """Show the progress for a long-running synchronous operation.
    progressIterator should be a generator-like object that can return
    either None, for an indeterminate indicator,
    A float value between 0.0 and 1.0 for a determinate indicator,
    A string, to update the progress info label
    or a tuple of (float value, string) to set the progress and update the label"""
    class ProgressWidget(Dialog):
        progressFraction = 0.0
        firstDraw = False

        def draw(self, surface):
            Widget.draw(self, surface)
            frameStart = datetime.now()
            frameInterval = timedelta(0, 1, 0) / 2
            amount = None

            try:
                while datetime.now() < frameStart + frameInterval:
                    amount = progressIterator.next()
                    if self.firstDraw is False:
                        self.firstDraw = True
                        break

            except StopIteration:
                self.dismiss()

            infoText = ""
            if amount is not None:

                if isinstance(amount, tuple):
                    if len(amount) > 2:
                        infoText = ": " + amount[2]

                    amount, max = amount[:2]

                else:
                    max = amount
                maxwidth = (self.width - self.margin * 2)
                if amount is None:
                    self.progressBar.width = maxwidth
                    self.progressBar.bg_color = (255, 255, 25, 255)
                elif isinstance(amount, basestring):
                    self.statusText = amount
                else:
                    self.progressAmount = amount
                    if isinstance(amount, (int, float)):
                        self.progressFraction = float(amount) / (float(max)
                                                                 or 1)
                        self.progressBar.width = maxwidth * self.progressFraction
                        self.statusText = str("{0} / {1}".format(amount, max))
                    else:
                        self.statusText = str(amount)

                if infoText:
                    self.statusText += infoText

        @property
        def estimateText(self):
            delta = ((datetime.now() - self.startTime))
            progressPercent = (int(self.progressFraction * 10000))
            left = delta * (10000 - progressPercent) / (progressPercent or 1)
            return "Time left: {0}".format(left)

        def cancel(self):
            if cancel:
                self.dismiss(False)

        def idleevent(self, evt):
            self.invalidate()

    widget = ProgressWidget()
    widget.progressText = progressText
    widget.statusText = ""
    widget.progressAmount = 0.0

    progressLabel = ValueDisplay(ref=AttrRef(widget, 'progressText'),
                                 width=550)
    statusLabel = ValueDisplay(ref=AttrRef(widget, 'statusText'), width=550)
    estimateLabel = ValueDisplay(ref=AttrRef(widget, 'estimateText'),
                                 width=550)

    progressBar = Widget(size=(550, 20), bg_color=(150, 150, 150, 255))
    widget.progressBar = progressBar
    col = (progressLabel, statusLabel, estimateLabel, progressBar)
    if cancel:
        cancelButton = Button("Cancel",
                              action=widget.cancel,
                              fg_color=(255, 0, 0, 255))
        col += (Column((cancelButton, ), align="r"), )

    widget.add(Column(col))
    widget.shrink_wrap()
    widget.startTime = datetime.now()
    if widget.present():
        return widget.progressAmount
    else:
        return "Canceled"
예제 #19
0
    def makeTabPage(self, tool, inputs):
        page = Widget()
        page.is_gl_container = True
        rows = []
        cols = []
        height = 0
        max_height = 550
        page.optionDict = {}
        page.tool = tool
        title = "Tab"

        for optionName, optionType in inputs:
            if isinstance(optionType, tuple):
                if isinstance(optionType[0], (int, long, float)):
                    if len(optionType) > 2:
                        val, min, max = optionType
                    elif len(optionType) == 2:
                        min, max = optionType
                        val = min

                    rows.append(addNumField(page, optionName, val, min, max))

                if isinstance(optionType[0], (str, unicode)):
                    isChoiceButton = False

                    if optionType[0] == "string":
                        kwds = []
                        wid = None
                        val = None
                        for keyword in optionType:
                            if isinstance(keyword, (str, unicode)) and keyword != "string":
                                kwds.append(keyword)
                        for keyword in kwds:
                            splitWord = keyword.split('=')
                            if len(splitWord) > 1:
                                v = None
                                key = None

                                try:
                                    v = int(splitWord[1])
                                except:
                                    pass

                                key = splitWord[0]
                                if v is not None:
                                    if key == "lines":
                                        lin = v
                                    elif key == "width":
                                        wid = v
                                else:
                                    if key == "value":
                                        val = splitWord[1]

                        if val is None:
                            val = ""
                        if wid is None:
                            wid = 200

                        field = TextField(value=val, width=wid)
                        page.optionDict[optionName] = AttrRef(field, 'value')

                        row = Row((Label(optionName), field))
                        rows.append(row)
                    else:
                        isChoiceButton = True

                    if isChoiceButton:
                        choiceButton = ChoiceButton(map(str, optionType))
                        page.optionDict[optionName] = AttrRef(choiceButton, 'selectedChoice')

                        rows.append(Row((Label(optionName), choiceButton)))

            elif isinstance(optionType, bool):
                cbox = CheckBox(value=optionType)
                page.optionDict[optionName] = AttrRef(cbox, 'value')

                row = Row((Label(optionName), cbox))
                rows.append(row)

            elif isinstance(optionType, (int, float)):
                rows.append(addNumField(self, optionName, optionType))

            elif optionType == "blocktype" or isinstance(optionType, pymclevel.materials.Block):
                blockButton = BlockButton(tool.editor.level.materials)
                if isinstance(optionType, pymclevel.materials.Block):
                    blockButton.blockInfo = optionType

                row = Column((Label(optionName), blockButton))
                page.optionDict[optionName] = AttrRef(blockButton, 'blockInfo')

                rows.append(row)
            elif optionType == "label":
                rows.append(wrapped_label(optionName, 50))

            elif optionType == "string":
                input = None  # not sure how to pull values from filters, but leaves it open for the future. Use this variable to set field width.
                if input != None:
                    size = input
                else:
                    size = 200
                field = TextField(value="")
                row = TextInputRow(optionName, ref=AttrRef(field, 'value'), width=size)
                page.optionDict[optionName] = AttrRef(field, 'value')
                rows.append(row)

            elif optionType == "title":
                title = optionName

            else:
                raise ValueError(("Unknown option type", optionType))

        height = sum(r.height for r in rows)

        if height > max_height:
            h = 0
            for i, r in enumerate(rows):
                h += r.height
                if h > height / 2:
                    break

            cols.append(Column(rows[:i]))
            rows = rows[i:]
        # cols.append(Column(rows))

        if len(rows):
            cols.append(Column(rows))

        if len(cols):
            page.add(Row(cols))
        page.shrink_wrap()

        return (title, page, page._rect)
예제 #20
0
    def __init__(self, tool):
        Panel.__init__(self)
        self.tool = tool
        replacing = tool.replacing

        self.blockButton = BlockButton(tool.editor.level.materials)
        self.blockButton.blockInfo = tool.blockInfo
        self.blockButton.action = self.pickFillBlock

        self.fillWithLabel = Label("Fill with:", width=self.blockButton.width, align="c")
        self.fillButton = Button("Fill", action=tool.confirm, width=self.blockButton.width)
        self.fillButton.tooltipText = "Shortcut: Enter"

        rollkey = config.keys.replaceShortcut.get()

        self.replaceLabel = replaceLabel = Label("Replace", width=self.blockButton.width)
        replaceLabel.mouse_down = lambda a: self.tool.toggleReplacing()
        replaceLabel.fg_color = (177, 177, 255, 255)
        # replaceLabelRow = Row( (Label(rollkey), replaceLabel) )
        replaceLabel.tooltipText = _("Shortcut: {0}").format(_(rollkey))
        replaceLabel.align = "c"
        self.noDataCheckBox = CheckBoxLabel("Keep Data Intact", ref=AttrRef(self.tool, "noData"))
        
        col = (self.fillWithLabel,
               self.blockButton,
               # swapRow,
               replaceLabel,
               # self.replaceBlockButton,
               self.fillButton)

        if replacing:
            self.fillWithLabel = Label("Find:", width=self.blockButton.width, align="c")

            self.replaceBlockButton = BlockButton(tool.editor.level.materials)
            self.replaceBlockButton.blockInfo = tool.replaceBlockInfo
            self.replaceBlockButton.action = self.pickReplaceBlock
            self.replaceLabel.text = "Replace with:"
            self.replaceLabel.tooltipText = _("Shortcut: {0}").format(_("Esc"))

            self.swapButton = Button("Swap", action=self.swapBlockTypes, width=self.blockButton.width)
            self.swapButton.fg_color = (255, 255, 255, 255)
            self.swapButton.highlight_color = (60, 255, 60, 255)
            swapkey = config.keys.swap.get()

            self.swapButton.tooltipText = _("Shortcut: {0}").format(_(swapkey))

            self.fillButton = Button("Replace", action=tool.confirm, width=self.blockButton.width)
            self.fillButton.tooltipText = "Shortcut: Enter"

            col = (self.fillWithLabel,
                   self.blockButton,
                   replaceLabel,
                   self.replaceBlockButton,
                   self.noDataCheckBox,
                   self.swapButton,
                   self.fillButton)

        col = Column(col)

        self.add(col)
        self.shrink_wrap()
예제 #21
0
    def __init__(self, tool, editor, _parent=None):
        Panel.__init__(self)
        self.tool = tool

        rotaterollRow = Row((
            Label(config.keys.rotateClone.get()),
            Button("Rotate",
                   width=80,
                   action=tool.rotate,
                   enable=self.transformEnable),
            Label(config.keys.rollClone.get()),
            Button("Roll",
                   width=80,
                   action=tool.roll,
                   enable=self.transformEnable),
        ))

        flipmirrorRow = Row((
            Label(config.keys.flip.get()),
            Button("Flip",
                   width=80,
                   action=tool.flip,
                   enable=self.transformEnable),
            Label(config.keys.mirror.get()),
            Button("Mirror",
                   width=80,
                   action=tool.mirror,
                   enable=self.transformEnable),
        ))

        self.alignCheckBox = CheckBox(ref=AttrRef(self.tool, 'chunkAlign'))
        self.alignLabel = Label("Chunk Align")
        self.alignLabel.mouse_down = self.alignCheckBox.mouse_down

        alignRow = Row((self.alignCheckBox, self.alignLabel))

        # headerLabel = Label("Clone Offset")
        if self.useOffsetInput:
            self.offsetInput = CoordsInput(editor)
            self.offsetInput.coordsChanged = tool.offsetChanged
            self.offsetInput.nudgeButton.bg_color = tool.color
            self.offsetInput.nudge = tool.nudge
        else:
            self.nudgeButton = NudgeButton(editor)
            self.nudgeButton.bg_color = tool.color
            self.nudgeButton.nudge = tool.nudge

        repeatField = IntField(ref=AttrRef(tool, 'repeatCount'))
        repeatField.min = 1
        repeatField.max = 1000

        repeatRow = Row((Label("Repeat"), repeatField))
        self.repeatField = repeatField

        scaleField = FloatField(ref=AttrRef(tool, 'scaleFactor'))
        scaleField.min = 0.1
        scaleField.max = 8

        if self.transformEnable():
            scaleRow = Row((Label("Scale Factor"), scaleField))
        else:
            scaleRow = Row((Label("Scale Factor: 1.0"), ))

        self.scaleField = scaleField

        self.copyAirCheckBox = CheckBox(ref=AttrRef(self.tool, "copyAir"))
        self.copyAirLabel = Label("Copy Air")
        self.copyAirLabel.mouse_down = self.copyAirCheckBox.mouse_down
        self.copyAirLabel.tooltipText = "Shortcut: Alt-1"
        self.copyAirCheckBox.tooltipText = self.copyAirLabel.tooltipText

        copyAirRow = Row((self.copyAirCheckBox, self.copyAirLabel))

        self.copyWaterCheckBox = CheckBox(ref=AttrRef(self.tool, "copyWater"))
        self.copyWaterLabel = Label("Copy Water")
        self.copyWaterLabel.mouse_down = self.copyWaterCheckBox.mouse_down
        self.copyWaterLabel.tooltipText = "Shortcut: Alt-2"
        self.copyWaterCheckBox.tooltipText = self.copyWaterLabel.tooltipText

        copyWaterRow = Row((self.copyWaterCheckBox, self.copyWaterLabel))

        self.copyBiomesCheckBox = CheckBox(
            ref=AttrRef(self.tool, "copyBiomes"))
        self.copyBiomesLabel = Label("Copy Biomes")
        self.copyBiomesLabel.mouse_down = self.copyBiomesCheckBox.mouse_down
        self.copyBiomesLabel.tooltipText = "Shortcut: Alt-3"
        self.copyBiomesCheckBox.tooltipText = self.copyBiomesLabel.tooltipText

        copyBiomesRow = Row((self.copyBiomesCheckBox, self.copyBiomesLabel))

        self.staticCommandsCheckBox = CheckBox(
            ref=AttrRef(self.tool, "staticCommands"))
        self.staticCommandsLabel = Label("Change Coordinates")
        self.staticCommandsLabel.mouse_down = self.staticCommandsCheckBox.mouse_down
        self.staticCommandsLabel.tooltipText = "Check to automatically change command block static coordinates when moved.\nShortcut: Alt-4"
        self.staticCommandsCheckBox.tooltipText = self.staticCommandsLabel.tooltipText

        staticCommandsRow = Row(
            (self.staticCommandsCheckBox, self.staticCommandsLabel))

        self.moveSpawnerPosCheckBox = CheckBox(
            ref=AttrRef(self.tool, "moveSpawnerPos"))
        self.moveSpawnerPosLabel = Label("Change Spawners")
        self.moveSpawnerPosLabel.mouse_down = self.moveSpawnerPosCheckBox.mouse_down
        self.moveSpawnerPosLabel.tooltipText = "Check to automatically change the position of the mobs in spawners when moved.\nShortcut: Alt-5"
        self.moveSpawnerPosCheckBox.tooltipText = self.moveSpawnerPosLabel.tooltipText

        moveSpawnerPosRow = Row(
            (self.moveSpawnerPosCheckBox, self.moveSpawnerPosLabel))

        self.regenerateUUIDCheckBox = CheckBox(
            ref=AttrRef(self.tool, "regenerateUUID"))
        self.regenerateUUIDLabel = Label("Regenerate UUID")
        self.regenerateUUIDLabel.mouse_down = self.regenerateUUIDCheckBox.mouse_down
        self.regenerateUUIDLabel.tooltipText = "Check to automatically generate new UUIDs for entities.\nShortcut: Alt-6"
        self.regenerateUUIDCheckBox.tooltipText = self.regenerateUUIDLabel.tooltipText

        regenerateUUIDRow = Row(
            (self.regenerateUUIDCheckBox, self.regenerateUUIDLabel))

        self.performButton = Button("Clone", width=100, align="c")
        self.performButton.tooltipText = "Shortcut: Enter"
        self.performButton.action = tool.confirm
        self.performButton.enable = lambda: (tool.destPoint is not None)

        max_height = self.tool.editor.mainViewport.height - self.tool.editor.toolbar.height - self.tool.editor.subwidgets[
            0].height  # - self.performButton.height - 2

        def buildPage(*items):
            height = 0
            cls = []
            idx = 0
            for i, r in enumerate(items):
                r.margin = 0
                r.shrink_wrap()
                height += r.height
                if height > max_height:
                    cls.append(Column(items[idx:i], spacing=2, margin=0))
                    idx = i
                    height = 0
            cls.append(Column(items[idx:], spacing=2, margin=0))
            return cls

        if self.useOffsetInput:
            cols = buildPage(rotaterollRow, flipmirrorRow, alignRow,
                             self.offsetInput, repeatRow, scaleRow, copyAirRow,
                             copyWaterRow, copyBiomesRow, staticCommandsRow,
                             moveSpawnerPosRow, regenerateUUIDRow)
        else:
            cols = buildPage(rotaterollRow, flipmirrorRow, alignRow,
                             self.nudgeButton, scaleRow, copyAirRow,
                             copyWaterRow, copyBiomesRow, staticCommandsRow,
                             moveSpawnerPosRow, regenerateUUIDRow)

        row = Row(cols, spacing=0, margin=2)
        row.shrink_wrap()
        col = Column((row, self.performButton), spacing=2)
        self.add(col)
        self.anchor = "lwh"
        self.shrink_wrap()
예제 #22
0
    def __init__old(self, blockInfo, materials, *a, **kw):
        self.root = get_root()
        self.allowWildcards = False
        Dialog.__init__(self, *a, **kw)
        panelWidth = 518

        self.click_outside_response = 0
        self.materials = materials
        self.anySubtype = blockInfo.wildcard

        self.matchingBlocks = materials.allBlocks

        try:
            self.selectedBlockIndex = self.matchingBlocks.index(blockInfo)
        except ValueError:
            self.selectedBlockIndex = 0
            for i, b in enumerate(self.matchingBlocks):
                if blockInfo.ID == b.ID and blockInfo.blockData == b.blockData:
                    self.selectedBlockIndex = i
                    break

        lbl = Label("Search")
        # lbl.rect.topleft = (0,0)

        fld = TextFieldWrapped(300)
        # fld.rect.topleft = (100, 10)
        # fld.centery = lbl.centery
        # fld.left = lbl.right

        fld.change_action = self.textEntered
        fld.enter_action = self.ok
        fld.escape_action = self.cancel

        self.awesomeField = fld

        searchRow = Row((lbl, fld))

        def formatBlockName(x):
            block = self.matchingBlocks[x]
            r = "{name}".format(name=block.name)
            if block.aka:
                r += " [{0}]".format(block.aka)

            return r

        def formatBlockID(x):
            block = self.matchingBlocks[x]
            ident = "({id}:{data})".format(id=block.ID, data=block.blockData)
            return ident

        tableview = TableView(columns=[
            TableColumn(" ", 24, "l", lambda x: ""),
            TableColumn("Name", 415, "l", formatBlockName),
            TableColumn("ID", 45, "l", formatBlockID)
        ])
        tableicons = [
            blockview.BlockView(materials)
            for i in xrange(tableview.rows.num_rows())
        ]
        for t in tableicons:
            t.size = (16, 16)
            t.margin = 0
        icons = Column(tableicons, spacing=2)

        # tableview.margin = 5
        tableview.num_rows = lambda: len(self.matchingBlocks)
        tableview.row_data = lambda x: (self.matchingBlocks[x], x, x)
        tableview.row_is_selected = lambda x: x == self.selectedBlockIndex
        tableview.click_row = self.selectTableRow
        draw_table_cell = tableview.draw_table_cell

        def draw_block_table_cell(surf, i, data, cell_rect, column):
            if isinstance(data, Block):

                tableicons[i - tableview.rows.scroll].blockInfo = data
            else:
                draw_table_cell(surf, i, data, cell_rect, column)

        tableview.draw_table_cell = draw_block_table_cell
        tableview.width = panelWidth
        tableview.anchor = "lrbt"
        # self.add(tableview)
        self.tableview = tableview
        tableWidget = Widget()
        tableWidget.add(tableview)
        tableWidget.shrink_wrap()

        def wdraw(*args):
            for t in tableicons:
                t.blockInfo = materials.Air

        tableWidget.draw = wdraw
        self.blockButton = blockView = thumbview.BlockThumbView(
            materials, self.blockInfo)

        blockView.centerx = self.centerx
        blockView.top = tableview.bottom

        # self.add(blockview)

        but = Button("OK")
        but.action = self.ok
        but.top = blockView.bottom
        but.centerx = self.centerx
        but.align = "c"
        but.height = 30

        if self.allowWildcards:
            # self.add(but)
            anyRow = CheckBoxLabel(
                "Any Subtype",
                ref=AttrRef(self, 'anySubtype'),
                tooltipText=
                "Replace blocks with any data value. Only useful for Replace operations."
            )
            col = Column((searchRow, tableWidget, anyRow, blockView, but))
        else:
            col = Column((searchRow, tableWidget, blockView, but))
        col.anchor = "wh"
        self.anchor = "wh"

        panel = GLBackground()
        panel.bg_color = [i / 255. for i in self.bg_color]
        panel.anchor = "tlbr"
        self.add(panel)

        self.add(col)
        self.add(icons)
        icons.topleft = tableWidget.topleft
        icons.top += tableWidget.margin + 30
        icons.left += tableWidget.margin + 4

        self.shrink_wrap()
        panel.size = self.size

        try:
            self.tableview.rows.scroll_to_item(self.selectedBlockIndex)
        except:
            pass
예제 #23
0
    def __init__(self, tool):
        Panel.__init__(self)
        self.tool = tool

        rotateRow = Row((
            Label(config.config.get("Keys", "Rotate").upper()),
            Button("Rotate",
                   width=80,
                   action=tool.rotate,
                   enable=self.transformEnable),
        ))

        rollRow = Row((
            Label(config.config.get("Keys", "Roll").upper()),
            Button("Roll",
                   width=80,
                   action=tool.roll,
                   enable=self.transformEnable),
        ))

        flipRow = Row((
            Label(config.config.get("Keys", "Flip").upper()),
            Button("Flip",
                   width=80,
                   action=tool.flip,
                   enable=self.transformEnable),
        ))

        mirrorRow = Row((
            Label(config.config.get("Keys", "Mirror").upper()),
            Button("Mirror",
                   width=80,
                   action=tool.mirror,
                   enable=self.transformEnable),
        ))

        alignRow = Row((CheckBox(ref=AttrRef(self.tool, 'chunkAlign')),
                        Label("Chunk Align")))

        # headerLabel = Label("Clone Offset")
        if self.useOffsetInput:
            self.offsetInput = CoordsInput()
            self.offsetInput.coordsChanged = tool.offsetChanged
            self.offsetInput.nudgeButton.bg_color = tool.color
            self.offsetInput.nudge = tool.nudge
        else:
            self.nudgeButton = NudgeButton()
            self.nudgeButton.bg_color = tool.color
            self.nudgeButton.nudge = tool.nudge

        repeatField = IntField(ref=AttrRef(tool, 'repeatCount'))
        repeatField.min = 1
        repeatField.max = 50

        repeatRow = Row((Label("Repeat"), repeatField))
        self.repeatField = repeatField

        scaleField = FloatField(ref=AttrRef(tool, 'scaleFactor'))
        scaleField.min = 0.125
        scaleField.max = 8
        dv = scaleField.decrease_value
        iv = scaleField.increase_value

        def scaleFieldDecrease():
            if scaleField.value > 1 / 8.0 and scaleField.value <= 1.0:
                scaleField.value *= 0.5
            else:
                dv()

        def scaleFieldIncrease():
            if scaleField.value < 1.0:
                scaleField.value *= 2.0
            else:
                iv()

        scaleField.decrease_value = scaleFieldDecrease
        scaleField.increase_value = scaleFieldIncrease

        scaleRow = Row((Label("Scale Factor"), scaleField))

        self.scaleField = scaleField

        self.copyAirCheckBox = CheckBox(ref=AttrRef(self.tool, "copyAir"))
        self.copyAirLabel = Label("Copy Air")
        self.copyAirLabel.mouse_down = self.copyAirCheckBox.mouse_down
        self.copyAirLabel.tooltipText = "Shortcut: ALT-1"
        self.copyAirCheckBox.tooltipText = self.copyAirLabel.tooltipText

        copyAirRow = Row((self.copyAirCheckBox, self.copyAirLabel))

        self.copyWaterCheckBox = CheckBox(ref=AttrRef(self.tool, "copyWater"))
        self.copyWaterLabel = Label("Copy Water")
        self.copyWaterLabel.mouse_down = self.copyWaterCheckBox.mouse_down
        self.copyWaterLabel.tooltipText = "Shortcut: ALT-2"
        self.copyWaterCheckBox.tooltipText = self.copyWaterLabel.tooltipText

        copyWaterRow = Row((self.copyWaterCheckBox, self.copyWaterLabel))

        self.copyBiomesCheckBox = CheckBox(
            ref=AttrRef(self.tool, "copyBiomes"))
        self.copyBiomesLabel = Label("Copy Biomes")
        self.copyBiomesLabel.mouse_down = self.copyBiomesCheckBox.mouse_down
        self.copyBiomesLabel.tooltipText = "Shortcut: ALT-3"
        self.copyBiomesCheckBox.tooltipText = self.copyBiomesLabel.tooltipText

        copyBiomesRow = Row((self.copyBiomesCheckBox, self.copyBiomesLabel))

        self.staticCommandsCheckBox = CheckBox(
            ref=AttrRef(self.tool, "staticCommands"))
        self.staticCommandsLabel = Label("Change Coordinates")
        self.staticCommandsLabel.mouse_down = self.staticCommandsCheckBox.mouse_down
        self.staticCommandsLabel.tooltipText = "Check to automatically change command block static coordinates when moved.\nShortcut: ALT-4"
        self.staticCommandsCheckBox.tooltipText = self.staticCommandsLabel.tooltipText

        staticCommandsRow = Row(
            (self.staticCommandsCheckBox, self.staticCommandsLabel))

        self.performButton = Button("Clone", width=100, align="c")
        self.performButton.tooltipText = "Shortcut: ENTER"
        self.performButton.action = tool.confirm
        self.performButton.enable = lambda: (tool.destPoint is not None)
        if self.useOffsetInput:
            col = Column((rotateRow, rollRow, flipRow, mirrorRow, alignRow,
                          self.offsetInput, repeatRow, scaleRow, copyAirRow,
                          copyWaterRow, copyBiomesRow, staticCommandsRow,
                          self.performButton))
        else:
            col = Column(
                (rotateRow, rollRow, flipRow, mirrorRow, alignRow,
                 self.nudgeButton, copyAirRow, copyWaterRow, copyBiomesRow,
                 staticCommandsRow, self.performButton))

        self.add(col)
        self.anchor = "lwh"

        self.shrink_wrap()
예제 #24
0
    def makeTabPage(self, tool, inputs):
        page = Widget()
        page.is_gl_container = True
        rows = []
        cols = []
        height = 0
        max_height = 550
        page.optionDict = {}
        page.tool = tool
        title = "Tab"

        for optionName, optionType in inputs:
            if isinstance(optionType, tuple):
                if isinstance(optionType[0], (int, long, float)):
                    if len(optionType) > 2:
                        val, min, max = optionType
                    elif len(optionType) == 2:
                        min, max = optionType
                        val = min

                    rows.append(addNumField(page, optionName, val, min, max))

                if isinstance(optionType[0], (str, unicode)):
                    isChoiceButton = False
                    if len(optionType) == 3:
                        a,b,c = optionType
                        if a == "strValSize":
                            field = TextField(value=b, width=c)
                            page.optionDict[optionName] = AttrRef(field, 'value')

                            row = Row((Label(optionName), field))
                            rows.append(row)
                        else:
                            isChoiceButton = True
                    elif len(optionType) == 2:
                        a,b = optionType
                        if a == "strVal":
                            field = TextField(value=b, width=200)
                            page.optionDict[optionName] = AttrRef(field, 'value')

                            row = Row((Label(optionName), field))
                            rows.append(row)
                        elif a == "strSize":
                            field = TextField(value="Input String Here", width=b)
                            page.optionDict[optionName] = AttrRef(field, 'value')

                            row = Row((Label(optionName), field))
                            rows.append(row)
                        else:
                            isChoiceButton = True
                    else:
                        isChoiceButton = True

                    if isChoiceButton:
                        choiceButton = ChoiceButton(map(str, optionType))
                        page.optionDict[optionName] = AttrRef(choiceButton, 'selectedChoice')

                        rows.append(Row((Label(optionName), choiceButton)))

            elif isinstance(optionType, bool):
                cbox = CheckBox(value=optionType)
                page.optionDict[optionName] = AttrRef(cbox, 'value')

                row = Row((Label(optionName), cbox))
                rows.append(row)

            elif isinstance(optionType, (int, float)):
                rows.append(addNumField(self, optionName, optionType))

            elif optionType == "blocktype" or isinstance(optionType, pymclevel.materials.Block):
                blockButton = BlockButton(tool.editor.level.materials)
                if isinstance(optionType, pymclevel.materials.Block):
                    blockButton.blockInfo = optionType

                row = Column((Label(optionName), blockButton))
                page.optionDict[optionName] = AttrRef(blockButton, 'blockInfo')

                rows.append(row)
            elif optionType == "label":
                rows.append(wrapped_label(optionName, 50))

            elif optionType == "string":
                field = TextField(value="Input String Here", width=200)
                page.optionDict[optionName] = AttrRef(field, 'value')

                row = Row((Label(optionName), field))
                rows.append(row)

            elif optionType == "title":
                title = optionName

            else:
                raise ValueError(("Unknown option type", optionType))

        height = sum(r.height for r in rows)

        if height > max_height:
            h = 0
            for i, r in enumerate(rows):
                h += r.height
                if h > height / 2:
                    break

            cols.append(Column(rows[:i]))
            rows = rows[i:]
        #cols.append(Column(rows))

        if len(rows):
            cols.append(Column(rows))

        if len(cols):
            page.add(Row(cols))
        page.shrink_wrap()

        return (title, page, page._rect)