Example #1
0
 def build_field(itm):
     fields = []
     if type(itm) in field_types.keys():
         f, bounds = field_types[type(itm)]
         if bounds:
             fields = [f(ref=AttrRef(itm, 'value'), min=bounds[0], max=bounds[1]),]
         else:
             fields = [f(ref=AttrRef(itm, 'value')),]
     elif type(itm) in array_types.keys():
         idx = 0
         for _itm in itm.value.tolist():
             f, bounds = array_types[type(itm)]
             fields.append(f(ref=ItemRef(itm.value, idx)))
             idx += 1
     elif type(itm) in (TAG_Compound, TAG_List):
         for _itm in itm.value:
             fields.append(Label("%s"%(_itm.name or "%s #%03d"%(itm.name or _("Item"), itm.value.index(_itm))), align='l', doNotTranslate=True))
             fields += NBTExplorerToolPanel.build_field(_itm)
     elif type(itm) not in (str, unicode):
         if type(getattr(itm, 'value', itm)) not in (str, unicode, int, float):
             fld = Label
             kw = {'align': 'l'}
         else:
             fld = TextFieldWrapped
             kw = {}
         fields = [fld("%s"%getattr(itm, 'value', itm), doNotTranslate=True, **kw),]
     else:
         fields = [TextFieldWrapped("%s"%itm, doNotTranslata=True),]
     return fields
 def __init__(self, inventory, data):
     Panel.__init__(self)
     self.inventory = inventory
     slot, id, count, damage = data
     self.former_id_text = id
     self.slot = slot
     self.id = TextFieldWrapped(text=id, doNotTranslate=True, width=300)
     #&# Prototype for blocks/items names
     self.menu = None
     m = Menu("", [""])
     h = m.font.get_linesize()
     self.menu = Menu("", [""], scrolling=True, scroll_items=(self.root.local_to_global(self.root.bottomleft)[1] - self.root.local_to_global(self.bottomleft)[1] - (m.margin * 2)) / h)
     del m
     self.id.change_action = self.text_entered
     self.id.escape_action = self.close_menu
     self.menu.key_down = self.id.key_down
     #&#
     self.count = IntField(text="%s"%count, min=-64, max=64)
     self.damage = IntField(text="%s"%damage, min=-32768, max=32767)
     header = Label(_("Inventory Slot #%s")%slot, doNotTranslate=True)
     row = Row([Label("id"), self.id,
                Label("Count"), self.count,
                Label("Damage"), self.damage,
                ])
     buttons = Row([Button("Save", action=self.dismiss), Button("Cancel", action=self.cancel)])
     col = Column([header, row, buttons], spacing=2)
     self.add(col)
     self.shrink_wrap()
Example #3
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()
Example #4
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 #5
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
Example #6
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()
Example #7
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()
 def mouse_down(e):
     if self.bulletFilePath.subwidgets[1].enabled:
         TextFieldWrapped.mouse_down(self.bulletFilePath.subwidgets[1], e)
Example #9
0
 def mouse_down(e):
     if self.bulletFilePath.subwidgets[1].enabled:
         TextFieldWrapped.mouse_down(self.bulletFilePath.subwidgets[1], e)
Example #10
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 #11
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 #12
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
Example #13
0
def TextInputRow(title, *args, **kw):
    warn(TextInputRow)
    return Row((Label(title, tooltipText=kw.get('tooltipText')),
                TextFieldWrapped(*args, **kw)))
Example #14
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
                        lin = 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 lin is None:
                            lin = 1
                        if val is None:
                            val = "Input String Here"
                        if wid is None:
                            wid = 200

                        field = TextFieldWrapped(value=val,
                                                 width=wid,
                                                 lines=lin)
                        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":
                field = TextFieldWrapped(value="Input String Here",
                                         width=200,
                                         lines=1)
                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)
class SlotEditor(Panel):
    def __init__(self, inventory, data):
        Panel.__init__(self)
        self.inventory = inventory
        slot, id, count, damage = data
        self.former_id_text = id
        self.slot = slot
        self.id = TextFieldWrapped(text=id, doNotTranslate=True, width=300)
        #&# Prototype for blocks/items names
        self.menu = None
        m = Menu("", [""])
        h = m.font.get_linesize()
        self.menu = Menu("", [""], scrolling=True, scroll_items=(self.root.local_to_global(self.root.bottomleft)[1] - self.root.local_to_global(self.bottomleft)[1] - (m.margin * 2)) / h)
        del m
        self.id.change_action = self.text_entered
        self.id.escape_action = self.close_menu
        self.menu.key_down = self.id.key_down
        #&#
        self.count = IntField(text="%s"%count, min=-64, max=64)
        self.damage = IntField(text="%s"%damage, min=-32768, max=32767)
        header = Label(_("Inventory Slot #%s")%slot, doNotTranslate=True)
        row = Row([Label("id"), self.id,
                   Label("Count"), self.count,
                   Label("Damage"), self.damage,
                   ])
        buttons = Row([Button("Save", action=self.dismiss), Button("Cancel", action=self.cancel)])
        col = Column([header, row, buttons], spacing=2)
        self.add(col)
        self.shrink_wrap()

    def cancel(self, *args, **kwargs):
        kwargs['save'] = False
        self.dismiss(*args, **kwargs)

    def dismiss(self, *args, **kwargs):
        if kwargs.pop('save', True):
            data = [self.slot, self.id.text, self.count.text, self.damage.text]
            self.inventory.change_value(data)
        Panel.dismiss(self, *args, **kwargs)

    #&# Prototype for blocks/items names
    def text_entered(self):
        text = self.id.get_text()
        if self.former_id_text == text:
            return
        results = []
        for k in map_items.keys():
            k = mclangres.translate(k)
            if text.lower() in k.lower():
                results.append(k)
        results.sort()
        self.menu.set_items([[a] for a in results])
        self.menu.scrolling = True
        self.menu.set_scroll_items((self.root.local_to_global(self.parent.bottomleft)[1] - self.root.local_to_global(self.bottomleft)[1] - (self.menu.margin * 2)) / self.menu.font.get_linesize())
        sel = self.menu.present(self.id, (0, self.id.bottom - self.margin))
        if sel >= 0:
            self.former_id_text = self.menu.items[sel][0]
            self.id.change_text(self.menu.items[sel][0])
            self.former_id_text = self.menu.items[sel][0]

    def close_menu(self):
        if self.menu:
            self.menu.dismiss(-1)