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())
Example #2
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(), "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 = 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()
Example #3
0
    def __init__(self,
                 materials,
                 blockInfo=None,
                 ref=None,
                 recentBlocks=None,
                 *a,
                 **kw):
        self.allowWildcards = False
        if 'name' not in kw.keys():
            kw['name'] = 'Panel.BlockButton'
        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()
Example #4
0
    def createChunks(self):
        panel = GeneratorPanel()
        col = [panel]
        label = Label("Create chunks using the settings above? This cannot be undone.")
        col.append(Row([Label("")]))
        col.append(label)
        col = Column(col)
        if Dialog(client=col, responses=["OK", "Cancel"]).present() == "Cancel":
            return
        chunks = self.selectedChunks()

        createChunks = panel.generate(self.editor.level, chunks)

        try:
            with setWindowCaption("CREATING - "):
                showProgress("Creating {0} chunks...".format(len(chunks)), createChunks, cancel=True)
        except Exception, e:
            traceback.print_exc()
            alert(_("Failed to start the chunk generator. {0!r}").format(e))
Example #5
0
    def createRecentBlockView(self):
        def makeBlockView(bi):
            bv = BlockView(self.materials, bi)
            bv.size = (16, 16)

            def action(evt):
                self.blockInfo = bi

            bv.mouse_up = action
            return bv

        row = [makeBlockView(bi) for bi in self.recentBlocks]
        row = Row(row)

        widget = GLBackground()
        widget.bg_color = (0.8, 0.8, 0.8, 0.8)
        widget.add(row)
        widget.shrink_wrap()
        widget.anchor = "whtr"
        return widget
Example #6
0
    def __init__(self, editor):
        Widget.__init__(self)

        self.nudgeButton = NudgeButton(editor)
        self.nudgeButton.nudge = self._nudge

        self.xField = IntField(value=0)
        self.yField = IntField(value=0)
        self.zField = IntField(value=0)

        for field in (self.xField, self.yField, self.zField):
            field.change_action = self._coordsChanged
            field.enter_passes = False

        offsetCol = Column((self.xField, self.yField, self.zField))

        nudgeOffsetRow = Row((offsetCol, self.nudgeButton))

        self.add(nudgeOffsetRow)
        self.shrink_wrap()
Example #7
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
Example #8
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()
Example #9
0
    def removePreset(self):
        """
        Brings up a panel to remove presets.
        """
        panel = Dialog()
        p = self.getBrushFileList()
        if not p:
            alert('No presets saved')
            return

        def okPressed():
            panel.dismiss()
            name = p[presetTable.selectedIndex] + ".preset"
            os.remove(os.path.join(directories.brushesDir, name))
            self.tool.showPanel()

        def selectTableRow(i, evt):
            presetTable.selectedIndex = i
            if evt.num_clicks == 2:
                okPressed()

        presetTable = TableView(columns=(TableColumn("", 200), ))
        presetTable.num_rows = lambda: len(p)
        presetTable.row_data = lambda i: (p[i], )
        presetTable.row_is_selected = lambda x: x == presetTable.selectedIndex
        presetTable.click_row = selectTableRow
        presetTable.selectedIndex = 0
        choiceCol = Column(
            (ValueDisplay(width=200,
                          get_value=lambda: "Select preset to delete"),
             presetTable))
        okButton = Button("OK", action=okPressed)
        cancelButton = Button("Cancel", action=panel.dismiss)
        row = Row([okButton, cancelButton])
        panel.add(Column((choiceCol, row)))
        panel.shrink_wrap()
        panel.present()
Example #10
0
    def __init__(self, tool):
        Panel.__init__(self, name='Panel.FilterToolPanel')
        self.macro_steps = []
        self.current_step = 0
        self._filter_json = None
        self.keys_panel = None
        self.filterOptionsPanel = None
        self.filterSelect = ChoiceButton([], choose=self.filterChanged, doNotTranslate=True)
        self.binding_button = Button("", action=self.bind_key,
                                     tooltipText="Click to bind this filter to a key")

        self.filterLabel = Label("Filter:", fg_color=(177, 177, 255, 255))
        self.filterLabel.mouse_down = lambda x: mcplatform.platform_open(directories.getFiltersDir())
        self.filterLabel.tooltipText = "Click to open filters folder"

        self.macro_button = Button("Record Macro", action=self.start_record_macro)
        self.filterSelectRow = Row((self.filterLabel, self.filterSelect,
                                    self.macro_button, self.binding_button))

        self.confirmButton = Button("Filter", action=self.confirm)

        self._recording = False
        self._save_macro = False
        self.tool = tool
        self.selectedName = self.filter_json.get("Last Filter Opened", "")
        
        
        utils = FilterUtils(
                            editor=tool.editor, 
                            materials=self.tool.editor.level.materials,
                            custom_widget=tool.editor.addExternalWidget,
                            resize_selection_box=tool.editor._resize_selection_box
                            )
        utils_module = imp.new_module("filter_utils")
        utils_module = utils
        sys.modules["filter_utils"] = utils_module
Example #11
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()
Example #12
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)
Example #13
0
def IntInputRow(title, *args, **kw):
    return Row(
        (Label(title,
               tooltipText=kw.get('tooltipText')), IntField(*args, **kw)))
Example #14
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()
Example #15
0
    def editCommandBlock(self, point):
        panel = Dialog()
        block = self.editor.level.blockAt(*point)
        blockData = self.editor.level.blockDataAt(*point)
        tileEntity = self.editor.level.tileEntityAt(*point)
        undoBackupEntityTag = copy.deepcopy(tileEntity)

        if not tileEntity:
            tileEntity = pymclevel.TAG_Compound()
            tileEntity["id"] = pymclevel.TAG_String("Control")
            tileEntity["x"] = pymclevel.TAG_Int(point[0])
            tileEntity["y"] = pymclevel.TAG_Int(point[1])
            tileEntity["z"] = pymclevel.TAG_Int(point[2])
            tileEntity["Command"] = pymclevel.TAG_String()
            tileEntity["CustomName"] = pymclevel.TAG_String("@")
            tileEntity["TrackOutput"] = pymclevel.TAG_Byte(0)
            self.editor.level.addTileEntity(tileEntity)

        titleLabel = Label("Edit Command Block")
        commandField = TextField(width=200)
        nameField = TextField(width=100)
        trackOutput = CheckBox()

        commandField.value = tileEntity["Command"].value
        oldCommand = commandField.value
        trackOutput.value = tileEntity["TrackOutput"].value
        oldTrackOutput = trackOutput.value
        nameField.value = tileEntity["CustomName"].value
        oldNameField = nameField.value

        class CommandBlockEditOperation(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
                self.level.addTileEntity(tileEntity)
                self.canUndo = True

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

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

        def updateCommandBlock():
            if oldCommand != commandField.value or oldTrackOutput != trackOutput.value or oldNameField != nameField.value:
                tileEntity["Command"] = pymclevel.TAG_String(commandField.value)
                tileEntity["TrackOutput"] = pymclevel.TAG_Byte(trackOutput.value)
                tileEntity["CustomName"] = pymclevel.TAG_String(nameField.value)

                op = CommandBlockEditOperation(self.editor, self.editor.level)
                self.editor.addOperation(op)
                if op.canUndo:
                    self.editor.addUnsavedEdit()

            chunk = self.editor.level.getChunk(int(int(point[0]) / 16), int(int(point[2]) / 16))
            chunk.dirty = True
            panel.dismiss()

        okBTN = Button("OK", action=updateCommandBlock)
        cancel = Button("Cancel", action=panel.dismiss)
        column = [titleLabel, Row((Label("Command"), commandField)), Row((Label("Custom Name"), nameField)), Row((Label("Track Output"), trackOutput)), okBTN, cancel]
        panel.add(Column(column))
        panel.shrink_wrap()
        panel.present()

        return
Example #16
0
    def reload(self):
        for i in list(self.subwidgets):
            self.remove(i)

        tool = self.tool

        # Display "No filter modules found" if there are no filters
        if len(tool.filterModules) is 0:
            self.add(Label("No filter modules found!"))
            self.shrink_wrap()
            return

        names_list = sorted(
            [n for n in tool.filterNames if not n.startswith("[")])

        # We get a list of names like ["[foo] bar", "[test] thing"]
        # The to sort on is created by splitting on "[": "[foo", " bar" and then
        # removing the first char: "foo", "bar"

        subfolder_names_list = sorted(
            [n for n in tool.filterNames if n.startswith("[")],
            key=lambda x: x.split("]")[0][1:])

        names_list.extend(subfolder_names_list)
        names_list.extend(
            [macro for macro in self.filter_json["Macros"].keys()])

        if self.selectedName is None or self.selectedName not in names_list:
            self.selectedName = names_list[0]

        # Remove any keybindings that don't have a filter
        for (i, j) in config.config.items("Filter Keys"):
            if i == "__name__":
                continue
            if not any([i == m.lower() for m in names_list]):
                config.config.remove_option("Filter Keys", i)

        self.filterSelect.choices = names_list

        name = self.selectedName.lower()
        names = [k for (k, v) in config.config.items("Filter Keys")]
        btn_name = config.config.get("Filter Keys",
                                     name) if name in names else "*"
        self.binding_button.set_text(btn_name)

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

                if len(tool.filterNames) == 0:
                    raise ValueError("No filters loaded!")
                if not self._recording:
                    self.confirmButton.set_text("Filter")
            else:  # We verified it was an existing macro already
                macro_data = self.filter_json["Macros"][self.selectedName]
                self.filterOptionsPanel = MacroModuleOptions(macro_data)
                self.confirmButton.set_text("Run Macro")

        # This has to be recreated every time in case a macro has a longer name then everything else.
        self.filterSelect = ChoiceButton(names_list,
                                         choose=self.filterChanged,
                                         doNotTranslate=True)
        self.filterSelect.selectedChoice = self.selectedName
        self.filterSelectRow = Row((self.filterLabel, self.filterSelect,
                                    self.macro_button, self.binding_button))

        self.add(
            Column((self.filterSelectRow, self.filterOptionsPanel,
                    self.confirmButton)))

        self.shrink_wrap()

        if self.parent:
            height = self.parent.mainViewport.height - self.parent.toolbar.height
            self.centery = height / 2 + self.parent.subwidgets[0].height

        if self.selectedName in self.tool.savedOptions:
            self.filterOptionsPanel.options = self.tool.savedOptions[
                self.selectedName]
Example #17
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
Example #18
0
    def __init__(self,
                 editor,
                 nbtObject=None,
                 fileName=None,
                 dontSaveRootTag=False,
                 dataKeyName='Data',
                 close_text="Close",
                 load_text="Open",
                 **kwargs):
        """..."""
        Panel.__init__(self)
        self.editor = editor
        self.nbtObject = nbtObject
        self.fileName = fileName
        self.dontSaveRootTag = dontSaveRootTag
        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)
        row = [self.tree,
               Column([
                   Label("", width=300),
               ], 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
Example #19
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
Example #20
0
class FilterToolPanel(Panel):
    def __init__(self, tool):
        Panel.__init__(self)

        self.savedOptions = {}

        self.tool = tool
        self.selectedFilterName = None
        if len(self.tool.filterModules):
            self.reload()

    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!")

        self.filterSelect = ChoiceButton(tool.filterNames,
                                         choose=self.filterChanged)
        self.filterSelect.selectedChoice = self.selectedFilterName

        self.confirmButton = Button("Filter", action=self.tool.confirm)

        filterLabel = Label("Filter:", fg_color=(177, 177, 255, 255))
        filterLabel.mouse_down = lambda x: mcplatform.platform_open(mcplatform.
                                                                    filtersDir)
        filterLabel.tooltipText = "Click to open filters folder"
        filterSelectRow = Row((filterLabel, self.filterSelect))

        self.add(
            Column((filterSelectRow, self.filterOptionsPanel,
                    self.confirmButton)))

        self.shrink_wrap()
        if self.parent:
            self.centery = self.parent.centery

        if self.selectedFilterName in self.savedOptions:
            self.filterOptionsPanel.options = self.savedOptions[
                self.selectedFilterName]
Example #21
0
    def __init__(self,
                 editor,
                 nbtObject=None,
                 fileName=None,
                 dontSaveRootTag=False,
                 dataKeyName='Data',
                 **kwargs):
        """..."""
        Panel.__init__(self)
        self.editor = editor
        self.nbtObject = nbtObject
        self.fileName = fileName
        self.dontSaveRootTag = dontSaveRootTag
        self.displayed_item = None
        self.dataKeyName = dataKeyName
        self.init_data()
        btnRow = Row(
            [
                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=self.reset,
                       tooltipText="Reset ALL your changes in the NBT data."),
                Button("Close", action=self.close),
            ],
            margin=1,
            spacing=4,
        )
        btnRow.shrink_wrap()

        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:
            header = Label("NBT Explorer")
            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,
                            inner_width=250,
                            data=self.data,
                            compound_types=self.compounds,
                            draw_zebra=False,
                            _parent=self,
                            styles=bullet_styles)
        col = Column([self.tree, btnRow], margin=0, spacing=2)
        col.shrink_wrap()
        row = [
            col,
            Column([
                Label("", width=300),
            ],
                   height=max_height + btnRow.height + 2)
        ]
        self.displayRow = Row(row, height=max_height + btnRow.height + 2)
        if kwargs.get('no_header', False):
            self.add(
                Column([
                    self.displayRow,
                ],
                       height=max_height + btnRow.height + 2,
                       margin=0))
        else:
            self.add(Column([header, self.displayRow], margin=0))
        self.shrink_wrap()
        self.side_panel = None
Example #22
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()
Example #23
0
def FloatInputRow(title, *args, **kw):
    warn(FloatInputRow)
    return Row(
        (Label(title,
               tooltipText=kw.get('tooltipText')), FloatField(*args, **kw)))
Example #24
0
def TextInputRow(title, *args, **kw):
    warn(TextInputRow)
    return Row((Label(title, tooltipText=kw.get('tooltipText')),
                TextFieldWrapped(*args, **kw)))
Example #25
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
Example #26
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()
Example #27
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()
Example #28
0
    def __init__(self, tool):
        Panel.__init__(self)
        self.tool = tool
        useStyleBox = CheckBoxLabel(title="Use Bullet Styles",
                                    ref=config.nbtTreeSettings.useBulletStyles)

        self.useStyleBox = useStyleBox
        useTextBox = CheckBoxLabel(title="Use Bullet Text",
                                   ref=config.nbtTreeSettings.useBulletText)
        self.useTextBox = useTextBox
        useImagesBox = CheckBoxLabel(
            title="Use Bullet Images",
            ref=config.nbtTreeSettings.useBulletImages)
        self.useImagesBox = useImagesBox
        bulletFilePath = Row(
            (Button("Bullet Images File", action=self.open_bullet_file),
             TextFieldWrapped(ref=config.nbtTreeSettings.bulletFileName,
                              width=300)),
            margin=0)

        def mouse_down(e):
            if self.bulletFilePath.subwidgets[1].enabled:
                TextFieldWrapped.mouse_down(self.bulletFilePath.subwidgets[1],
                                            e)

        bulletFilePath.subwidgets[1].mouse_down = mouse_down
        self.bulletFilePath = bulletFilePath

        def mouse_down(e):
            CheckBox.mouse_down(useImagesBox.subwidgets[1], e)
            for sub in bulletFilePath.subwidgets:
                sub.enabled = config.nbtTreeSettings.useBulletImages.get()
                if type(sub) == TextFieldWrapped:
                    if config.nbtTreeSettings.useBulletImages.get():
                        sub.fg_color = fg_color
                    else:
                        sub.fg_color = disabled_color

        useImagesBox.subwidgets[0].mouse_down = useImagesBox.subwidgets[
            1].mouse_down = mouse_down

        def mouse_down(e):
            CheckBox.mouse_down(useStyleBox.subwidgets[1], e)
            useImagesBox.mouse_down(e)
            self.useStyleBox_click(e)

        useStyleBox.subwidgets[0].mouse_down = useStyleBox.subwidgets[
            1].mouse_down = mouse_down

        showAllTags = CheckBoxLabel(title="Show all the tags in the tree",
                                    ref=config.nbtTreeSettings.showAllTags)

        col = Column((
            Label("NBT Tree Settings"),
            Row((useStyleBox, useTextBox, useImagesBox)),
            bulletFilePath,
            showAllTags,
            #                      Button("Load NBT file...", action=tool.loadFile),
            Button("OK", action=self.dismiss),
        ))
        self.add(col)
        self.shrink_wrap()
        self.useStyleBox_click(None)
Example #29
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 Biome(s)")
        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("Update Command Block Coords")
        self.staticCommandsLabel.mouse_down = self.staticCommandsCheckBox.mouse_down
        self.staticCommandsLabel.tooltipText = "When a command block is moved, and it contains a command, automatically update static coordinates (x y z) within that command.\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("Update Spawner Coords")
        self.moveSpawnerPosLabel.mouse_down = self.moveSpawnerPosCheckBox.mouse_down
        self.moveSpawnerPosLabel.tooltipText = (
            "When a spawner is moved, automatically update its spawning coordinates.\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 Entity UUID")
        self.regenerateUUIDLabel.mouse_down = self.regenerateUUIDCheckBox.mouse_down
        self.regenerateUUIDLabel.tooltipText = (
            "Automatically generate new UUIDs for every entity copied. [RECOMMENDED]\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()
Example #30
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)