Esempio n. 1
0
    def __init__(self, tool):
        Panel.__init__(self)
        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", "")
Esempio n. 2
0
    def openSavePresetDialog(self):
        """
        Opens up a dialgo to input the name of the to save Preset.
        """
        panel = Dialog()
        label = Label("Preset Name:")
        nameField = TextFieldWrapped(width=200)

        def okPressed():
            panel.dismiss()
            name = nameField.value

            if name in ['Load Preset', 'Remove Presets', '__temp__']:
                alert(
                    "That preset name is reserved. Try pick another preset name."
                )
                return

            for p in ['<', '>', ':', '\"', '/', '\\', '|', '?', '*', '.']:
                if p in name:
                    alert('Invalid character in file name')
                    return

            self.tool.saveBrushPreset(name)
            self.tool.showPanel()

        okButton = Button("OK", action=okPressed)
        cancelButton = Button("Cancel", action=panel.dismiss)
        namerow = Row([label, nameField])
        buttonRow = Row([okButton, cancelButton])

        panel.add(Column([namerow, buttonRow]))
        panel.shrink_wrap()
        panel.present()
Esempio n. 3
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
Esempio n. 4
0
    def __init__(self, items, keysColumn=None, buttonsColumn=None):
        if keysColumn is None:
            keysColumn = []
        if buttonsColumn is None:
            buttonsColumn = []

        Widget.__init__(self)
        for (hotkey, title, action) in items:
            if isinstance(title, (str, unicode)):
                button = Button(title, action=action)
            else:
                button = ValueButton(ref=title, action=action, width=200)
            button.anchor = self.anchor

            label = Label(hotkey, width=75, margin=button.margin)
            label.anchor = "wh"

            label.height = button.height

            keysColumn.append(label)
            buttonsColumn.append(button)

        self.buttons = list(buttonsColumn)

        buttonsColumn = Column(buttonsColumn)
        buttonsColumn.anchor = self.anchor
        keysColumn = Column(keysColumn)

        commandRow = Row((keysColumn, buttonsColumn))
        self.add(commandRow)
        self.shrink_wrap()
    def __init__(self, items, keysColumn=None, buttonsColumn=None):
        if keysColumn is None:
            keysColumn = []
        if buttonsColumn is None:
            buttonsColumn = []

        Widget.__init__(self)
        for (hotkey, title, action) in items:
            if isinstance(title, (str, unicode)):
                button = Button(title, action=action)
            else:
                button = ValueButton(ref=title, action=action, width=200)
            button.anchor = self.anchor

            label = Label(hotkey, width=75, margin=button.margin)
            label.anchor = "wh"

            label.height = button.height

            keysColumn.append(label)
            buttonsColumn.append(button)

        self.buttons = list(buttonsColumn)

        buttonsColumn = Column(buttonsColumn)
        buttonsColumn.anchor = self.anchor
        keysColumn = Column(keysColumn)

        commandRow = Row((keysColumn, buttonsColumn))
        self.add(commandRow)
        self.shrink_wrap()
Esempio n. 6
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()
Esempio n. 7
0
    def __init__(self, tool):
        Panel.__init__(self)
        self.tool = tool
        replacing = tool.replacing

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

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

        rollkey = config.keys.replaceShortcut.get()

        self.replaceLabel = replaceLabel = Label("Replace", width=self.blockButton.width)
        replaceLabel.mouse_down = lambda a: self.tool.toggleReplacing()
        replaceLabel.fg_color = (177, 177, 255, 255)
        # replaceLabelRow = Row( (Label(rollkey), replaceLabel) )
        replaceLabel.tooltipText = "Shortcut: {0}".format(rollkey)
        replaceLabel.align = "c"

        col = (self.fillWithLabel,
               self.blockButton,
               # swapRow,
               replaceLabel,
               # self.replaceBlockButton,
               self.fillButton)

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

            self.replaceBlockButton = BlockButton(tool.editor.level.materials)
            self.replaceBlockButton.blockInfo = tool.replaceBlockInfo
            self.replaceBlockButton.action = self.pickReplaceBlock
            self.replaceLabel.text = "Replace with:"

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

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

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

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

        col = Column(col)

        self.add(col)
        self.shrink_wrap()
Esempio n. 8
0
    def __init__(self,
                 items,
                 keysColumn=None,
                 buttonsColumn=None,
                 item_spacing=None):
        warn(self)
        if keysColumn is None:
            keysColumn = []
        if buttonsColumn is None:
            buttonsColumn = []
        labels = []

        Widget.__init__(self)
        for t in items:
            if len(t) == 3:
                (hotkey, title, action) = t
                tooltipText = None
            else:
                (hotkey, title, action, tooltipText) = t
            if isinstance(title, (str, unicode)):
                button = Button(title, action=action)
            else:
                button = ValueButton(ref=title, action=action, width=200)
            button.anchor = self.anchor

            label = Label(hotkey, width=100, margin=button.margin)
            label.anchor = "wh"

            label.height = button.height

            labels.append(label)

            if tooltipText:
                button.tooltipText = tooltipText

            keysColumn.append(label)
            buttonsColumn.append(button)

        self.buttons = list(buttonsColumn)

        #.#
        if item_spacing == None:
            buttonsColumn = Column(buttonsColumn)
        else:
            buttonsColumn = Column(buttonsColumn, spacing=item_spacing)
        #.#
        buttonsColumn.anchor = self.anchor
        #.#
        if item_spacing == None:
            keysColumn = Column(keysColumn)
        else:
            keysColumn = Column(keysColumn, spacing=item_spacing)

        commandRow = Row((keysColumn, buttonsColumn))
        self.labels = labels
        self.add(commandRow)
        self.shrink_wrap()
Esempio n. 9
0
    def __init__(self, editor, nbtObject=None, fileName=None, savePolicy=0, dataKeyName='Data', close_text="Close",
                 load_text="Open", **kwargs):
        """..."""
        Panel.__init__(self)
        self.editor = editor
        self.nbtObject = nbtObject
        self.fileName = fileName
        self.savePolicy = savePolicy
        self.displayed_item = None
        self.dataKeyName = dataKeyName
        self.copy_data = kwargs.get('copy_data', True)
        self.init_data()
        btns = []
        if load_text:
            btns.append(Button(load_text, action=self.editor.nbtTool.loadFile))
        btns += [
            Button({True: "Save", False: "OK"}[fileName != None], action=kwargs.get('ok_action', self.save_NBT),
                   tooltipText="Save your change in the NBT data."),
            Button("Reset", action=kwargs.get('reset_action', self.reset),
                   tooltipText="Reset ALL your changes in the NBT data."),
        ]
        if close_text:
            btns.append(Button(close_text, action=kwargs.get('close_action', self.close)))

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

        btnRow.shrink_wrap()
        self.btnRow = btnRow

        if kwargs.get('no_header', False):
            self.max_height = max_height = kwargs.get('height', editor.mainViewport.height - editor.toolbar.height -
                                                      editor.subwidgets[0].height) - (
                                               self.margin * 2) - btnRow.height - 2
        else:
            title = _("NBT Explorer")
            if fileName:
                title += " - %s" % os.path.split(fileName)[-1]
            header = Label(title, doNotTranslate=True)
            self.max_height = max_height = kwargs.get('height', editor.mainViewport.height - editor.toolbar.height -
                                                      editor.subwidgets[0].height) - header.height - (
                                               self.margin * 2) - btnRow.height - 2
        self.setCompounds()
        self.tree = NBTTree(height=max_height - btnRow.height - 2, inner_width=250, data=self.data,
                            compound_types=self.compounds,
                            copyBuffer=editor.nbtCopyBuffer, draw_zebra=False, _parent=self, styles=bullet_styles)
        self.tree.update_side_panel = self.update_side_panel
        self.side_panel_width = 350
        row = [self.tree, Column([Label("", width=self.side_panel_width), ], margin=0)]
        self.displayRow = Row(row, height=max_height, margin=0, spacing=0)
        if kwargs.get('no_header', False):
            self.add(Column([self.displayRow, btnRow], margin=0))
        else:
            self.add(Column([header, self.displayRow, btnRow], margin=0))
        self.shrink_wrap()
        self.side_panel = None
        # &# Prototype for Blocks/item names
        mclangres.buildResources(lang=getLang())
Esempio n. 10
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)
Esempio n. 11
0
    def __init__(self, items, keysColumn=None, buttonsColumn=None, item_spacing=None):
        warn(self)
        if keysColumn is None:
            keysColumn = []
        if buttonsColumn is None:
            buttonsColumn = []
        labels = []

        Widget.__init__(self)
        for t in items:
            if len(t) == 3:
                (hotkey, title, action) = t
                tooltipText = None
            else:
                (hotkey, title, action, tooltipText) = t
            if isinstance(title, (str, unicode)):
                button = Button(title, action=action)
            else:
                button = ValueButton(ref=title, action=action, width=200)
            button.anchor = self.anchor

            label = Label(hotkey, width=100, margin=button.margin)
            label.anchor = "wh"

            label.height = button.height

            labels.append(label)

            if tooltipText:
                button.tooltipText = tooltipText

            keysColumn.append(label)
            buttonsColumn.append(button)

        self.buttons = list(buttonsColumn)

        #.#
        if item_spacing == None:
            buttonsColumn = Column(buttonsColumn)
        else:
            buttonsColumn = Column(buttonsColumn, spacing=item_spacing)
        #.#
        buttonsColumn.anchor = self.anchor
        #.#
        if item_spacing == None:
            keysColumn = Column(keysColumn)
        else:
            keysColumn = Column(keysColumn, spacing=item_spacing)

        commandRow = Row((keysColumn, buttonsColumn))
        self.labels = labels
        self.add(commandRow)
        self.shrink_wrap()
Esempio n. 12
0
    def __init__(self, inventory, data, *args, **kwargs):
        Dialog.__init__(self, *args, **kwargs)
        self.inventory = inventory
        slot, id, count, damage = data
        self.former_id_text = id
        self.slot = slot
        self.id = TextFieldWrapped(text=str(id),
                                   doNotTranslate=True,
                                   width=300)
        self.id.change_action = self.text_entered
        self.id.escape_action = self.cancel
        self.id.enter_action = self.ok
        self.count = IntField(text="%s" % count, min=0, max=64)
        self.damage = IntField(text="%s" % damage, min=0, max=os.sys.maxint)
        header = Label(_("Inventory Slot #%s") % slot, doNotTranslate=True)
        row = Row([
            Label("id"),
            self.id,
            Label("Count"),
            self.count,
            Label("Damage"),
            self.damage,
        ])

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

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

        try:
            self.tableview.rows.scroll_to_item(self.selected_item_index)
        except Exception, e:
            print e
            pass
Esempio n. 13
0
    def __init__(self, tool):
        Panel.__init__(self)
        self.tool = tool
        self.player_UUID = {}
        self.level = tool.editor.level
        if hasattr(self.level, 'players'):
            players = self.level.players or ["[No players]"]
            if not self.level.oldPlayerFolderFormat:
                for player in players:
                    if player != "Player":
                        self.player_UUID[
                            version_compatability_utils.getPlayerNameFromUUID(
                                player)] = player
                self.player_UUID["Player"] = "Player"
                players = self.player_UUID.keys()

        else:
            players = ["Player"]
        self.players = players
        tableview = TableView(columns=[
            TableColumn("Player Name", 200),
        ])
        tableview.index = 0
        tableview.num_rows = lambda: len(players)
        tableview.row_data = lambda i: (players[i], )
        tableview.row_is_selected = lambda x: x == tableview.index
        tableview.zebra_color = (0, 0, 0, 48)

        def selectTableRow(i, evt):
            tableview.index = i

        tableview.click_row = selectTableRow
        self.table = tableview
        l = Label("Player: ")
        col = [l, tableview]

        gotoButton = Button("Goto Player", action=self.tool.gotoPlayer)
        gotoCameraButton = Button("Goto Player's View",
                                  action=self.tool.gotoPlayerCamera)
        moveButton = Button("Move Player", action=self.tool.movePlayer)
        moveToCameraButton = Button("Align Player to Camera",
                                    action=self.tool.movePlayerToCamera)
        col.extend(
            [gotoButton, gotoCameraButton, moveButton, moveToCameraButton])

        col = Column(col)
        self.add(col)
        self.shrink_wrap()
Esempio n. 14
0
 def updateFilters(self):
     totalFilters = 0
     updatedFilters = 0
     try:
         os.mkdir(mcplatform.filtersDir + "/updates")
     except OSError:
         pass
     for module in self.filterModules.values():
         totalFilters = totalFilters + 1
         if hasattr(module, "UPDATE_URL") and hasattr(module, "VERSION"):
             if isinstance(module.UPDATE_URL, (str, unicode)) and isinstance(module.VERSION, (str, unicode)):
                 versionJSON = json.loads(urllib2.urlopen(module.UPDATE_URL).read())
                 if module.VERSION != versionJSON["Version"]:
                     urllib.urlretrieve(versionJSON["Download-URL"],
                                        mcplatform.filtersDir + "/updates/" + versionJSON["Name"])
                     updatedFilters = updatedFilters + 1
     for f in os.listdir(mcplatform.filtersDir + "/updates"):
         shutil.copy(mcplatform.filtersDir + "/updates/" + f, mcplatform.filtersDir)
     shutil.rmtree(mcplatform.filtersDir + "/updates/")
     self.finishedUpdatingWidget = Widget()
     lbl = Label("Updated " + str(updatedFilters) + " filter(s) out of " + str(totalFilters))
     closeBTN = Button("Close this message", action=self.closeFinishedUpdatingWidget)
     col = Column((lbl, closeBTN))
     self.finishedUpdatingWidget.bg_color = (0.0, 0.0, 0.6)
     self.finishedUpdatingWidget.add(col)
     self.finishedUpdatingWidget.shrink_wrap()
     self.finishedUpdatingWidget.present()
Esempio n. 15
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()
Esempio n. 16
0
    def __init__(self, tool):
        ToolOptions.__init__(self, name='Panel.BrushToolOptions')
        alphaField = FloatField(ref=ItemRef(tool.settings, 'brushAlpha'),
                                min=0.0,
                                max=1.0,
                                width=60)
        alphaField.increment = 0.1
        alphaRow = Row((Label("Alpha: "), alphaField))
        autoChooseCheckBox = CheckBoxLabel(
            "Choose Block Immediately",
            ref=ItemRef(tool.settings, "chooseBlockImmediately"),
            tooltipText=
            "When the brush tool is chosen, prompt for a block type.")

        updateOffsetCheckBox = CheckBoxLabel(
            "Reset Distance When Brush Size Changes",
            ref=ItemRef(tool.settings, "updateBrushOffset"),
            tooltipText=
            "Whenever the brush size changes, reset the distance to the brush blocks."
        )

        col = Column((Label("Brush Options"), alphaRow, autoChooseCheckBox,
                      updateOffsetCheckBox, Button("OK", action=self.dismiss)))
        self.add(col)
        self.shrink_wrap()
        return
Esempio n. 17
0
 def updateFilters(self):
     totalFilters = 0
     updatedFilters = 0
     filtersDir = directories.getFiltersDir()
     try:
         os.mkdir(os.path.join(filtersDir, "updates"))
     except OSError:
         pass
     for module in self.filterModules.values():
         totalFilters += 1
         if hasattr(module, "UPDATE_URL") and hasattr(module, "VERSION"):
             if isinstance(module.UPDATE_URL,
                           (str, unicode)) and isinstance(
                               module.VERSION, (str, unicode)):
                 versionJSON = json.loads(
                     urllib2.urlopen(module.UPDATE_URL).read())
                 if module.VERSION != versionJSON["Version"]:
                     urllib.urlretrieve(
                         versionJSON["Download-URL"],
                         os.path.join(filtersDir, "updates",
                                      versionJSON["Name"]))
                     updatedFilters += 1
     for f in os.listdir(os.path.join(filtersDir, "updates")):
         shutil.copy(os.path.join(filtersDir, "updates", f), filtersDir)
     shutil.rmtree(os.path.join(filtersDir, "updates"))
     finishedUpdatingWidget = Widget()
     lbl = Label("Updated %s filter(s) out of %s" %
                 (updatedFilters, totalFilters))
     closeBTN = Button("Close this message",
                       action=finishedUpdatingWidget.dismiss)
     col = Column((lbl, closeBTN))
     finishedUpdatingWidget.bg_color = (0.0, 0.0, 0.6)
     finishedUpdatingWidget.add(col)
     finishedUpdatingWidget.shrink_wrap()
     finishedUpdatingWidget.present()
Esempio n. 18
0
 def createField(self, key, value):
     """
     Creates a field matching the input type.
     :param key, key to store the value in, also the name of the label if type is float or int.
     :param value, default value for the field.
     """
     doNotTranslate = bool(hasattr(self.tool.brushMode, "trn"))
     check_value = value
     mi = 0
     ma = 100
     if key in ('W', 'H', 'L'):
         reference = AttrRef(self.tool, key)
     else:
         reference = ItemRef(self.tool.options, key)
     if isinstance(check_value, tuple):
         check_value = value[0]
         mi = value[1]
         ma = value[2]
     if isinstance(check_value, Block):
         if key not in self.tool.recentBlocks:
             self.tool.recentBlocks[key] = []
         wcb = getattr(self.tool.brushMode, 'wildcardBlocks', [])
         aw = False
         if key in wcb:
             aw = True
         field = BlockButton(self.tool.editor.level.materials,
                             ref=reference,
                             recentBlocks=self.tool.recentBlocks[key],
                             allowWildcards=aw)
     elif isinstance(check_value, types.MethodType):
         field = Button(key, action=value)
     else:
         if doNotTranslate:
             key = self.tool.brushMode.trn._(key)
             value = self.tool.brushMode.trn._(value)
         if isinstance(check_value, int):
             field = IntInputRow(key,
                                 ref=reference,
                                 width=50,
                                 min=mi,
                                 max=ma,
                                 doNotTranslate=doNotTranslate)
         elif isinstance(check_value, float):
             field = FloatInputRow(key,
                                   ref=reference,
                                   width=50,
                                   min=mi,
                                   max=ma,
                                   doNotTranslate=doNotTranslate)
         elif isinstance(check_value, bool):
             field = CheckBoxLabel(key,
                                   ref=reference,
                                   doNotTranslate=doNotTranslate)
         elif isinstance(check_value, str):
             field = Label(value, doNotTranslate=doNotTranslate)
         else:
             print(type(check_value))
             field = None
     return field
Esempio n. 19
0
 def __init__(self, file_types=None, operation=0, **kwds):
     Widget.__init__(self, **kwds)
     if file_types is None:
         self.file_types = ["*.*",]
     else:
         self.file_types = file_types
     self.file_path = None
     self._button = None
         
     if operation == self.OPEN_FILE:
         self._button = Button("Choose a file", action=self._open_file)
     elif operation == self.SAVE_FILE:
         self._button = Button("Save a file", action=self._save_file)
         
     self.add(self._button)
     
     self.shrink_wrap()
Esempio n. 20
0
 def __init__(self, inventory, data):
     Panel.__init__(self)
     self.inventory = inventory
     slot, id, count, damage = data
     self.slot = slot
     self.id = TextFieldWrapped(text=id, doNotTranslate=True, width=300)
     self.count = IntField(text="%s"%count, min=-64, max=64)
     self.damage = IntField(text="%s"%damage, min=-32768, max=32767)
     header = Label(_("Inventory Slot #%s")%slot, doNotTranslate=True)
     row = Row([Label("id"), self.id,
                Label("Count"), self.count,
                Label("Damage"), self.damage,
                ])
     buttons = Row([Button("Save", action=self.dismiss), Button("Cancel", action=self.cancel)])
     col = Column([header, row, buttons], spacing=2)
     self.add(col)
     self.shrink_wrap()
Esempio n. 21
0
    def stop_record_macro(self):
        macro_dialog = Dialog()
        macroNameLabel = Label("Macro Name: ")
        macroNameField = TextFieldWrapped(width=200)

        def save_macro():
            macro_name = "{Macro} " + macroNameField.get_text()

            self.filter_json["Macros"][macro_name] = {}
            self.filter_json["Macros"][macro_name]["Number of steps"] = len(
                self.macro_steps)
            self.filterSelect.choices.append(macro_name)
            for entry in self.macro_steps:
                for inp in entry["Inputs"].keys():
                    if not isinstance(entry["Inputs"][inp],
                                      pymclevel.materials.Block):
                        if not entry["Inputs"][inp] == "blocktype":
                            continue
                    _inp = entry["Inputs"][inp]
                    entry["Inputs"][inp] = "block-{0}:{1}".format(
                        _inp.ID, _inp.blockData)
                self.filter_json["Macros"][macro_name][entry["Step"]] = {
                    "Name": entry["Name"],
                    "Inputs": entry["Inputs"]
                }
            stop_dialog()
            self.filterSelect.selectedChoice = macro_name
            self.filterChanged()

        def stop_dialog():
            self.macro_button.text = "Record Macro"
            self.macro_button.tooltipText = None
            self.macro_button.action = self.start_record_macro
            macro_dialog.dismiss()
            self.macro_steps = []
            self.current_step = 0
            self._recording = False

        input_row = Row((macroNameLabel, macroNameField))
        saveButton = Button("Save", action=save_macro)
        closeButton = Button("Cancel", action=stop_dialog)
        button_row = Row((saveButton, closeButton))
        macro_dialog.add(Column((input_row, button_row)))
        macro_dialog.shrink_wrap()
        macro_dialog.present()
Esempio n. 22
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]
Esempio n. 23
0
    def showPanel(self):
        self.panel = Panel(name='Panel.PlayerSpawnPositionTool')
        button = Button("Goto Spawn", action=self.gotoSpawn)
        self.panel.add(button)
        self.panel.shrink_wrap()

        self.panel.left = self.editor.left
        self.panel.centery = self.editor.centery
        self.editor.add(self.panel)
Esempio n. 24
0
    def showPanel(self):
        self.panel = Panel()
        button = Button("Goto Spawn", action=self.gotoSpawn)
        self.panel.add(button)
        self.panel.shrink_wrap()

        self.panel.left = self.editor.left
        self.panel.centery = self.editor.centery
        self.editor.add(self.panel)
Esempio n. 25
0
    def __init__(self, tool):
        Panel.__init__(self)
        self.tool = tool
        self.autoChooseCheckBox = CheckBoxLabel("Choose Block Immediately",
                                                ref=config.fill.chooseBlockImmediately,
                                                tooltipText="When the fill tool is chosen, prompt for a block type.")

        col = Column((Label("Fill Options"), self.autoChooseCheckBox, Button("OK", action=self.dismiss)))

        self.add(col)
        self.shrink_wrap()
Esempio n. 26
0
    def __init__(self, editor):
        EditorTool.__init__(self, editor)

        self.filterModules = {}
        self.savedOptions = {}

        self.updatePanel = Panel()
        updateButton = Button("Update Filters", action=self.updateFilters)
        self.updatePanel.add(updateButton)
        self.updatePanel.shrink_wrap()

        self.updatePanel.bottomleft = self.editor.viewportContainer.bottomleft
Esempio n. 27
0
    def __init__(self, tool):
        Panel.__init__(self)
        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", "")
Esempio n. 28
0
 def __init__(self, tool):
     ToolOptions.__init__(self, name='Panel.FilterToolOptions')
     self.tool = tool
     
     self.notifications_disabled = False
     
     disable_error_popup = CheckBoxLabel("Disable Error Notification",
                                         ref=AttrRef(self, 'notifications_disabled'))
     ok_button = Button("Ok", action=self.dismiss)
     
     col = Column((disable_error_popup, ok_button,), spacing=2)
     self.add(col)
     self.shrink_wrap()
Esempio n. 29
0
    def __init__(self, tool):
        Panel.__init__(self)
        self.tool = tool
        level = tool.editor.level
        if hasattr(level, 'players'):
            players = level.players or ["[No players]"]
        else:
            players = ["Player"]
        self.players = players
        tableview = TableView(columns=[
            TableColumn("Player Name", 200),
        ])
        tableview.index = 0
        tableview.num_rows = lambda: len(players)
        tableview.row_data = lambda i: (players[i], )
        tableview.row_is_selected = lambda x: x == tableview.index
        tableview.zebra_color = (0, 0, 0, 48)

        def selectTableRow(i, evt):
            tableview.index = i

        tableview.click_row = selectTableRow
        self.table = tableview
        l = Label("Player: ")
        col = [l, tableview]

        gotoButton = Button("Goto Player", action=self.tool.gotoPlayer)
        gotoCameraButton = Button("Goto Player's View",
                                  action=self.tool.gotoPlayerCamera)
        moveButton = Button("Move Player", action=self.tool.movePlayer)
        moveToCameraButton = Button("Align Player to Camera",
                                    action=self.tool.movePlayerToCamera)
        col.extend(
            [gotoButton, gotoCameraButton, moveButton, moveToCameraButton])

        col = Column(col)
        self.add(col)
        self.shrink_wrap()
Esempio n. 30
0
    def __init__(self, tool):
        Panel.__init__(self, name='Panel.BrushPanel')
        self.tool = tool
        """
        presets, modeRow and styleRow are always created, no matter
        what brush is selected. styleRow can be disabled by putting disableStyleButton = True
        in the brush file.
        """
        presets = self.createPresetRow()

        self.brushModeButtonLabel = Label("Mode:")
        self.brushModeButton = ChoiceButton(
            sorted([mode for mode in tool.brushModes]),
            width=150,
            choose=self.brushModeChanged,
            doNotTranslate=True,
        )
        modeRow = Row([self.brushModeButtonLabel, self.brushModeButton])

        self.brushStyleButtonLabel = Label("Style:")
        self.brushStyleButton = ValueButton(ref=ItemRef(
            self.tool.options, "Style"),
                                            action=self.tool.swapBrushStyles,
                                            width=150)

        styleRow = Row([self.brushStyleButtonLabel, self.brushStyleButton])
        self.brushModeButton.selectedChoice = self.tool.selectedBrushMode
        optionsColumn = []
        optionsColumn.extend([presets, modeRow])
        if not getattr(tool.brushMode, 'disableStyleButton', False):
            optionsColumn.append(styleRow)
        """
        We're going over all options in the selected brush module, and making
        a field for all of them.
        """
        for r in tool.brushMode.inputs:
            row = []
            for key, value in r.items():
                field = self.createField(key, value)
                row.append(field)
            row = Row(row)
            optionsColumn.append(row)
        if getattr(tool.brushMode, 'addPasteButton', False):
            importButton = Button("Import", action=tool.importPaste)
            importRow = Row([importButton])
            optionsColumn.append(importRow)
        optionsColumn = Column(optionsColumn, spacing=0)
        self.add(optionsColumn)
        self.shrink_wrap()
Esempio n. 31
0
    def __init__(self, tool):
        Panel.__init__(self)
        self.tool = tool
        self.spawnProtectionCheckBox = CheckBox(ref=AttrRef(tool, "spawnProtection"))
        self.spawnProtectionLabel = Label("Spawn Position Safety")
        self.spawnProtectionLabel.mouse_down = self.spawnProtectionCheckBox.mouse_down

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

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

        self.add(col)
        self.shrink_wrap()
Esempio n. 32
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

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

        self.add(col)
        self.shrink_wrap()
Esempio n. 33
0
    def __init__(self, tool):
        ToolOptions.__init__(self, name='Panel.FillToolOptions')
        self.tool = tool
        self.autoChooseCheckBoxFill = CheckBoxLabel(
            "Open Block Picker for Fill",
            ref=config.fill.chooseBlockImmediately,
            tooltipText="When the fill tool is chosen, prompt for a block type."
        )
        self.autoChooseCheckBoxReplace = CheckBoxLabel(
            "Open Block Picker for Replace",
            ref=config.fill.chooseBlockImmediatelyReplace,
            tooltipText=
            "When the replace tool is chosen, prompt for a block type.")
        col = Column(
            (Label("Fill and Replace Options"), self.autoChooseCheckBoxFill,
             self.autoChooseCheckBoxReplace, Button("OK",
                                                    action=self.dismiss)))

        self.add(col)
        self.shrink_wrap()
Esempio n. 34
0
    def showPanel(self):
        if self.panel.parent:
            self.editor.remove(self.panel)

        self.reloadFilters()

        # self.panel = FilterToolPanel(self)
        self.panel.reload()

        self.panel.midleft = self.editor.midleft

        self.editor.add(self.panel)

        self.updatePanel = Panel()
        updateButton = Button("Update Filters", action=self.updateFilters)
        self.updatePanel.add(updateButton)
        self.updatePanel.shrink_wrap()

        self.updatePanel.bottomleft = self.editor.viewportContainer.bottomleft
        self.editor.add(self.updatePanel)
 def __init__(self, title, choices, **kw):
     Button.__init__(self, title, **kw)
     self.choices = choices
     self.menu = Menu(title, ((c, c) for c in choices))
Esempio n. 36
0
class FilterToolPanel(Panel):

    BACKUP_FILTER_JSON = False
    """If set to true, the filter.json is backed up to the hard disk
    every time it's edited. The default is false, which makes the file save
    only whenever the tool gets closed. If MCEdit were to crash, any recorded
    macros would not be saved."""

    def __init__(self, tool):
        Panel.__init__(self)
        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", "")

    @property
    def filter_json(self):
        if self._filter_json is not None:
            return self._filter_json
        if FilterToolPanel.BACKUP_FILTER_JSON:
            self._filter_json = JsonDictProperty(os.path.join(directories.getDataDir(), "filters.json"))
        else:
            try:
                self._filter_json = json.load(open(os.path.join(directories.getDataDir(), "filters.json"), 'rb'))
            except (ValueError, IOError) as e:
                log.error("Error while loading filters.json", e)
                self._filter_json = {"Macros": {}}
        return self._filter_json

    def close(self):
        self._saveOptions()
        self.filter_json["Last Filter Opened"] = self.selectedName
        if not FilterToolPanel.BACKUP_FILTER_JSON:
            with open(os.path.join(directories.getDataDir(), "filters.json"), 'w') as f:
                json.dump(self.filter_json, f)

    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]

    @property
    def macroSelected(self):
        return self.filterSelect.selectedChoice not in self.tool.filterNames

    def filterChanged(self):
        # if self.filterSelect.selectedChoice not in self.tool.filterModules:
        #     return
        self._saveOptions()
        self.selectedName = self.filterSelect.selectedChoice
        if self.macroSelected:  # Is macro
            self.macro_button.set_text("Delete Macro")
            self.macro_button.action = self.delete_macro
        elif not self._recording:
            self.macro_button.set_text("Record Macro")
            self.macro_button.action = self.start_record_macro
        self.reload()

    def delete_macro(self):
        macro_name = self.selectedName
        if macro_name in self.filter_json["Macros"]:
            del self.filter_json["Macros"][macro_name]
        if len(self.filterSelect.choices) == 1:  # Just this macro available
            self.reload()
            return
        choices = self.filterSelect.choices
        self.filterSelect.selectedChoice = choices[0] if choices[0] != macro_name else choices[1]
        self.filterChanged()

    def stop_record_macro(self):
        macro_dialog = Dialog()
        macroNameLabel = Label("Macro Name: ")
        macroNameField = TextFieldWrapped(width=200)

        def save_macro():
            macro_name = "{Macro} " + macroNameField.get_text()

            self.filter_json["Macros"][macro_name] = {}
            self.filter_json["Macros"][macro_name]["Number of steps"] = len(self.macro_steps)
            self.filterSelect.choices.append(macro_name)
            for entry in self.macro_steps:
                for inp in entry["Inputs"].keys():
                    if not isinstance(entry["Inputs"][inp], pymclevel.materials.Block):
                        if not entry["Inputs"][inp] == "blocktype":
                            continue
                    _inp = entry["Inputs"][inp]
                    entry["Inputs"][inp] = "block-{0}:{1}".format(_inp.ID, _inp.blockData)
                self.filter_json["Macros"][macro_name][entry["Step"]] = {"Name": entry["Name"],
                                                                         "Inputs": entry["Inputs"]}
            stop_dialog()
            self.filterSelect.selectedChoice = macro_name
            self.filterChanged()

        def stop_dialog():
            self.macro_button.text = "Record Macro"
            self.macro_button.tooltipText = None
            self.macro_button.action = self.start_record_macro
            macro_dialog.dismiss()
            self.macro_steps = []
            self.current_step = 0
            self._recording = False

        input_row = Row((macroNameLabel, macroNameField))
        saveButton = Button("Save", action=save_macro)
        closeButton = Button("Cancel", action=stop_dialog)
        button_row = Row((saveButton, closeButton))
        macro_dialog.add(Column((input_row, button_row)))
        macro_dialog.shrink_wrap()
        macro_dialog.present()

    def start_record_macro(self):
        self.macro_button.text = "Stop recording"
        self.macro_button.tooltipText = "Currently recording a macro"
        self.macro_button.action = self.stop_record_macro
        self.confirmButton.text = "Add macro"
        self.confirmButton.width += 75
        self.confirmButton.centerx = self.centerx
        self._recording = True

    def _addMacroStep(self, name=None, inputs=None):
        data = {"Name": name, "Step": self.current_step, "Inputs": inputs}
        self.current_step += 1
        self.macro_steps.append(data)

    def unbind_key(self):
        config.config.remove_option("Filter Keys", self.selectedName)
        self.binding_button.text = "*"
        self.keys_panel.dismiss()
        # self.saveOptions()
        self.reload()

    def bind_key(self, message=None):
        panel = Panel()
        panel.bg_color = (0.5, 0.5, 0.6, 1.0)
        if not message:
            message = _("Press a key to assign to the filter \"{0}\"\n\n"
                        "Press ESC to cancel.").format(self.selectedName)
        label = albow.Label(message)
        unbind_button = Button("Press to unbind", action=self.unbind_key)
        column = Column((label, unbind_button))
        panel.add(column)
        panel.shrink_wrap()

        def panelKeyUp(evt):
            _key_name = self.root.getKey(evt)
            panel.dismiss(_key_name)

        def panelMouseUp(evt):
            button = keys.remapMouseButton(evt.button)
            _key_name = None
            if button == 3:
                _key_name = "Button 3"
            elif button == 4:
                _key_name = "Scroll Up"
            elif button == 5:
                _key_name = "Scroll Down"
            elif button == 6:
                _key_name = "Button 4"
            elif button == 7:
                _key_name = "Button 5"
            if 2 < button < 8:
                panel.dismiss(_key_name)

        panel.key_up = panelKeyUp
        panel.mouse_up = panelMouseUp

        self.keys_panel = panel
        key_name = panel.present()

        if type(key_name) is bool:
            return True
        if key_name != "Escape":
            if key_name in ["Alt-F4", "F1", "F2", "F3", "F4", "F5", "1", "2", "3",
                            "4", "5", "6", "7", "8", "9", "Ctrl-Alt-F9", "Ctrl-Alt-F10"]:
                self.bind_key(_("You can't use the key {0}.\n"
                                "Press a key to assign to the filter \"{1}\"\n\n"
                                ""
                                "Press ESC to cancel.").format(_(key_name), self.selectedName))
                return True

            keysUsed = [(j, i) for (j, i) in config.config.items("Keys") if i == key_name]
            if keysUsed:
                self.bind_key(_("Can't bind. {0} is already used by {1}.\n"
                                "Press a key to assign to the filter \"{2}\"\n\n"
                                ""
                                "Press ESC to cancel.").format(_(key_name), keysUsed[0][0], self.selectedName))
                return True

            filter_keys = [i for (i, j) in config.config.items("Filter Keys") if j == key_name]
            if filter_keys:
                self.bind_key(_("Can't bind. {0} is already used by the \"{1}\" filter.\n"
                                "Press a new key.\n\n"
                                ""
                                "Press ESC to cancel.").format(_(key_name), filter_keys[0]))
                return True
            config.config.set("Filter Keys", self.selectedName.lower(), key_name)
        config.save()
        self.reload()

    def _saveOptions(self):
        """Should never be called. Call filterchanged() or close() instead,
        which will then call this.
        :return:
        """
        if self.filterOptionsPanel is not None:
            options = {}
            options.update(self.filterOptionsPanel.options)
            options.pop("", "")
            self.tool.savedOptions[self.selectedName] = options

    @alertFilterException
    def confirm(self):
        if self._recording:
            self._addMacroStep(self.selectedName, self.filterOptionsPanel.options)
        else:
            self.filterOptionsPanel.confirm(self.tool)
Esempio n. 37
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 range(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
Esempio n. 38
0
    def __init__(self, tool, *a, **kw):
        if 'name' not in kw.keys():
            kw['name'] = 'Panel.ChunkToolPanel'
        Panel.__init__(self, *a, **kw)

        self.tool = tool

        self.anchor = "whl"

        chunkToolLabel = Label("Selected Chunks:")

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

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

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

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

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

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

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

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

        col = Column((
        chunkToolLabel, self.chunksLabel, deselectButton, createButton, destroyButton, pruneButton, relightButton,
        repopButton, dontRepopButton))
        # col.right = self.width - 10;
        self.width = col.width
        self.height = col.height
        #self.width = 120
        self.add(col)