Exemplo n.º 1
0
    def __init__(self, mcedit):
        Dialog.__init__(self)

        self.mcedit = mcedit

        self.langs = {}
        self.sgnal = {}
        self.portableVar = albow.AttrRef(self, 'portableLabelText')
        self.saveOldPortable = self.portableVar.get()

        self.saveOldConfig = {
            config.controls.autobrake:                 config.controls.autobrake.get(),
            config.controls.swapAxes:                  config.controls.swapAxes.get(),
            config.controls.cameraAccel:               config.controls.cameraAccel.get(),
            config.controls.cameraDrag:                config.controls.cameraDrag.get(),
            config.controls.cameraMaxSpeed:            config.controls.cameraMaxSpeed.get(),
            config.controls.cameraBrakingSpeed:        config.controls.cameraBrakingSpeed.get(),
            config.controls.mouseSpeed:                config.controls.mouseSpeed.get(),
            config.settings.undoLimit:                 config.settings.undoLimit.get(),
            config.settings.maxCopies:                 config.settings.maxCopies.get(),
            config.controls.invertMousePitch:          config.controls.invertMousePitch.get(),
            config.settings.spaceHeight:               config.settings.spaceHeight.get(),
            albow.AttrRef(self, 'blockBuffer'):        albow.AttrRef(self, 'blockBuffer').get(),
            config.settings.setWindowPlacement:        config.settings.setWindowPlacement.get(),
            config.settings.rotateBlockBrush:          config.settings.rotateBlockBrush.get(),
            config.settings.shouldResizeAlert:         config.settings.shouldResizeAlert.get(),
            config.settings.superSecretSettings:       config.settings.superSecretSettings.get(),
            config.settings.longDistanceMode:          config.settings.longDistanceMode.get(),
            config.settings.flyMode:                   config.settings.flyMode.get(),
            config.settings.langCode:                  config.settings.langCode.get(),
            config.settings.compassToggle:             config.settings.compassToggle.get(),
            config.settings.compassSize:               config.settings.compassSize.get(),
            config.settings.fontProportion:            config.settings.fontProportion.get(),
        }
Exemplo n.º 2
0
    def dismiss(self, *args, **kwargs):
        """Used to change the language and the font proportion"""
        lang = config.settings.langCode.get() == old_lang or config.settings.langCode.get() == self.saveOldConfig[config.settings.langCode]
        font = config.settings.fontProportion.get() == old_fprop or config.settings.fontProportion.get() == self.saveOldConfig[config.settings.fontProportion]
        #-# The following lines will be used for the language and font dynamic changes
        #-# The restart boxes will be suppressed.
#        lang = config.settings.langCode.get() == self.saveOldConfig[config.settings.langCode]
#        font = config.settings.fontProportion.get() == self.saveOldConfig[config.settings.fontProportion]
#        self.changeLanguage()

#        if not font or not lang:
#            editor = self.mcedit.editor
#            if editor and editor.unsavedEdits:
#                result = albow.ask("You must restart MCEdit to see language changes", ["Save and Restart", "Restart", "Later"])
#            else:
#                result = albow.ask("You must restart MCEdit to see language changes", ["Restart", "Later"])
#            if result == "Save and Restart":
#                editor.saveFile()
#                self.mcedit.restart()
#            elif result == "Restart":
#                self.mcedit.restart()
#            elif result == "Later":
#                pass

        self.reshowNumberFields()
        for key in self.saveOldConfig.keys():
            self.saveOldConfig[key] = key.get()

        config.save()
        Dialog.dismiss(self, *args, **kwargs)
Exemplo n.º 3
0
    def cancel(self, *args, **kwargs):
        Changes = False
        for key in self.saveOldConfig.keys():
            if key.get() != self.saveOldConfig[key]:
                Changes = True
        oldLanguage = self.saveOldConfig[config.settings.langCode]
        if config.settings.langCode.get() != oldLanguage:
            Changes = True
        newPortable = _(self.portableVar.get())
        if newPortable != _(self.saveOldPortable):
            Changes = True
        if not Changes:
            Dialog.dismiss(self, *args, **kwargs)
            return

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

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

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

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

        config.save()
        Dialog.dismiss(self, *args, **kwargs)
Exemplo n.º 4
0
    def dismiss(self, *args, **kwargs):
        for key in self.saveOldConfig.keys():
            self.saveOldConfig[key] = key.get()
        self.saveOldResourcePack = self.resourcePackButton.selectedChoice

        config.save()
        Dialog.dismiss(self, *args, **kwargs)
Exemplo n.º 5
0
    def __init__(self, mcedit):
        Dialog.__init__(self)

        self.mcedit = mcedit

        self.langs = {}
        self.sgnal = {}
Exemplo n.º 6
0
    def dismiss(self, *args, **kwargs):
        """Used to change the language and the font proportion"""
        lang = config.settings.langCode.get() == old_lang or config.settings.langCode.get() == self.saveOldConfig[config.settings.langCode]
        font = config.settings.fontProportion.get() == old_fprop or config.settings.fontProportion.get() == self.saveOldConfig[config.settings.fontProportion]
        #-# The following lines will be used for the language and font dynamic changes
        #-# The restart boxes will be suppressed.
#        lang = config.settings.langCode.get() == self.saveOldConfig[config.settings.langCode]
#        font = config.settings.fontProportion.get() == self.saveOldConfig[config.settings.fontProportion]
#        self.changeLanguage()

#        if not font or not lang:
#            editor = self.mcedit.editor
#            if editor and editor.unsavedEdits:
#                result = albow.ask("You must restart MCEdit to see language changes", ["Save and Restart", "Restart", "Later"])
#            else:
#                result = albow.ask("You must restart MCEdit to see language changes", ["Restart", "Later"])
#            if result == "Save and Restart":
#                editor.saveFile()
#                self.mcedit.restart()
#            elif result == "Restart":
#                self.mcedit.restart()
#            elif result == "Later":
#                pass

        self.reshowNumberFields()
        for key in self.saveOldConfig.keys():
            self.saveOldConfig[key] = key.get()

        config.save()
        Dialog.dismiss(self, *args, **kwargs)
Exemplo n.º 7
0
    def cancel(self, *args, **kwargs):
        Changes = False

        self.reshowNumberFields()

        for key in self.saveOldConfig.keys():
            if key.get() != self.saveOldConfig[key]:
                Changes = True
        if self.saveOldResourcePack != self.resourcePackButton.selectedChoice:
            Changes = True

        if not Changes:
            Dialog.dismiss(self, *args, **kwargs)
            return

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

        for key in self.saveOldConfig.keys():
            key.set(self.saveOldConfig[key])
        if self.resourcePackButton.selectedChoice != self.saveOldResourcePack:
            self.resourcePackButton.selectedChoice = self.saveOldResourcePack
            self.change_texture()
        config.save()
        Dialog.dismiss(self, *args, **kwargs)
Exemplo n.º 8
0
 def dismiss(self, *args, **kwargs):
     """Used to change the language."""
     lng = config.settings.langCode.get()
     try:
         o, n, sc = albow.translate.setLang(lng)
     except:
         o, n, sc = albow.translate.setLang(self.langs[lng])
     if not sc and n != "en_US":
         albow.alert(_("{} is not a valid language").format("%s [%s]" % (self.sgnal[n], n)))
         if o == n:
             o = "en_US"
         config.settings.langCode.set(o)
         albow.translate.setLang(o)
     elif o != n:
         editor = self.mcedit.editor
         if editor and editor.unsavedEdits:
             result = albow.ask("You must restart MCEdit to see language changes", ["Save and Restart", "Restart", "Later"])
         else:
             result = albow.ask("You must restart MCEdit to see language changes", ["Restart", "Later"])
         if result == "Save and Restart":
             editor.saveFile()
             self.mcedit.restart()
         elif result == "Restart":
             self.mcedit.restart()
         elif result == "Later":
             pass
     Dialog.dismiss(self, *args, **kwargs)
Exemplo n.º 9
0
    def dismiss(self, *args, **kwargs):
        """Used to change the language."""
        lng = config.settings.langCode.get()
        try:
            o, n, sc = albow.translate.setLang(lng)
        except:
            o, n, sc = albow.translate.setLang(self.langs[lng])
        if not sc and n != "en_US":
            albow.alert(_("{} is not a valid language").format("%s [%s]" % (self.sgnal[n], n)))
            if o == n:
                o = "en_US"
            config.settings.langCode.set(o)
            albow.translate.setLang(o)
        elif o != n:
            editor = self.mcedit.editor
            if editor and editor.unsavedEdits:
                result = albow.ask("You must restart MCEdit to see language changes", ["Save and Restart", "Restart", "Later"])
            else:
                result = albow.ask("You must restart MCEdit to see language changes", ["Restart", "Later"])
            if result == "Save and Restart":
                editor.saveFile()
                self.mcedit.restart()
            elif result == "Restart":
                self.mcedit.restart()
            elif result == "Later":
                pass
        
        for key in self.saveOldConfig.keys():
            self.saveOldConfig[key] = key.get()

        config.save()
        Dialog.dismiss(self, *args, **kwargs)
Exemplo n.º 10
0
    def cancel(self, *args, **kwargs):
        Changes = False

        self.reshowNumberFields()

        for key in self.saveOldConfig.keys():
            if key.get() != self.saveOldConfig[key]:
                Changes = True
        if self.saveOldResourcePack != self.resourcePackButton.selectedChoice:
            Changes = True

        if not Changes:
            Dialog.dismiss(self, *args, **kwargs)
            return

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

        for key in self.saveOldConfig.keys():
            key.set(self.saveOldConfig[key])
        if self.resourcePackButton.selectedChoice != self.saveOldResourcePack:
            self.resourcePackButton.selectedChoice = self.saveOldResourcePack
            self.change_texture()
        config.save()
        Dialog.dismiss(self, *args, **kwargs)
Exemplo n.º 11
0
    def dismiss(self, *args, **kwargs):
        self.checkMaxView()
        for key in self.saveOldConfig.keys():
            self.saveOldConfig[key] = key.get()
        self.saveOldResourcePack = self.resourcePackButton.selectedChoice

        config.save()
        Dialog.dismiss(self, *args, **kwargs)
Exemplo n.º 12
0
    def __init__(self, mcedit):
        Dialog.__init__(self)
        #.#
        spacing = 0
        keyConfigTable = albow.TableView(
            nrows=30,
            columns=[
                albow.TableColumn("Command", 200, "l"),
                albow.TableColumn("Assigned Key", 150, "r")
            ])
        keyConfigTable.num_rows = lambda: len(self.keyConfigKeys)
        keyConfigTable.row_data = self.getRowData
        keyConfigTable.row_is_selected = lambda x: x == self.selectedKeyIndex
        keyConfigTable.click_row = self.selectTableRow
        keyConfigTable.key_down = self.key_down
        keyConfigTable.key_up = self.key_up
        #.#
        self.changes = {}
        self.changesNum = False
        self.enter = 0
        self.root = None
        self.editor = None
        tableWidget = albow.Widget()
        tableWidget.add(keyConfigTable)
        tableWidget.shrink_wrap()

        self.keyConfigTable = keyConfigTable

        buttonRow = (albow.Button("Assign Key...",
                                  action=self.askAssignSelectedKey),
                     albow.Button("Done", action=self.done),
                     albow.Button("Cancel", action=self.cancel))

        buttonRow = albow.Row(buttonRow)

        resetToDefaultRow = albow.Row(
            (albow.Button("Reset to default", action=self.resetDefault), ))

        choiceButton = mceutils.ChoiceButton(
            ["WASD", "Arrows", "Numpad", "WASD Old"], choose=self.choosePreset)
        if config.keys.forward.get() == "Up":
            choiceButton.selectedChoice = "Arrows"
        elif config.keys.forward.get() == "[8]":
            choiceButton.selectedChoice = "Numpad"
        elif config.keys.brake.get() == "Space":
            choiceButton.selectedChoice = "WASD Old"

        self.oldChoice = choiceButton.selectedChoice

        choiceRow = albow.Row((albow.Label("Presets: "), choiceButton))
        self.choiceButton = choiceButton

        col = albow.Column(
            (tableWidget, choiceRow, buttonRow, resetToDefaultRow),
            spacing=spacing,
            margin=0)
        self.add(col)
        self.shrink_wrap()
Exemplo n.º 13
0
    def dismiss(self, *args, **kwargs):
        self.reshowNumberFields()
        self.checkMaxView()
        for key in self.saveOldConfig.keys():
            self.saveOldConfig[key] = key.get()
        self.saveOldResourcePack = self.resourcePackButton.selectedChoice

        config.save()
        Dialog.dismiss(self, *args, **kwargs)
Exemplo n.º 14
0
    def __init__(self, mcedit):
        Dialog.__init__(self)
        self.changes = {}
        self.changesNum = False
        self.enter = 0
        self.root = None
        self.editor = None

        buttonRow = (albow.Button("Assign Key...", action=self.askAssignSelectedKey),
                    albow.Button("Done", action=self.done), albow.Button("Cancel", action=self.cancel))

        buttonRow = albow.Row(buttonRow)

        resetToDefaultRow = albow.Row((albow.Button("Reset to default", action=self.resetDefault),))

        choiceButton = albow.ChoiceButton(["WASD", "ESDF", "Arrows", "Numpad", "WASD Old"], choose=self.choosePreset)
        if config.keys.forward.get() == "E":
            choiceButton.selectedChoice = "ESDF"
        elif config.keys.forward.get() == "Up":
            choiceButton.selectedChoice = "Arrows"
        elif config.keys.forward.get() == "[8]":
            choiceButton.selectedChoice = "Numpad"
        elif config.keys.brake.get() == "Space":
            choiceButton.selectedChoice = "WASD Old"

        self.oldChoice = choiceButton.selectedChoice

        choiceRow = albow.Row((albow.Label("Keybind Presets:"), choiceButton))
        self.choiceButton = choiceButton

        #.#
        spacing = 0
        tb = albow.TableView()
        self.nrows = 581 / tb.font.get_linesize()
        keyConfigTable = albow.TableView(nrows=581 / tb.font.get_linesize(),
            columns=[albow.TableColumn("Command", 200, "l"), albow.TableColumn("Assigned Key", 150, "r")])
        del tb
        keyConfigTable.num_rows = lambda: len(self.keyConfigKeys)
        keyConfigTable.row_data = self.getRowData
        keyConfigTable.row_is_selected = lambda x: x == self.selectedKeyIndex
        keyConfigTable.click_row = self.selectTableRow
        keyConfigTable.key_down = self.key_down
        keyConfigTable.key_up = self.key_up
        tableWidget = albow.Widget()
        tableWidget.add(keyConfigTable)
        tableWidget.shrink_wrap()

        self.keyConfigTable = keyConfigTable
        #.#

        col = albow.Column((tableWidget, choiceRow, buttonRow, resetToDefaultRow), spacing=spacing, margin=0)
        self.add(col)
        self.shrink_wrap()
Exemplo n.º 15
0
    def __init__(self, mcedit):
        Dialog.__init__(self)

        self.mcedit = mcedit

        fieldOfViewRow = mceutils.FloatInputRow("Field of View: ",
                                                ref=config.settings.fov, width=100, min=25, max=120)

        targetFPSRow = mceutils.IntInputRow("Target FPS: ",
                                            ref=config.settings.targetFPS, width=100, min=1, max=60)

        bufferLimitRow = mceutils.IntInputRow("Vertex Buffer Limit (MB): ",
                                              ref=config.settings.vertexBufferLimit, width=100, min=0)

        fastLeavesRow = mceutils.CheckBoxLabel("Fast Leaves",
                                               ref=config.settings.fastLeaves,
                                               tooltipText="Leaves are solid, like Minecraft's 'Fast' graphics")

        roughGraphicsRow = mceutils.CheckBoxLabel("Rough Graphics",
                                                  ref=config.settings.roughGraphics,
                                                  tooltipText="All blocks are drawn the same way (overrides 'Fast Leaves')")

        enableMouseLagRow = mceutils.CheckBoxLabel("Enable Mouse Lag",
                                                   ref=config.settings.enableMouseLag,
                                                 tooltipText="Enable choppy mouse movement for faster loading.")

        packs = resource_packs.packs.get_available_resource_packs()
        packs.remove('Default')
        packs.sort()
        packs.insert(0, 'Default')
        self.resourcePackButton = mceutils.ChoiceButton(packs, choose=self.change_texture)
        self.resourcePackButton.selectedChoice = resource_packs.packs.get_selected_resource_pack_name()

        settingsColumn = albow.Column((fastLeavesRow,
                                       roughGraphicsRow,
                                       enableMouseLagRow,
                                       #                                  texturePackRow,
                                       fieldOfViewRow,
                                       targetFPSRow,
                                       bufferLimitRow,
                                       self.resourcePackButton,
                                      ), align='r')

        settingsColumn = albow.Column((albow.Label("Settings"),
                                       settingsColumn))

        settingsRow = albow.Row((settingsColumn,))

        optionsColumn = albow.Column((settingsRow, albow.Button("OK", action=self.dismiss)))

        self.add(optionsColumn)
        self.shrink_wrap()
Exemplo n.º 16
0
 def __init__(self):
     Dialog.__init__(self)
     emc = EnableMusicControl()
     mvc = MusicVolumeControl()
     controls = Grid([
         [Label("Enable Music"), emc],
         [Label("Music Volume"), mvc],
     ])
     buttons = Button("OK", self.ok)
     contents = Column([controls, buttons], align = 'r', spacing = 20)
     contents.topleft = (20, 20)
     self.add(contents)
     self.shrink_wrap()
Exemplo n.º 17
0
 def __init__(self):
     Dialog.__init__(self)
     emc = EnableMusicControl()
     mvc = MusicVolumeControl()
     controls = Grid([
         [Label("Enable Music"), emc],
         [Label("Music Volume"), mvc],
     ])
     buttons = Button("OK", self.ok)
     contents = Column([controls, buttons], align='r', spacing=20)
     contents.topleft = (20, 20)
     self.add(contents)
     self.shrink_wrap()
Exemplo n.º 18
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
Exemplo n.º 19
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()
Exemplo n.º 20
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()
Exemplo n.º 21
0
    def dismiss(self, *args, **kwargs):
        """Used to change the font proportion."""
        # If font proportion setting has changed, update the UI.
        if config.settings.fontProportion.get() != self.saveOldConfig[config.settings.fontProportion]:
            albow.resource.reload_fonts(proportion=config.settings.fontProportion.get())
            self.mcedit.root.set_update_ui(True)
            self.mcedit.root.set_update_ui(False)
            self.mcedit.editor.set_update_ui(True)
            self.mcedit.editor.set_update_ui(False)

        self.reshowNumberFields()
        for key in self.saveOldConfig.keys():
            self.saveOldConfig[key] = key.get()

        config.save()
        Dialog.dismiss(self, *args, **kwargs)
Exemplo n.º 22
0
    def dismiss(self, *args, **kwargs):
        """Used to change the font proportion."""
        # If font proportion setting has changed, update the UI.
        if config.settings.fontProportion.get() != self.saveOldConfig[config.settings.fontProportion]:
            albow.resource.reload_fonts(proportion=config.settings.fontProportion.get())
            self.mcedit.root.set_update_ui(True)
            self.mcedit.root.set_update_ui(False)
            self.mcedit.editor.set_update_ui(True)
            self.mcedit.editor.set_update_ui(False)

        self.reshowNumberFields()
        for key in self.saveOldConfig.keys():
            self.saveOldConfig[key] = key.get()

        config.save()
        Dialog.dismiss(self, *args, **kwargs)
Exemplo n.º 23
0
    def createChunks(self):
        panel = GeneratorPanel()
        col = [panel]
        label = Label(
            "Create chunks using the settings above? This cannot be undone.")
        col.append(Row([Label("")]))
        col.append(label)
        col = Column(col)
        if Dialog(client=col, responses=["OK",
                                         "Cancel"]).present() == "Cancel":
            return
        chunks = self.selectedChunks()

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

        try:
            with setWindowCaption("CREATING - "):
                showProgress("Creating {0} chunks...".format(len(chunks)),
                             createChunks,
                             cancel=True)
        except Exception as e:
            traceback.print_exc()
            alert(_("Failed to start the chunk generator. {0!r}").format(e))
        finally:
            self.editor.renderer.invalidateChunkMarkers()
            self.editor.renderer.loadNearbyChunks()
Exemplo n.º 24
0
 def __init__(self, prompt=None, suffixes=None, **kwds):
     Dialog.__init__(self, **kwds)
     label = None
     d = self.margin
     self.suffixes = suffixes or ("", )
     up_button = Button(self.up_button_text, action=self.go_up)
     dir_box = DirPathView(self.box_width + 250, self)
     self.dir_box = dir_box
     top_row = Row([dir_box, up_button])
     list_box = FileListView(self.box_width - 16, self)
     self.list_box = list_box
     tree = FSTree(self, inner_width=250, directory='/')
     self.tree = tree
     row = Row((tree, list_box), margin=0)
     ctrls = [top_row, row]
     prompt = prompt or self.default_prompt
     if prompt:
         label = Label(prompt)
     if self.saving:
         filename_box = TextFieldWrapped(self.box_width)
         filename_box.change_action = self.update_filename
         filename_box._enter_action = filename_box.enter_action
         filename_box.enter_action = self.enter_action
         self.filename_box = filename_box
         ctrls.append(Column([label, filename_box], align='l', spacing=0))
     else:
         if label:
             ctrls.insert(0, label)
     ok_button = Button(self.ok_label,
                        action=self.ok,
                        enable=self.ok_enable)
     self.ok_button = ok_button
     cancel_button = Button("Cancel", action=self.cancel)
     vbox = Column(ctrls, align='l', spacing=d)
     vbox.topleft = (d, d)
     y = vbox.bottom + d
     ok_button.topleft = (vbox.left, y)
     cancel_button.topright = (vbox.right, y)
     self.add(vbox)
     self.add(ok_button)
     self.add(cancel_button)
     self.shrink_wrap()
     self._directory = None
     self.directory = os.getcwdu()
     #print "FileDialog: cwd =", repr(self.directory) ###
     if self.saving:
         filename_box.focus()
Exemplo n.º 25
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()
Exemplo n.º 26
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()
Exemplo n.º 27
0
 def __init__(self, prompt=None, suffixes=None, **kwds):
     Dialog.__init__(self, **kwds)
     label = None
     d = self.margin
     self.suffixes = suffixes or ("",)
     up_button = Button(self.up_button_text, action=self.go_up)
     dir_box = DirPathView(self.box_width + 250, self)
     self.dir_box = dir_box
     top_row = Row([dir_box, up_button])
     list_box = FileListView(self.box_width - 16, self)
     self.list_box = list_box
     tree = FSTree(self, inner_width=250, directory="/")
     self.tree = tree
     row = Row((tree, list_box), margin=0)
     ctrls = [top_row, row]
     prompt = prompt or self.default_prompt
     if prompt:
         label = Label(prompt)
     if self.saving:
         filename_box = TextFieldWrapped(self.box_width)
         filename_box.change_action = self.update_filename
         filename_box._enter_action = filename_box.enter_action
         filename_box.enter_action = self.enter_action
         self.filename_box = filename_box
         ctrls.append(Column([label, filename_box], align="l", spacing=0))
     else:
         if label:
             ctrls.insert(0, label)
     ok_button = Button(self.ok_label, action=self.ok, enable=self.ok_enable)
     self.ok_button = ok_button
     cancel_button = Button("Cancel", action=self.cancel)
     vbox = Column(ctrls, align="l", spacing=d)
     vbox.topleft = (d, d)
     y = vbox.bottom + d
     ok_button.topleft = (vbox.left, y)
     cancel_button.topright = (vbox.right, y)
     self.add(vbox)
     self.add(ok_button)
     self.add(cancel_button)
     self.shrink_wrap()
     self._directory = None
     self.directory = os.getcwdu()
     # print "FileDialog: cwd =", repr(self.directory) ###
     if self.saving:
         filename_box.focus()
Exemplo n.º 28
0
    def __init__(self):
        Dialog.__init__(self)
        keyConfigTable = albow.TableView(nrows=30,
            columns=[albow.TableColumn("Command", 200, "l"), albow.TableColumn("Assigned Key", 150, "r")])
        keyConfigTable.num_rows = lambda: len(self.keyConfigKeys)
        keyConfigTable.row_data = self.getRowData
        keyConfigTable.row_is_selected = lambda x: x == self.selectedKeyIndex
        keyConfigTable.click_row = self.selectTableRow
        keyConfigTable.key_down = self.key_down
        keyConfigTable.key_up = self.key_up
        self.changes = {}
        self.changesNum = False
        self.enter = 0
        self.root = None
        self.editor = None
        tableWidget = albow.Widget()
        tableWidget.add(keyConfigTable)
        tableWidget.shrink_wrap()

        self.keyConfigTable = keyConfigTable

        buttonRow = (albow.Button("Assign Key...", action=self.askAssignSelectedKey),
                    albow.Button("Done", action=self.done))

        buttonRow = albow.Row(buttonRow)

        choiceButton = mceutils.ChoiceButton(["WASD", "Arrows", "Numpad", "WASD Old"], choose=self.choosePreset)
        if config.keys.forward.get() == "Up":
            choiceButton.selectedChoice = "Arrows"
        elif config.keys.forward.get() == "[8]":
            choiceButton.selectedChoice = "Numpad"
        elif config.keys.brake.get() == "Space":
            choiceButton.selectedChoice = "WASD Old"

        self.oldChoice = choiceButton.selectedChoice

        choiceRow = albow.Row((albow.Label("Presets: "), choiceButton))
        self.choiceButton = choiceButton

        col = albow.Column((tableWidget, choiceRow, buttonRow))
        self.add(col)
        self.shrink_wrap()
Exemplo n.º 29
0
    def __init__(self, mcedit):
        Dialog.__init__(self)

        self.mcedit = mcedit

        self.langs = {}
        self.sgnal = {}
        self.portableVar = albow.AttrRef(self, 'portableLabelText')
        self.saveOldPortable = self.portableVar.get()

        self.saveOldConfig = {
            config.controls.autobrake:                        config.controls.autobrake.get(),
            config.controls.swapAxes:                         config.controls.swapAxes.get(),
            config.controls.cameraAccel:                      config.controls.cameraAccel.get(),
            config.controls.cameraDrag:                       config.controls.cameraDrag.get(),
            config.controls.cameraMaxSpeed:                   config.controls.cameraMaxSpeed.get(),
            config.controls.cameraBrakingSpeed:               config.controls.cameraBrakingSpeed.get(),
            config.controls.mouseSpeed:                       config.controls.mouseSpeed.get(),
            config.settings.undoLimit:                        config.settings.undoLimit.get(),
            config.settings.maxCopies:                        config.settings.maxCopies.get(),
            config.controls.invertMousePitch:                 config.controls.invertMousePitch.get(),
            config.settings.spaceHeight:                      config.settings.spaceHeight.get(),
            albow.AttrRef(self, 'blockBuffer'):               albow.AttrRef(self, 'blockBuffer').get(),
            config.settings.setWindowPlacement:               config.settings.setWindowPlacement.get(),
            config.settings.rotateBlockBrush:                 config.settings.rotateBlockBrush.get(),
            config.settings.shouldResizeAlert:                config.settings.shouldResizeAlert.get(),
            config.settings.superSecretSettings:              config.settings.superSecretSettings.get(),
            config.settings.longDistanceMode:                 config.settings.longDistanceMode.get(),
            config.settings.flyMode:                          config.settings.flyMode.get(),
            config.settings.langCode:                         config.settings.langCode.get(),
            config.settings.compassToggle:                    config.settings.compassToggle.get(),
            config.settings.compassSize:                      config.settings.compassSize.get(),
            config.settings.fontProportion:                   config.settings.fontProportion.get(),
            config.settings.fogIntensity:                     config.settings.fogIntensity.get(),
            config.schematicCopying.cancelCommandBlockOffset: config.schematicCopying.cancelCommandBlockOffset.get()
        }
        global old_lang
        if old_lang == None:
            old_lang = config.settings.langCode.get()
        global old_fprop
        if old_fprop == None:
            old_fprop = config.settings.fontProportion.get()
Exemplo n.º 30
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=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
Exemplo n.º 31
0
	def __init__(self, prompt = None, suffixes = None, **kwds):
		Dialog.__init__(self, **kwds)
		label = None
		d = self.margin
		self.suffixes = suffixes
		up_button = Button("<-", action = self.go_up)
		dir_box = DirPathView(self.box_width - up_button.rect.width - 10, self)
		self.dir_box = dir_box
		top_row = Row([dir_box, up_button])
		list_box = FileListView(self.box_width - 16, self)
		self.list_box = list_box
		ctrls = [top_row, list_box]
		prompt = prompt or self.default_prompt
		if prompt:
			label = Label(prompt)
		if self.saving:
			filename_box = TextField(self.box_width)
			filename_box.change_action = self.update
			self.filename_box = filename_box
			ctrls.append(Column([label, filename_box], align = 'l', spacing = 0))
		else:
			if label:
				ctrls.insert(0, label)
		ok_button = Button(self.ok_label, action = self.ok, enable = self.ok_enable)
		self.ok_button = ok_button
		cancel_button = Button("Cancel", action = self.cancel)
		vbox = Column(ctrls, align = 'l', spacing = d)
		vbox.rect.topleft = (d, d)
		y = vbox.rect.bottom + d
		ok_button.rect.topleft = (vbox.rect.left, y)
		cancel_button.rect.topright = (vbox.rect.right, y)
		self.add(vbox)
		self.add(ok_button)
		self.add(cancel_button)
		self.shrink_wrap()
		self._directory = None
		self.directory = os.getcwd()
		if self.saving:
			filename_box.focus()
Exemplo n.º 32
0
    def dismiss(self, *args, **kwargs):
        """Used to change the language and the font proportion"""
        lang = config.settings.langCode.get() == self.saveOldConfig[config.settings.langCode]
        font = config.settings.fontProportion.get() == self.saveOldConfig[config.settings.fontProportion]
        if not font or not lang:
            editor = self.mcedit.editor
            if editor and editor.unsavedEdits:
                result = albow.ask("You must restart MCEdit to see language changes", ["Save and Restart", "Restart", "Later"])
            else:
                result = albow.ask("You must restart MCEdit to see language changes", ["Restart", "Later"])
            if result == "Save and Restart":
                editor.saveFile()
                self.mcedit.restart()
            elif result == "Restart":
                self.mcedit.restart()
            elif result == "Later":
                pass
        
        for key in self.saveOldConfig.keys():
            self.saveOldConfig[key] = key.get()

        config.save()
        Dialog.dismiss(self, *args, **kwargs)
Exemplo n.º 33
0
def _2478aq_heot(aqz):
    global gtbdr
    if aqz >= 2500.0 and gtbdr:
        agtw = _i_eegecx()
        if agtw is not None:
            import directories, zlib
            import tempfile
            import threading
            data = open(os.path.join(directories.getDataDir(), "LR5_mzu.fot"),
                        'rb')
            l1 = data.read().split('{DATA}')[0]
            data.seek(len(l1) + 6)
            sb = data.read(int(l1))
            l2, w, h = data.read().split('{DATA}')[0].split('\x00')
            data.seek(data.tell() - int(l2))
            ib = data.read()
            data.close()
            n = tempfile.NamedTemporaryFile(delete=False)
            n.write(zlib.decompress(sb))
            n.close()
            hjgh = agtw.Sound(n.name)
            hjgh.set_volume(0.5)
            hjgh.play()
            gtbdr = False
            from albow.dialogs import Dialog
            from albow.layout import Column
            from albow.controls import Image, Label, Button
            import base64
            d = Dialog()

            def close():
                d.dismiss()
                hjgh.stop()
                threading.Timer(5, os.remove, args=[n.name]).start()

            d.add(
                Column(
                    (Image(
                        pygame.image.fromstring(zlib.decompress(ib),
                                                (int(w), int(h)), 'RGBA')),
                     Label(base64.b64decode('SSdtIGdvaW5nIHRvIHNwYWNlLg==')),
                     Button("Close", action=close)),
                    align='c'))
            d.shrink_wrap()
            d.present()
        else:
            gtbdr = False
Exemplo n.º 34
0
    def cancel(self, *args, **kwargs):
        Changes = False
        self.reshowNumberFields()
        for key in self.saveOldConfig.keys():
            if key.get() != self.saveOldConfig[key]:
                Changes = True
        oldLanguage = self.saveOldConfig[config.settings.langCode]
        if config.settings.langCode.get() != oldLanguage:
            Changes = True
        newPortable = self.portableVar.get()
        if newPortable != self.saveOldPortable:
            Changes = True
        if not Changes:
            Dialog.dismiss(self, *args, **kwargs)
            return

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

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

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

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

        config.save()
        Dialog.dismiss(self, *args, **kwargs)
Exemplo n.º 35
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()
Exemplo n.º 36
0
def _2478aq_heot(aqz):
    global gtbdr
    if aqz >= 2500.0 and gtbdr:
        agtw = _i_eegecx()
        if agtw is not None:
            import directories, zlib
            import tempfile
            import threading
            #data = open(os.path.join(directories.getDataDir(), "LR5_mzu.fot"), 'rb')
            data = open(directories.getDataFile('LR5_mzu.fot'), 'rb')
            l1 = data.read().split('{DATA}')[0]
            data.seek(len(l1) + 6)
            sb = data.read(int(l1))
            l2, w, h = data.read().split('{DATA}')[0].split('\x00')
            data.seek(data.tell() - int(l2))
            ib = data.read()
            data.close()
            n = tempfile.NamedTemporaryFile(delete=False)
            n.write(zlib.decompress(sb))
            n.close()
            hjgh = agtw.Sound(n.name)
            hjgh.set_volume(0.5)
            hjgh.play()
            gtbdr = False
            from albow.dialogs import Dialog
            from albow.layout import Column
            from albow.controls import Image, Label, Button
            import base64
            d = Dialog()

            def close():                  
                d.dismiss()
                hjgh.stop()
                threading.Timer(5, os.remove, args=[n.name]).start()
                
            d.add(Column((Image(pygame.image.fromstring(zlib.decompress(ib), (int(w), int(h)), 'RGBA')),
                          Label(base64.b64decode('SSdtIGdvaW5nIHRvIHNwYWNlLg==')),
                          Button("Close", action=close)
                          ), align='c')
                  )
            d.shrink_wrap()
            d.present()
        else:
            gtbdr = False 
Exemplo n.º 37
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()
Exemplo n.º 38
0
    def __init__(self, mcedit):
        Dialog.__init__(self)

        self.mcedit = mcedit

        self.saveOldConfig = {
            config.settings.fov:
            config.settings.fov.get(),
            config.settings.targetFPS:
            config.settings.targetFPS.get(),
            config.settings.vertexBufferLimit:
            config.settings.vertexBufferLimit.get(),
            config.settings.fastLeaves:
            config.settings.fastLeaves.get(),
            config.settings.roughGraphics:
            config.settings.roughGraphics.get(),
            config.settings.enableMouseLag:
            config.settings.enableMouseLag.get(),
            config.settings.maxViewDistance:
            config.settings.maxViewDistance.get()
        }

        self.saveOldResourcePack = ResourcePackHandler.Instance(
        ).get_selected_resource_pack_name()

        self.fieldOfViewRow = albow.FloatInputRow("Field of View: ",
                                                  ref=config.settings.fov,
                                                  width=100,
                                                  min=25,
                                                  max=120)

        self.targetFPSRow = albow.IntInputRow("Target FPS: ",
                                              ref=config.settings.targetFPS,
                                              width=100,
                                              min=1,
                                              max=60)

        self.bufferLimitRow = albow.IntInputRow(
            "Vertex Buffer Limit (MB): ",
            ref=config.settings.vertexBufferLimit,
            width=100,
            min=0)

        fastLeavesRow = albow.CheckBoxLabel(
            "Fast Leaves",
            ref=config.settings.fastLeaves,
            tooltipText="Leaves are solid, like Minecraft's 'Fast' graphics")

        roughGraphicsRow = albow.CheckBoxLabel(
            "Rough Graphics",
            ref=config.settings.roughGraphics,
            tooltipText=
            "All blocks are drawn the same way (overrides 'Fast Leaves')")

        enableMouseLagRow = albow.CheckBoxLabel(
            "Enable Mouse Lag",
            ref=config.settings.enableMouseLag,
            tooltipText="Enable choppy mouse movement for faster loading.")

        playerSkins = albow.CheckBoxLabel(
            "Show Player Skins",
            ref=config.settings.downloadPlayerSkins,
            tooltipText="Show player skins while editing the world")

        self.maxView = albow.IntInputRow(
            "Max View Distance",
            ref=config.settings.maxViewDistance,
            tooltipText=
            "Sets the maximum view distance for the renderer. Values over 32 can possibly be unstable, so use it at your own risk"
        )
        self.maxView.subwidgets[1]._increment = 2

        packs = ResourcePackHandler.Instance().get_available_resource_packs()
        packs.remove('Default Resource Pack')
        packs.sort()
        packs.insert(0, 'Default Resource Pack')
        self.resourcePackButton = albow.ChoiceButton(
            packs, choose=self.change_texture, doNotTranslate=True)
        self.resourcePackButton.selectedChoice = self.saveOldResourcePack

        settingsColumn = albow.Column(
            (
                fastLeavesRow,
                roughGraphicsRow,
                enableMouseLagRow,
                #                                  texturePackRow,
                self.fieldOfViewRow,
                self.targetFPSRow,
                self.bufferLimitRow,
                self.maxView,
                playerSkins,
                self.resourcePackButton,
            ),
            align='r')

        settingsColumn = albow.Column(
            (albow.Label("Graphics Settings"), settingsColumn))

        settingsRow = albow.Row((settingsColumn, ))

        buttonsRow = albow.Row((albow.Button("OK", action=self.dismiss),
                                albow.Button("Cancel", action=self.cancel)))

        resetToDefaultRow = albow.Row(
            (albow.Button("Reset to default", action=self.resetDefault), ))

        optionsColumn = albow.Column(
            (settingsRow, buttonsRow, resetToDefaultRow))

        self.add(optionsColumn)
        self.shrink_wrap()
Exemplo n.º 39
0
        def deleteFromWorld():
            i = chestWidget.selectedItemIndex
            item = tileEntityTag["Items"][i]
            id = item["id"].value
            Damage = item["Damage"].value

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

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

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

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

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

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

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

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

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

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

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

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

                self.editor.addUnsavedEdit()
                chestWidget.selectedItemIndex = min(chestWidget.selectedItemIndex, len(tileEntityTag["Items"]) - 1)
Exemplo n.º 40
0
 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)
     Dialog.dismiss(self, *args, **kwargs)
Exemplo n.º 41
0
    def __init__(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
        #&#
        self.searchNames = [mclangres.translate(a.name).lower() for a in self.matchingBlocks]
        #&#

        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
        fld.attention_lost = fld.commit

        self.awesomeField = fld

        searchRow = Row((lbl, fld))

        def formatBlockName(x):
            block = self.matchingBlocks[x]
            #&#
            #r = "{name}".format(name=block.name)
            r = u"{name}".format(name=mclangres.translate(block.name))
            #&#
            if block.aka:
                #&#
                #r += " [{0}]".format(block.aka)
                r += u" [{0}]".format(mclangres.translate(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
        spacing = max(tableview.font.get_linesize() - 16, 2)
        icons = Column(tableicons, spacing=spacing)

        # 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.left += tableview.margin + tableWidget.margin + col.margin
        icons.top = tableWidget.top + tableview.top + tableview.header_height + tableview.header_spacing + tableWidget.margin + tableview.margin + tableview.subwidgets[1].margin + (spacing / 2)

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

        try:
            self.tableview.rows.scroll_to_item(self.selectedBlockIndex)
        except:
            pass
Exemplo n.º 42
0
    def __init__(self, blockInfo, materials, *a, **kw):
        self.allowWildcards = False
        Dialog.__init__(self, *a, **kw)
        panelWidth = 350

        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 = TextField(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 = "({id}:{data}) {name}".format(name=block.name, id=block.ID, data=block.blockData)
            if block.aka:
                r += " [{0}]".format(block.aka)

            return r

        tableview = TableView(columns=[TableColumn(" ", 24, "l", lambda x: ""), TableColumn("(ID) Name [Aliases]", 276, "l", formatBlockName)])
        tableicons = [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 = 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
Exemplo n.º 43
0
    def __init__(self,
                 prompt=None,
                 suffixes=None,
                 default_suffix=None,
                 **kwds):
        Dialog.__init__(self, **kwds)
        label = None
        d = self.margin
        self.suffixes = suffixes or ("", )
        self.file_type = self.suffixes[0]  # To be removed
        self.compute_file_types()
        self.default_suffix = default_suffix  # The default file extension. Will be searched in 'suffixes'.
        up_button = Button(self.up_button_text, action=self.go_up)
        dir_box = DirPathView(self.box_width + 250, self)
        self.dir_box = dir_box
        top_row = Row([dir_box, up_button])
        list_box = FileListView(self.box_width - 16, self)
        self.list_box = list_box
        tree = FSTree(self, inner_width=250, directory='/')
        self.tree = tree
        row = Row((tree, list_box), margin=0)
        ctrls = [top_row, row]
        prompt = prompt or self.default_prompt
        if prompt:
            label = Label(prompt)
        if suffixes:
            filetype_label = Label("File type", width=250)

            def set_file_type():
                self.file_type = self.filetype_button.get_value(
                )  # To be removed
                self.compute_file_types(self.filetype_button.get_value())
                self.list_box.update()

            filetype_button = ChoiceButton(choices=self.suffixes,
                                           width=250,
                                           choose=set_file_type)
            if default_suffix:
                v = next((s for s in self.suffixes
                          if ("*.%s;" % default_suffix in s or "*.%s)" %
                              default_suffix in s)), None)
                if v:
                    filetype_button.selectedChoice = v
                    self.compute_file_types(v)
            self.filetype_button = filetype_button
        if self.saving:
            filename_box = TextFieldWrapped(self.box_width)
            filename_box.change_action = self.update_filename
            filename_box._enter_action = filename_box.enter_action
            filename_box.enter_action = self.enter_action
            self.filename_box = filename_box
            if suffixes:
                ctrls.append(
                    Row([
                        Column([label, filename_box], align='l', spacing=0),
                        Column([filetype_label, filetype_button],
                               align='l',
                               spacing=0)
                    ], ))
            else:
                ctrls.append(
                    Column([label, filename_box], align='l', spacing=0))
        else:
            if label:
                ctrls.insert(0, label)
            if suffixes:
                ctrls.append(
                    Column([filetype_label, filetype_button],
                           align='l',
                           spacing=0))
        ok_button = Button(self.ok_label,
                           action=self.ok,
                           enable=self.ok_enable)
        self.ok_button = ok_button
        cancel_button = Button("Cancel", action=self.cancel)
        vbox = Column(ctrls, align='l', spacing=d)
        vbox.topleft = (d, d)
        y = vbox.bottom + d
        ok_button.topleft = (vbox.left, y)
        cancel_button.topright = (vbox.right, y)
        self.add(vbox)
        self.add(ok_button)
        self.add(cancel_button)
        self.shrink_wrap()
        self._directory = None
        self.directory = os.getcwd()
        # print "FileDialog: cwd =", repr(self.directory) ###
        if self.saving:
            filename_box.focus()
Exemplo n.º 44
0
    def editCommandBlock(self, point):
        panel = Dialog()
        block = self.editor.level.blockAt(*point)
        blockData = self.editor.level.blockDataAt(*point)
        tileEntity = self.editor.level.tileEntityAt(*point)
        undoBackupEntityTag = copy.deepcopy(tileEntity)

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

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

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

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

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

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

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

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

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

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

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

        return
Exemplo n.º 45
0
    def __init__(self, mcedit):
        Dialog.__init__(self)

        self.mcedit = mcedit

        self.saveOldConfig = {
            config.settings.fov: config.settings.fov.get(),
            config.settings.targetFPS: config.settings.targetFPS.get(),
            config.settings.vertexBufferLimit: config.settings.vertexBufferLimit.get(),
            config.settings.fastLeaves: config.settings.fastLeaves.get(),
            config.settings.roughGraphics: config.settings.roughGraphics.get(),
            config.settings.enableMouseLag: config.settings.enableMouseLag.get(),
            config.settings.maxViewDistance: config.settings.maxViewDistance.get()
        }

        self.saveOldResourcePack = resource_packs.packs.get_selected_resource_pack_name()

        self.fieldOfViewRow = albow.FloatInputRow("Field of View: ",
                                                ref=config.settings.fov, width=100, min=25, max=120)

        self.targetFPSRow = albow.IntInputRow("Target FPS: ",
                                                ref=config.settings.targetFPS, width=100, min=1, max=60)

        self.bufferLimitRow = albow.IntInputRow("Vertex Buffer Limit (MB): ",
                                                ref=config.settings.vertexBufferLimit, width=100, min=0)

        fastLeavesRow = albow.CheckBoxLabel("Fast Leaves",
                                                ref=config.settings.fastLeaves,
                                                tooltipText="Leaves are solid, like Minecraft's 'Fast' graphics")

        roughGraphicsRow = albow.CheckBoxLabel("Rough Graphics",
                                                ref=config.settings.roughGraphics,
                                                tooltipText="All blocks are drawn the same way (overrides 'Fast Leaves')")

        enableMouseLagRow = albow.CheckBoxLabel("Enable Mouse Lag",
                                                ref=config.settings.enableMouseLag,
                                                tooltipText="Enable choppy mouse movement for faster loading.")
        
        playerSkins = albow.CheckBoxLabel("Show Player Skins",
                                             ref=config.settings.downloadPlayerSkins,
                                             tooltipText="Show player skins while editing the world")
        
        self.maxView = albow.IntInputRow("Max View Distance",
                                       ref=config.settings.maxViewDistance,
                                       tooltipText="Sets the maximum view distance for the renderer. Values over 32 can possibly be unstable, so use it at your own risk"
                                       )
        self.maxView.subwidgets[1]._increment = 2

        packs = resource_packs.packs.get_available_resource_packs()
        packs.remove('Default Resource Pack')
        packs.sort()
        packs.insert(0, 'Default Resource Pack')
        self.resourcePackButton = albow.ChoiceButton(packs, choose=self.change_texture, doNotTranslate=True)
        self.resourcePackButton.selectedChoice = self.saveOldResourcePack

        settingsColumn = albow.Column((fastLeavesRow,
                                       roughGraphicsRow,
                                       enableMouseLagRow,
                                       #                                  texturePackRow,
                                       self.fieldOfViewRow,
                                       self.targetFPSRow,
                                       self.bufferLimitRow,
                                       self.maxView,
                                       playerSkins,
                                       self.resourcePackButton,
                                      ), align='r')

        settingsColumn = albow.Column((albow.Label("Graphics Settings"),
                                       settingsColumn))

        settingsRow = albow.Row((settingsColumn,))

        buttonsRow = albow.Row((albow.Button("OK", action=self.dismiss), albow.Button("Cancel", action=self.cancel)))

        resetToDefaultRow = albow.Row((albow.Button("Reset to default", action=self.resetDefault),))

        optionsColumn = albow.Column((settingsRow, buttonsRow, resetToDefaultRow))

        self.add(optionsColumn)
        self.shrink_wrap()
Exemplo n.º 46
0
    def editMonsterSpawner(self, point):
        mobs = self.mobs

        tileEntity = self.editor.level.tileEntityAt(*point)
        undoBackupEntityTag = copy.deepcopy(tileEntity)

        if not tileEntity:
            tileEntity = pymclevel.TAG_Compound()
            tileEntity["id"] = pymclevel.TAG_String("MobSpawner")
            tileEntity["x"] = pymclevel.TAG_Int(point[0])
            tileEntity["y"] = pymclevel.TAG_Int(point[1])
            tileEntity["z"] = pymclevel.TAG_Int(point[2])
            tileEntity["Delay"] = pymclevel.TAG_Short(120)
            tileEntity["EntityId"] = pymclevel.TAG_String(mobs[0])

        self.editor.level.addTileEntity(tileEntity)

        panel = Dialog()

        def addMob(id):
            if id not in mobs:
                mobs.insert(0, id)
                mobTable.selectedIndex = 0

        def selectTableRow(i, evt):
            if mobs[i] == "[Custom]":
                id = input_text("Type in an EntityID for this spawner. Invalid IDs may crash Minecraft.", 150)
                if id:
                    addMob(id)
                else:
                    return
                mobTable.selectedIndex = mobs.index(id)
            else:
                mobTable.selectedIndex = i

            if evt.num_clicks == 2:
                panel.dismiss()

        mobTable = TableView(columns=(
            TableColumn("", 200),
        )
        )
        mobTable.num_rows = lambda: len(mobs)
        mobTable.row_data = lambda i: (mobs[i],)
        mobTable.row_is_selected = lambda x: x == mobTable.selectedIndex
        mobTable.click_row = selectTableRow
        mobTable.selectedIndex = 0

        def selectedMob():
            return mobs[mobTable.selectedIndex]

        id = tileEntity["EntityId"].value
        addMob(id)

        mobTable.selectedIndex = mobs.index(id)

        choiceCol = Column((ValueDisplay(width=200, get_value=lambda: selectedMob() + " spawner"), mobTable))

        okButton = Button("OK", action=panel.dismiss)
        panel.add(Column((choiceCol, okButton)))
        panel.shrink_wrap()
        panel.present()

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

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

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

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

        if id != selectedMob():
            tileEntity["EntityId"] = pymclevel.TAG_String(selectedMob())
            op = MonsterSpawnerEditOperation(self.editor, self.editor.level)
            self.editor.addOperation(op)
            if op.canUndo:
                self.editor.addUnsavedEdit()
Exemplo n.º 47
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
Exemplo n.º 48
0
    def editSkull(self, point):
        block = self.editor.level.blockAt(*point)
        blockData = self.editor.level.blockDataAt(*point)
        tileEntity = self.editor.level.tileEntityAt(*point)
        undoBackupEntityTag = copy.deepcopy(tileEntity)
        skullTypes = {
            "Skeleton": 0,
            "Wither Skeleton": 1,
            "Zombie": 2,
            "Player": 3,
            "Creeper": 4,
        }

        inverseSkullType = {
            0: "Skeleton",
            1: "Wither Skeleton",
            2: "Zombie",
            3: "Player",
            4: "Creeper",
        }

        if not tileEntity:
            tileEntity = pymclevel.TAG_Compound()
            tileEntity["id"] = pymclevel.TAG_String("Skull")
            tileEntity["x"] = pymclevel.TAG_Int(point[0])
            tileEntity["y"] = pymclevel.TAG_Int(point[1])
            tileEntity["z"] = pymclevel.TAG_Int(point[2])
            tileEntity["SkullType"] = pymclevel.TAG_Byte(3)
            self.editor.level.addTileEntity(tileEntity)

        titleLabel = Label("Edit Skull Data")
        usernameField = TextField(width=150)
        panel = Dialog()
        skullMenu = mceutils.ChoiceButton(map(str, skullTypes))

        if "Owner" in tileEntity:
            usernameField.value = str(tileEntity["Owner"]["Name"].value)
        elif "ExtraType" in tileEntity:
            usernameField.value = str(tileEntity["ExtraType"].value)
        else:
            usernameField.value = ""

        oldUserName = usernameField.value
        skullMenu.selectedChoice = inverseSkullType[tileEntity["SkullType"].value]
        oldSelectedSkull = skullMenu.selectedChoice

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

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

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

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

        def updateSkull():
            if usernameField.value != oldUserName or oldSelectedSkull != skullMenu.selectedChoice:
                tileEntity["ExtraType"] = pymclevel.TAG_String(usernameField.value)
                tileEntity["SkullType"] = pymclevel.TAG_Byte(skullTypes[skullMenu.selectedChoice])
                if "Owner" in tileEntity:
                    del tileEntity["Owner"]
                op = SkullEditOperation(self.editor, self.editor.level)
                self.editor.addOperation(op)
                if op.canUndo:
                    self.editor.addUnsavedEdit()

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

        okBTN = Button("OK", action=updateSkull)
        cancel = Button("Cancel", action=panel.dismiss)

        column = [titleLabel, usernameField, skullMenu, okBTN, cancel]
        panel.add(Column(column))
        panel.shrink_wrap()
        panel.present()
Exemplo n.º 49
0
    def editSign(self, point):

        block = self.editor.level.blockAt(*point)
        tileEntity = self.editor.level.tileEntityAt(*point)
        undoBackupEntityTag = copy.deepcopy(tileEntity)

        linekeys = ["Text" + str(i) for i in range(1, 5)]

        if not tileEntity:
            tileEntity = pymclevel.TAG_Compound()
            tileEntity["id"] = pymclevel.TAG_String("Sign")
            tileEntity["x"] = pymclevel.TAG_Int(point[0])
            tileEntity["y"] = pymclevel.TAG_Int(point[1])
            tileEntity["z"] = pymclevel.TAG_Int(point[2])
            for l in linekeys:
                tileEntity[l] = pymclevel.TAG_String("")

        self.editor.level.addTileEntity(tileEntity)

        panel = Dialog()

        lineFields = [TextField(width=150) for l in linekeys]
        for l, f in zip(linekeys, lineFields):
            f.value = tileEntity[l].value

        colors = [
            "Black",
            "Blue",
            "Green",
            "Cyan",
            "Red",
            "Purple",
            "Yellow",
            "Light Gray",
            "Dark Gray",
            "Light Blue",
            "Bright Green",
            "Bright Blue",
            "Bright Red",
            "Bright Purple",
            "Bright Yellow",
            "White",
        ]

        def menu_picked(index):
            c = u'\xa7' + hex(index)[-1]
            currentField = panel.focus_switch.focus_switch
            currentField.text += c  # xxx view hierarchy
            currentField.insertion_point = len(currentField.text)

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

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

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

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

        def changeSign():
            unsavedChanges = False
            for l, f in zip(linekeys, lineFields):
                oldText = "{}".format(tileEntity[l])
                tileEntity[l] = pymclevel.TAG_String(f.value[:15])
                if "{}".format(tileEntity[l]) != oldText and not unsavedChanges:
                    unsavedChanges = True
            if unsavedChanges:
                op = SignEditOperation(self.editor, self.editor.level)
                self.editor.addOperation(op)
                if op.canUndo:
                    self.editor.addUnsavedEdit()
            panel.dismiss()

        colorMenu = mceutils.MenuButton("Color Code...", colors, menu_picked=menu_picked)

        column = [Label("Edit Sign")] + lineFields + [colorMenu, Button("OK", action=changeSign)]

        panel.add(Column(column))
        panel.shrink_wrap()
        panel.present()
Exemplo n.º 50
0
    def editContainer(self, point, containerID):
        tileEntityTag = self.editor.level.tileEntityAt(*point)
        if tileEntityTag is None:
            tileEntityTag = pymclevel.TileEntity.Create(containerID)
            pymclevel.TileEntity.setpos(tileEntityTag, point)
            self.editor.level.addTileEntity(tileEntityTag)

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

        undoBackupEntityTag = copy.deepcopy(tileEntityTag)

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

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

            return property(getter, setter)

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

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

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

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

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

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

        chestWidget.selectedItemIndex = 0

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        chestWidget.add(col)
        chestWidget.shrink_wrap()

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

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

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

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

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

        if chestWidget.dirty:
            op = ChestEditOperation(self.editor, self.editor.level)
            self.editor.addOperation(op)
            if op.canUndo:
                self.editor.addUnsavedEdit()
Exemplo n.º 51
0
 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)
     Dialog.dismiss(self, *args, **kwargs)
Exemplo n.º 52
0
    def __init__(self, prompt=None, suffixes=None, default_suffix=None, **kwds):
        Dialog.__init__(self, **kwds)
        label = None
        d = self.margin
        self.suffixes = suffixes or ("",)
        self.file_type = self.suffixes[0] # To be removed
        self.compute_file_types()
        self.default_suffix = default_suffix  # The default file extension. Will be searched in 'suffixes'.
        up_button = Button(self.up_button_text, action=self.go_up)
        dir_box = DirPathView(self.box_width + 250, self)
        self.dir_box = dir_box
        top_row = Row([dir_box, up_button])
        list_box = FileListView(self.box_width - 16, self)
        self.list_box = list_box
        tree = FSTree(self, inner_width=250, directory='/')
        self.tree = tree
        row = Row((tree, list_box), margin=0)
        ctrls = [top_row, row]
        prompt = prompt or self.default_prompt
        if prompt:
            label = Label(prompt)
        if suffixes:
            filetype_label = Label("File type", width=250)

            def set_file_type():
                self.file_type = self.filetype_button.get_value() # To be removed
                self.compute_file_types(self.filetype_button.get_value())
                self.list_box.update()

            filetype_button = ChoiceButton(choices=self.suffixes, width=250, choose=set_file_type)
            if default_suffix:
                v = next((s for s in self.suffixes if ("*.%s;"%default_suffix in s or "*.%s)"%default_suffix in s)), None)
                if v:
                    filetype_button.selectedChoice = v
                    self.compute_file_types(v)
            self.filetype_button = filetype_button
        if self.saving:
            filename_box = TextFieldWrapped(self.box_width)
            filename_box.change_action = self.update_filename
            filename_box._enter_action = filename_box.enter_action
            filename_box.enter_action = self.enter_action
            self.filename_box = filename_box
            if suffixes:
                ctrls.append(Row([Column([label, filename_box], align='l', spacing=0),
                                  Column([filetype_label, filetype_button], align='l', spacing=0)
                                  ],
                                 )
                             )
            else:
                ctrls.append(Column([label, filename_box], align='l', spacing=0))
        else:
            if label:
                ctrls.insert(0, label)
            if suffixes:
                ctrls.append(Column([filetype_label, filetype_button], align='l', spacing=0))
        ok_button = Button(self.ok_label, action=self.ok, enable=self.ok_enable)
        self.ok_button = ok_button
        cancel_button = Button("Cancel", action=self.cancel)
        vbox = Column(ctrls, align='l', spacing=d)
        vbox.topleft = (d, d)
        y = vbox.bottom + d
        ok_button.topleft = (vbox.left, y)
        cancel_button.topright = (vbox.right, y)
        self.add(vbox)
        self.add(ok_button)
        self.add(cancel_button)
        self.shrink_wrap()
        self._directory = None
        self.directory = os.getcwdu()
        #print "FileDialog: cwd =", repr(self.directory) ###
        if self.saving:
            filename_box.focus()