def __init__(self, macro_data, *args, **kw): self._parent = None self._macro_data = macro_data if '_parent' in kw.keys(): self._parent = kw.pop('_parent') Widget.__init__(self, *args, **kw) infoColList = [] stepsLabel = wrapped_label("Number of steps: %s" % macro_data["Number of steps"], 300) infoColList.append(stepsLabel) for step in sorted(macro_data.keys()): if step != "Number of steps": infoColList.append(wrapped_label("Step %s: %s" % (int(step) + 1, macro_data[step]["Name"]), 300)) self.add(Column(infoColList)) self.shrink_wrap()
class RootWidget(Widget): # surface Pygame display surface # is_gl True if OpenGL surface redraw_every_frame = False bonus_draw_time = 0 _is_gl_container = True def __init__(self, surface): global root_widget Widget.__init__(self, surface.get_rect()) self.surface = surface root_widget = self widget.root_widget = self self.is_gl = surface.get_flags() & OPENGL != 0 self.idle_handlers = [] self.dont = False self.shiftClicked = 0 self.shiftPlaced = -2 self.ctrlClicked = 0 self.ctrlPlaced = -2 self.altClicked = 0 self.altPlaced = -2 self.shiftAction = None self.altAction = None self.ctrlAction = None self.editor = None self.selectTool = None self.movementMath = [-1, 1, 1, -1, 1, -1] self.movementNum = [0, 0, 2, 2, 1, 1] self.notMove = [False, False, False, False, False, False] self.usedKeys = [False, False, False, False, False, False] self.cameraMath = [-1., 1., -1., 1.] self.cameraNum = [0, 0, 1, 1] self.notMoveCamera = [False, False, False, False] self.usedCameraKeys = [False, False, False, False] def get_nudge_block(self): return self.selectTool.panel.nudgeBlocksButton def set_timer(self, ms): pygame.time.set_timer(USEREVENT, ms) def run(self): self.run_modal(None) captured_widget = None def capture_mouse(self, widget): #put the mouse in "virtual mode" and pass mouse moved events to the #specified widget if widget: pygame.mouse.set_visible(False) pygame.event.set_grab(True) self.captured_widget = widget else: pygame.mouse.set_visible(True) pygame.event.set_grab(False) self.captured_widget = None frames = 0 hover_widget = None def fix_sticky_ctrl(self): self.ctrlClicked = -1 def run_modal(self, modal_widget): if self.editor is None: self.editor = self.mcedit.editor self.selectTool = self.editor.toolbar.tools[0] old_captured_widget = None if self.captured_widget: old_captured_widget = self.captured_widget self.capture_mouse(None) global last_mouse_event, last_mouse_event_handler global top_widget, clicked_widget is_modal = modal_widget is not None modal_widget = modal_widget or self from OpenGL import GL try: old_top_widget = top_widget top_widget = modal_widget was_modal = modal_widget.is_modal modal_widget.is_modal = True modal_widget.modal_result = None if not modal_widget.focus_switch: modal_widget.tab_to_first() mouse_widget = None if clicked_widget: clicked_widget = modal_widget num_clicks = 0 last_click_time = start_time last_click_button = 0 self.bonus_draw_time = 0 while modal_widget.modal_result is None: try: self.hover_widget = self.find_widget(pygame.mouse.get_pos()) if self.bonus_draw_time < 5: self.bonus_draw_time += 1 if self.is_gl: self.gl_clear() self.gl_draw_all(self, (0, 0)) GL.glFlush() else: self.draw_all(self.surface) pygame.display.flip() self.frames += 1 #events = [pygame.event.wait()] events = [pygame.event.poll()] events.extend(pygame.event.get()) if (self.shiftClicked >= 1 and self.mcedit.editor.focus_switch == None) or (self.shiftClicked >= 3 and self.mcedit.editor.focus_switch != None): events.append(self.shiftAction) self.shiftPlaced = len(events)-1 self.shiftClicked = 1 elif self.shiftClicked != 0: self.shiftClicked += 1 else: self.shiftPlaced = -2 if (self.altClicked >= 1 and self.mcedit.editor.focus_switch == None) or (self.altClicked >= 3 and self.mcedit.editor.focus_switch != None): events.append(self.altAction) self.altPlaced = len(events)-1 self.altClicked = 1 elif self.altClicked != 0: self.altClicked += 1 else: self.altPlaced = -2 if (self.ctrlClicked >= 1 and self.mcedit.editor.focus_switch == None) or (self.ctrlClicked >= 3 and self.mcedit.editor.focus_switch != None): events.append(self.ctrlAction) self.ctrlPlaced = len(events)-1 self.ctrlClicked = 1 elif self.ctrlClicked != 0: self.ctrlClicked += 1 else: self.ctrlPlaced = -2 i = 0 for event in events: #if event.type: #log.debug("%s", event) self.dont = False type = event.type if type == QUIT: self.quit() elif type == MOUSEBUTTONDOWN: self.bonus_draw_time = 0 t = datetime.now() if t - last_click_time <= double_click_time and event.button == last_click_button: num_clicks += 1 else: num_clicks = 1 last_click_button = event.button last_click_time = t event.dict['num_clicks'] = num_clicks add_modifiers(event) mouse_widget = self.find_widget(event.pos) if self.captured_widget: mouse_widget = self.captured_widget if not mouse_widget.is_inside(modal_widget): mouse_widget = modal_widget #if event.button == 1: clicked_widget = mouse_widget last_mouse_event_handler = mouse_widget last_mouse_event = event mouse_widget.notify_attention_loss() mouse_widget.handle_mouse('mouse_down', event) elif type == MOUSEMOTION: self.bonus_draw_time = 0 add_modifiers(event) modal_widget.dispatch_key('mouse_delta', event) last_mouse_event = event mouse_widget = self.update_tooltip(event.pos) if clicked_widget: last_mouse_event_handler = clicked_widget clicked_widget.handle_mouse('mouse_drag', event) else: if not mouse_widget.is_inside(modal_widget): mouse_widget = modal_widget last_mouse_event_handler = mouse_widget mouse_widget.handle_mouse('mouse_move', event) elif type == MOUSEBUTTONUP: add_modifiers(event) self.bonus_draw_time = 0 mouse_widget = self.find_widget(event.pos) if self.captured_widget: mouse_widget = self.captured_widget if clicked_widget: last_mouse_event_handler = clicked_widget event.dict['clicked_widget'] = clicked_widget else: last_mouse_event_handler = mouse_widget event.dict['clicked_widget'] = None last_mouse_event = event clicked_widget = None last_mouse_event_handler.handle_mouse('mouse_up', event) elif type == KEYDOWN: key = event.key temp = modkeys.get(key) if temp == 'shift': if self.shiftPlaced != i and self.shiftPlaced != -1: self.shiftClicked += 1 self.shiftAction = event elif self.shiftPlaced == -1: self.dont = True self.shiftPlaced = -2 elif temp == 'alt': if self.altPlaced != i and self.altPlaced != -1: self.altClicked += 1 self.altAction = event elif self.altPlaced == -1: self.dont = True self.altPlaced = -2 elif (temp == 'ctrl' or temp == 'meta'): if self.ctrlPlaced != i and self.ctrlPlaced != -1 and self.ctrlClicked != -1: self.ctrlClicked += 1 self.ctrlAction = event elif self.ctrlPlaced == -1 or self.ctrlClicked == -1: self.dont = True self.ctrlPlaced = -2 self.ctrlClicked = 0 if not self.dont: set_modifier(key, True) add_modifiers(event) self.bonus_draw_time = 0 levelExist = self.editor.level is not None keyname = event.dict.get('keyname', None) or self.getKey(event) if 'mouse' not in keyname and 'Mouse' not in keyname and self.editor.level: tempKeyname = self.getKey(event, True) for i, key in enumerate(self.editor.movements): if tempKeyname == key: if event.ctrl or event.meta: if self.usedKeys[i]: self.usedKeys[i] = False self.editor.cameraInputs[self.movementNum[i]] -= self.movementMath[i] self.notMove[i] = True elif not self.notMove[i]: self.notMove[i] = True elif not self.usedKeys[i]: self.changeMovementKeys(i, True, levelExist) for i, key in enumerate(self.editor.cameraPan): if tempKeyname == key: if event.ctrl or event.meta: if self.usedCameraKeys[i]: self.usedCameraKeys[i] = False self.editor.cameraPanKeys[self.cameraNum[i]] = self.cameraMath[i] self.notMoveCamera[i] = True elif not self.notMoveCamera[i]: self.notMoveCamera[i] = True elif not self.usedCameraKeys[i]: self.changeCameraKeys(i, True, levelExist) self.send_key(modal_widget, 'key_down', event) if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict['local'] = last_mouse_event.local last_mouse_event_handler.setup_cursor(event) elif type == KEYUP: key = event.key temp = modkeys.get(key) if temp == 'shift': self.shiftClicked = 0 self.shiftPlaced = -1 elif temp == 'alt': self.altClicked = 0 self.altPlaced = -1 elif temp == 'ctrl' or temp == 'meta': self.ctrlClicked = 0 self.ctrlPlaced = -1 set_modifier(key, False) add_modifiers(event) self.bonus_draw_time = 0 keyname = event.dict.get('keyname', None) or self.getKey(event) levelExist = self.editor.level is not None if 'mouse' not in keyname and 'Mouse' not in keyname: tempKeyname = self.getKey(event, True) for i, key in enumerate(self.editor.movements): if tempKeyname == key: self.changeMovementKeys(i, False, levelExist) for i, key in enumerate(self.editor.cameraPan): if tempKeyname == key: self.changeCameraKeys(i, False, levelExist) self.send_key(modal_widget, 'key_up', event) if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict['local'] = last_mouse_event.local last_mouse_event_handler.setup_cursor(event) elif type == MUSIC_END_EVENT: self.music_end() elif type == USEREVENT: make_scheduled_calls() if not is_modal: if self.redraw_every_frame: self.bonus_draw_time = 0 else: self.bonus_draw_time += 1 if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict['local'] = last_mouse_event.local add_modifiers(event) last_mouse_event_handler.setup_cursor(event) self.begin_frame() elif type == VIDEORESIZE: #add_modifiers(event) self.bonus_draw_time = 0 self.size = (event.w, event.h) #self.dispatch_key('reshape', event) elif type == ACTIVEEVENT: add_modifiers(event) self.dispatch_key('activeevent', event) elif type == NOEVENT: add_modifiers(event) self.call_idle_handlers(event) i+=1 except Cancel: pass finally: modal_widget.is_modal = was_modal top_widget = old_top_widget if old_captured_widget: self.capture_mouse(old_captured_widget) clicked_widget = None def getKey(self, evt, movement=False): keyname = key.name(evt.key) if 'left' in keyname and len(keyname) > 5: keyname = keyname[5:] elif 'right' in keyname and len(keyname) > 6: keyname = keyname[6:] try: keyname = keyname.replace(keyname[0], keyname[0].upper(), 1) finally: if keyname == 'Meta': keyname = 'Ctrl' newKeyname = "" if evt.shift and keyname != "Shift" and not movement: newKeyname += "Shift-" if (evt.ctrl or evt.cmd) and keyname != "Ctrl" and not movement: newKeyname += "Ctrl-" if evt.alt and keyname != "Alt" and not movement: newKeyname += "Alt-" keyname = newKeyname + keyname if keyname == 'Enter': keyname = 'Return' return keyname def changeMovementKeys(self, keyNum, keyDown, levelExist): if not self.notMove[keyNum]: self.usedKeys[keyNum] = keyDown if keyDown: if levelExist: self.editor.cameraInputs[self.movementNum[keyNum]] += self.movementMath[keyNum] self.notMove[keyNum] = False else: if levelExist: self.editor.cameraInputs[self.movementNum[keyNum]] -= self.movementMath[keyNum] return self.notMove[keyNum] = keyDown def changeCameraKeys(self, keyNum, keyDown, levelExist): if not self.notMoveCamera[keyNum]: self.usedCameraKeys[keyNum] = keyDown if keyDown: if levelExist: self.editor.cameraPanKeys[self.cameraNum[keyNum]] = self.cameraMath[keyNum] else: if levelExist: self.editor.cameraPanKeys[self.cameraNum[keyNum]] = 0. self.notMoveCamera[keyNum] = False return self.notMoveCamera[keyNum] = keyDown def handling_ctrl(self, event): levelExist = self.editor.level is not None keyname = event.dict.get('keyname', None) or self.getKey(event) if 'mouse' not in keyname and 'Mouse' not in keyname and self.editor.level: tempKeyname = self.getKey(event, True) for i, key in enumerate(self.editor.movements): if tempKeyname == key: if self.usedKeys[i]: self.usedKeys[i] = False self.editor.cameraInputs[self.movementNum[i]] -= self.movementMath[i] self.notMove[i] = True elif not self.notMove[i]: self.notMove[i] = True for i, key in enumerate(self.editor.cameraPan): if tempKeyname == key: if self.usedCameraKeys[i]: self.usedCameraKeys[i] = False self.editor.cameraPanKeys[self.cameraNum[i]] = 0. self.notMoveCamera[i] = True elif not self.notMoveCamera[i]: self.notMoveCamera[i] = True def call_idle_handlers(self, event): def call(ref): widget = ref() if widget: widget.idleevent(event) else: print "Idle ref died!" return bool(widget) self.idle_handlers = filter(call, self.idle_handlers) def add_idle_handler(self, widget): from weakref import ref self.idle_handlers.append(ref(widget)) def remove_idle_handler(self, widget): from weakref import ref self.idle_handlers.remove(ref(widget)) def send_key(self, widget, name, event): widget.dispatch_key(name, event) def begin_frame(self): pass def get_root(self): return self labelClass = lambda s, t: wrapped_label(t, 45) def show_tooltip(self, widget, pos): if hasattr(self, 'currentTooltip'): if self.currentTooltip != None: self.remove(self.currentTooltip) self.currentTooltip = None def TextTooltip(text): tooltipBacking = Panel() tooltipBacking.bg_color = (0.0, 0.0, 0.0, 0.6) tooltipBacking.add(self.labelClass(text)) tooltipBacking.shrink_wrap() return tooltipBacking def showTip(tip): tip.topleft = pos tip.top += 20 if (tip.bottom > self.bottom) or hasattr(widget, 'tooltipsUp'): tip.bottomleft = pos tip.top -= 4 if tip.right > self.right: tip.right = pos[0] self.add(tip) self.currentTooltip = tip if widget.tooltip is not None: tip = widget.tooltip showTip(tip) else: ttext = widget.tooltipText if ttext is not None: tip = TextTooltip(ttext) showTip(tip) def update_tooltip(self, pos=None): if pos is None: pos = pygame.mouse.get_pos() if self.captured_widget: mouse_widget = self.captured_widget pos = mouse_widget.center else: mouse_widget = self.find_widget(pos) self.show_tooltip(mouse_widget, pos) return mouse_widget def has_focus(self): return True def quit(self): if self.confirm_quit(): self.capture_mouse(None) sys.exit(0) def confirm_quit(self): return True def get_mouse_for(self, widget): last = last_mouse_event event = Event(0, last.dict) event.dict['local'] = widget.global_to_local(event.pos) add_modifiers(event) return event def gl_clear(self): from OpenGL import GL bg = self.bg_color if bg: r = bg[0] / 255.0 g = bg[1] / 255.0 b = bg[2] / 255.0 GL.glClearColor(r, g, b, 0.0) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) def music_end(self): import music music.music_end()
def remove_idle_handler(self, widget): from weakref import ref self.idle_handlers.remove(ref(widget)) @staticmethod def send_key(widget, name, event): widget.dispatch_key(name, event) def begin_frame(self): pass def get_root(self): return self labelClass = lambda s, t: wrapped_label(t, 45) def show_tooltip(self, widget, pos): if hasattr(self, 'currentTooltip'): if self.currentTooltip is not None: self.remove(self.currentTooltip) self.currentTooltip = None def TextTooltip(text): tooltipBacking = Panel() tooltipBacking.bg_color = (0.0, 0.0, 0.0, 0.8) tooltipBacking.add(self.labelClass(text)) tooltipBacking.shrink_wrap() return tooltipBacking
def makeTabPage(self, tool, inputs): page = Widget() page.is_gl_container = True rows = [] cols = [] height = 0 max_height = 550 page.optionDict = {} page.tool = tool title = "Tab" for optionName, optionType in inputs: if isinstance(optionType, tuple): if isinstance(optionType[0], (int, long, float)): if len(optionType) > 2: val, min, max = optionType elif len(optionType) == 2: min, max = optionType val = min rows.append(addNumField(page, optionName, val, min, max)) if isinstance(optionType[0], (str, unicode)): isChoiceButton = False if optionType[0] == "string": kwds = [] wid = None val = None for keyword in optionType: if isinstance(keyword, (str, unicode)) and keyword != "string": kwds.append(keyword) for keyword in kwds: splitWord = keyword.split('=') if len(splitWord) > 1: v = None key = None try: v = int(splitWord[1]) except: pass key = splitWord[0] if v is not None: if key == "lines": lin = v elif key == "width": wid = v else: if key == "value": val = splitWord[1] if val is None: val = "" if wid is None: wid = 200 field = TextField(value=val, width=wid) page.optionDict[optionName] = AttrRef(field, 'value') row = Row((Label(optionName), field)) rows.append(row) else: isChoiceButton = True if isChoiceButton: choiceButton = ChoiceButton(map(str, optionType)) page.optionDict[optionName] = AttrRef(choiceButton, 'selectedChoice') rows.append(Row((Label(optionName), choiceButton))) elif isinstance(optionType, bool): cbox = CheckBox(value=optionType) page.optionDict[optionName] = AttrRef(cbox, 'value') row = Row((Label(optionName), cbox)) rows.append(row) elif isinstance(optionType, (int, float)): rows.append(addNumField(self, optionName, optionType)) elif optionType == "blocktype" or isinstance(optionType, pymclevel.materials.Block): blockButton = BlockButton(tool.editor.level.materials) if isinstance(optionType, pymclevel.materials.Block): blockButton.blockInfo = optionType row = Column((Label(optionName), blockButton)) page.optionDict[optionName] = AttrRef(blockButton, 'blockInfo') rows.append(row) elif optionType == "label": rows.append(wrapped_label(optionName, 50)) elif optionType == "string": input = None # not sure how to pull values from filters, but leaves it open for the future. Use this variable to set field width. if input != None: size = input else: size = 200 field = TextField(value="") row = TextInputRow(optionName, ref=AttrRef(field, 'value'), width=size) page.optionDict[optionName] = AttrRef(field, 'value') rows.append(row) elif optionType == "title": title = optionName else: raise ValueError(("Unknown option type", optionType)) height = sum(r.height for r in rows) if height > max_height: h = 0 for i, r in enumerate(rows): h += r.height if h > height / 2: break cols.append(Column(rows[:i])) rows = rows[i:] # cols.append(Column(rows)) if len(rows): cols.append(Column(rows)) if len(cols): page.add(Row(cols)) page.shrink_wrap() return (title, page, page._rect)
def makeTabPage(self, tool, inputs, trn=None, **kwargs): page = Widget(**kwargs) page.is_gl_container = True rows = [] cols = [] max_height = tool.editor.mainViewport.height - tool.editor.toolbar.height - tool.editor.subwidgets[0].height -\ self._parent.filterSelectRow.height - self._parent.confirmButton.height - self.pages.tab_height page.optionDict = {} page.tool = tool title = "Tab" for optionSpec in inputs: optionName = optionSpec[0] optionType = optionSpec[1] if trn is not None: n = trn._(optionName) else: n = optionName if n == optionName: oName = _(optionName) else: oName = n if isinstance(optionType, tuple): if isinstance(optionType[0], (int, long, float)): if len(optionType) == 3: val, min, max = optionType increment = 0.1 elif len(optionType) == 2: min, max = optionType val = min increment = 0.1 else: val, min, max, increment = optionType rows.append( addNumField(page, optionName, oName, val, min, max, increment)) if isinstance(optionType[0], (str, unicode)): isChoiceButton = False if optionType[0] == "string": kwds = [] wid = None val = None for keyword in optionType: if isinstance( keyword, (str, unicode)) and keyword != "string": kwds.append(keyword) for keyword in kwds: splitWord = keyword.split('=') if len(splitWord) > 1: v = None try: v = int(splitWord[1]) except ValueError: pass key = splitWord[0] if v is not None: if key == "width": wid = v else: if key == "value": val = "=".join(splitWord[1:]) if val is None: val = "" if wid is None: wid = 200 field = TextFieldWrapped(value=val, width=wid) page.optionDict[optionName] = AttrRef(field, 'value') row = Row((Label(oName, doNotTranslate=True), field)) rows.append(row) else: isChoiceButton = True if isChoiceButton: if trn is not None: __ = trn._ else: __ = _ choices = [__("%s" % a) for a in optionType] choiceButton = ChoiceButton(choices, doNotTranslate=True) page.optionDict[optionName] = AttrRef( choiceButton, 'selectedChoice') rows.append( Row((Label(oName, doNotTranslate=True), choiceButton))) elif isinstance(optionType, bool): cbox = CheckBox(value=optionType) page.optionDict[optionName] = AttrRef(cbox, 'value') row = Row((Label(oName, doNotTranslate=True), cbox)) rows.append(row) elif isinstance(optionType, (int, float)): rows.append(addNumField(self, optionName, oName, optionType)) elif optionType == "blocktype" or isinstance( optionType, pymclevel.materials.Block): blockButton = BlockButton(tool.editor.level.materials) if isinstance(optionType, pymclevel.materials.Block): blockButton.blockInfo = optionType row = Column((Label(oName, doNotTranslate=True), blockButton)) page.optionDict[optionName] = AttrRef(blockButton, 'blockInfo') rows.append(row) elif optionType == "label": rows.append(wrapped_label(oName, 50, doNotTranslate=True)) elif optionType == "string": inp = None # not sure how to pull values from filters, # but leaves it open for the future. Use this variable to set field width. if inp is not None: size = inp else: size = 200 field = TextFieldWrapped(value="") row = TextInputRow(oName, ref=AttrRef(field, 'value'), width=size, doNotTranslate=True) page.optionDict[optionName] = AttrRef(field, 'value') rows.append(row) elif optionType == "title": title = oName elif type( optionType) == list and optionType[0].lower() == "nbttree": kw = {'close_text': None, 'load_text': None} if len(optionType) >= 3: def close(): self.pages.show_page(self.pages.pages[optionType[2]]) kw['close_action'] = close kw['close_text'] = "Go Back" if len(optionType) >= 4: if optionType[3]: kw['load_text'] = optionType[3] if hasattr(self.module, 'nbt_ok_action'): kw['ok_action'] = getattr(self.module, 'nbt_ok_action') self.nbttree = NBTExplorerToolPanel(self.tool.editor, nbtObject=optionType[1], height=max_height, no_header=True, copy_data=False, **kw) self.module.set_tree(self.nbttree.tree) for meth_name in dir(self.module): if meth_name.startswith('nbttree_'): setattr(self.nbttree.tree.treeRow, meth_name.split('nbttree_')[-1], getattr(self.module, meth_name)) # elif meth_name.startswith('nbt_'): # setattr(self.nbttree, meth_name.split('nbt_')[-1], getattr(self.module, meth_name)) page.optionDict[optionName] = AttrRef(self, 'rebuildTabPage') rows.append(self.nbttree) self.nbttree.page = len(self.pgs) else: raise ValueError(("Unknown option type", optionType)) height = sum(r.height for r in rows) + (len(rows) - 1) * self.spacing if height > max_height: h = 0 for i, r in enumerate(rows): h += r.height if h > height / 2: if rows[:i]: cols.append(Column(rows[:i], spacing=0)) rows = rows[i:] break if len(rows): cols.append(Column(rows, spacing=0)) if len(cols): page.add(Row(cols, spacing=0)) page.shrink_wrap() return title, page, page._rect
class RootWidget(Widget): # surface Pygame display surface # is_gl True if OpenGL surface redraw_every_frame = False bonus_draw_time = False _is_gl_container = True def __init__(self, surface): global root_widget Widget.__init__(self, surface.get_rect()) self.surface = surface root_widget = self widget.root_widget = self self.is_gl = surface.get_flags() & OPENGL != 0 self.idle_handlers = [] self.editor = None self.selectTool = None self.movementMath = [-1, 1, 1, -1, 1, -1] self.movementNum = [0, 0, 2, 2, 1, 1] self.cameraMath = [-1., 1., -1., 1.] self.cameraNum = [0, 0, 1, 1] self.notMove = False self.nudge = None self.testTime = None self.testTimeBack = 0.4 self.nudgeDirection = None self.sessionStolen = False self.sprint = False self.filesToChange = [] def get_nudge_block(self): return self.selectTool.panel.nudgeBlocksButton def take_screenshot(self): try: os.mkdir(os.path.join(directories.getCacheDir(), "screenshots")) except OSError: pass screenshot_name = os.path.join( directories.getCacheDir(), "screenshots", time.strftime("%Y-%m-%d (%I-%M-%S-%p)") + ".png") pygame.image.save(pygame.display.get_surface(), screenshot_name) self.diag = Dialog() lbl = Label(_("Screenshot taken and saved as '%s'") % screenshot_name, doNotTranslate=True) folderBtn = Button("Open Folder", action=self.open_screenshots_folder) btn = Button("Ok", action=self.screenshot_notify) buttonsRow = Row((btn, folderBtn)) col = Column((lbl, buttonsRow)) self.diag.add(col) self.diag.shrink_wrap() self.diag.present() def open_screenshots_folder(self): from mcplatform import platform_open platform_open(os.path.join(directories.getCacheDir(), "screenshots")) self.screenshot_notify() def screenshot_notify(self): self.diag.dismiss() @staticmethod def set_timer(ms): pygame.time.set_timer(USEREVENT, ms) def run(self): self.run_modal(None) captured_widget = None def capture_mouse(self, widget): # put the mouse in "virtual mode" and pass mouse moved events to the # specified widget if widget: pygame.mouse.set_visible(False) pygame.event.set_grab(True) self.captured_widget = widget else: pygame.mouse.set_visible(True) pygame.event.set_grab(False) self.captured_widget = None frames = 0 hover_widget = None def fix_sticky_ctrl(self): self.ctrlClicked = -1 def run_modal(self, modal_widget): if self.editor is None: self.editor = self.mcedit.editor self.selectTool = self.editor.toolbar.tools[0] old_captured_widget = None if self.captured_widget: old_captured_widget = self.captured_widget self.capture_mouse(None) global last_mouse_event, last_mouse_event_handler global top_widget, clicked_widget is_modal = modal_widget is not None modal_widget = modal_widget or self #from OpenGL import GL try: old_top_widget = top_widget top_widget = modal_widget was_modal = modal_widget.is_modal modal_widget.is_modal = True modal_widget.modal_result = None if not modal_widget.focus_switch: modal_widget.tab_to_first() if clicked_widget: clicked_widget = modal_widget num_clicks = 0 last_click_time = start_time last_click_button = False self.bonus_draw_time = False while modal_widget.modal_result is None: try: if not self.mcedit.version_checked: if not self.mcedit.version_lock.locked(): self.mcedit.version_checked = True self.mcedit.check_for_version() self.hover_widget = self.find_widget( pygame.mouse.get_pos()) if not self.bonus_draw_time: self.bonus_draw_time = True if self.is_gl: self.gl_clear() self.gl_draw_all(self, (0, 0)) GL.glFlush() else: self.draw_all(self.surface) pygame.display.flip() self.frames += 1 events = pygame.event.get() if not events: self.call_idle_handlers() for event in events: type = event.type if type == QUIT: self.quit() elif type == MOUSEBUTTONDOWN: self.bonus_draw_time = False t = datetime.now() if t - last_click_time <= double_click_time and event.button == last_click_button: num_clicks += 1 else: num_clicks = 1 last_click_button = event.button last_click_time = t event.dict['num_clicks'] = num_clicks add_modifiers(event) mouse_widget = self.find_widget(event.pos) if self.captured_widget: mouse_widget = self.captured_widget if not mouse_widget.is_inside(modal_widget): mouse_widget = modal_widget clicked_widget = mouse_widget last_mouse_event_handler = mouse_widget last_mouse_event = event mouse_widget.notify_attention_loss() mouse_widget.handle_mouse('mouse_down', event) elif type == MOUSEMOTION: self.bonus_draw_time = False add_modifiers(event) modal_widget.dispatch_key('mouse_delta', event) last_mouse_event = event mouse_widget = self.update_tooltip(event.pos) if clicked_widget: last_mouse_event_handler = clicked_widget clicked_widget.handle_mouse( 'mouse_drag', event) else: if not mouse_widget.is_inside(modal_widget): mouse_widget = modal_widget last_mouse_event_handler = mouse_widget mouse_widget.handle_mouse('mouse_move', event) elif type == MOUSEBUTTONUP: add_modifiers(event) self.bonus_draw_time = False mouse_widget = self.find_widget(event.pos) if self.captured_widget: mouse_widget = self.captured_widget if clicked_widget: last_mouse_event_handler = clicked_widget event.dict['clicked_widget'] = clicked_widget else: last_mouse_event_handler = mouse_widget event.dict['clicked_widget'] = None last_mouse_event = event clicked_widget = None last_mouse_event_handler.handle_mouse( 'mouse_up', event) elif type == KEYDOWN: key_down = event.key set_modifier(key_down, True) add_modifiers(event) self.bonus_draw_time = False keyname = self.getKey(event) if keyname == config.keys.takeAScreenshot.get(): self.take_screenshot() self.send_key(modal_widget, 'key_down', event) if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict['local'] = last_mouse_event.local last_mouse_event_handler.setup_cursor(event) elif type == KEYUP: key_up = event.key set_modifier(key_up, False) add_modifiers(event) self.bonus_draw_time = False keyname = self.getKey(event) if keyname == config.keys.showBlockInfo.get( ) and self.editor.toolbar.tools[0].infoKey == 1: self.editor.toolbar.tools[0].infoKey = 0 self.editor.mainViewport.showCommands() if self.nudgeDirection is not None: keyname = self.getKey(movement=True, keyname=key.name(key_up)) for i, move_key in enumerate( self.editor.movements): if keyname == move_key and i == self.nudgeDirection: self.nudgeDirection = None self.testTime = None self.testTimeBack = 0.4 self.send_key(modal_widget, 'key_up', event) if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict['local'] = last_mouse_event.local last_mouse_event_handler.setup_cursor(event) elif type == MUSIC_END_EVENT: self.music_end() elif type == USEREVENT: make_scheduled_calls() if not is_modal: if self.redraw_every_frame: self.bonus_draw_time = False else: self.bonus_draw_time = True if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict[ 'local'] = last_mouse_event.local add_modifiers(event) last_mouse_event_handler.setup_cursor( event) self.begin_frame() elif type == VIDEORESIZE: self.bonus_draw_time = False self.size = (event.w, event.h) elif type == VIDEOEXPOSE: if self.mcedit.displayContext.win and self.mcedit.displayContext.win.get_state( ) == 1: x, y = config.settings.windowX.get( ), config.settings.windowY.get() pos = self.mcedit.displayContext.win.get_position( ) if pos[0] != x: config.settings.windowX.set(pos[0]) if pos[1] != y: config.settings.windowY.set(pos[1]) elif type == ACTIVEEVENT: add_modifiers(event) self.dispatch_key('activeevent', event) if not self.sessionStolen: try: if self.editor.level is not None and hasattr( self.editor.level, "checkSessionLock"): self.editor.level.checkSessionLock() except Exception as e: log.warn(u"Error reading chunk (?): %s", e) if not config.session.override.get(): self.sessionStolen = True else: self.editor.level.acquireSessionLock() if self.editor.level is not None: self.editor.cameraInputs = [0., 0., 0., 0., 0., 0.] self.editor.cameraPanKeys = [0., 0., 0., 0.] def useKeys(i): keyName = self.getKey(movement=True, keyname=key.name(i)) if keyName == self.editor.sprintKey: self.sprint = True if allKeys[K_LCTRL] or allKeys[K_RCTRL] or allKeys[ K_RMETA] or allKeys[K_LMETA]: return if keyName in self.editor.movements: self.changeMovementKeys( self.editor.movements.index(keyName), keyName) if keyName in self.editor.cameraPan: self.changeCameraKeys( self.editor.cameraPan.index(keyName)) allKeys = key.get_pressed() for x in enumerate(allKeys): if x[1]: useKeys(x[0]) for edit in self.filesToChange: newTime = os.path.getmtime(edit.filename) if newTime > edit.timeChanged: edit.timeChanged = newTime edit.makeChanges() except Cancel: pass finally: modal_widget.is_modal = was_modal top_widget = old_top_widget if old_captured_widget: self.capture_mouse(old_captured_widget) clicked_widget = None @staticmethod def getKey(evt=None, movement=False, keyname=None): if keyname is None: keyname = key.name(evt.key) keyname = keyname.replace("right ", "").replace("left ", "").replace( "Meta", "Ctrl").replace("Enter", "Return").replace("Delete", "Del") try: keyname = keyname.replace(keyname[0], keyname[0].upper(), 1) except: pass if movement: return keyname newKeyname = "" if evt.shift and keyname != "Shift": newKeyname += "Shift-" if (evt.ctrl or evt.cmd) and keyname != "Ctrl": newKeyname += "Ctrl-" if evt.alt and keyname != "Alt": newKeyname += "Alt-" keyname = newKeyname + keyname if newKeyname: return keyname if sys.platform == 'linux2': test_key = getattr(evt, 'scancode', None) tool_keys = [10, 11, 12, 13, 14, 15, 16, 17, 18] else: test_key = keyname tool_keys = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] if test_key in tool_keys: keyname = str(tool_keys.index(test_key) + 1) elif test_key == 19: keyname = '0' return keyname def changeMovementKeys(self, keyNum, keyname): if self.editor.level is not None and not self.notMove: self.editor.cameraInputs[ self.movementNum[keyNum]] += self.movementMath[keyNum] elif self.notMove and self.nudge is not None and ( self.testTime is None or datetime.now() - self.testTime >= timedelta(seconds=self.testTimeBack)): if self.testTimeBack > 0.1: self.testTimeBack -= 0.1 self.bonus_draw_time = False self.testTime = datetime.now() if keyname == self.editor.movements[4]: self.nudge.nudge(Vector(0, 1, 0)) if keyname == self.editor.movements[5]: self.nudge.nudge(Vector(0, -1, 0)) Z = self.editor.mainViewport.cameraVector absZ = map(abs, Z) if absZ[0] < absZ[2]: forward = (0, 0, (-1 if Z[2] < 0 else 1)) else: forward = ((-1 if Z[0] < 0 else 1), 0, 0) back = map(int.__neg__, forward) left = forward[2], forward[1], -forward[0] right = map(int.__neg__, left) if keyname == self.editor.movements[2]: self.nudge.nudge(Vector(*forward)) if keyname == self.editor.movements[3]: self.nudge.nudge(Vector(*back)) if keyname == self.editor.movements[0]: self.nudge.nudge(Vector(*left)) if keyname == self.editor.movements[1]: self.nudge.nudge(Vector(*right)) for i, move_key in enumerate(self.editor.movements): if move_key == keyname: self.nudgeDirection = i def changeCameraKeys(self, keyNum): if self.editor.level is not None and not self.notMove: self.editor.cameraPanKeys[ self.cameraNum[keyNum]] = self.cameraMath[keyNum] def RemoveEditFiles(self): self.filesToChange = [] def call_idle_handlers(self): def call(ref): widget = ref() if widget: widget.idleevent() else: print "Idle ref died!" return bool(widget) self.idle_handlers = filter(call, self.idle_handlers) def add_idle_handler(self, widget): from weakref import ref self.idle_handlers.append(ref(widget)) def remove_idle_handler(self, widget): from weakref import ref self.idle_handlers.remove(ref(widget)) @staticmethod def send_key(widget, name, event): widget.dispatch_key(name, event) def begin_frame(self): pass def get_root(self): return self labelClass = lambda s, t: wrapped_label(t, 45) def show_tooltip(self, widget, pos): if hasattr(self, 'currentTooltip'): if self.currentTooltip is not None: self.remove(self.currentTooltip) self.currentTooltip = None def TextTooltip(text, name): tooltipBacking = Panel(name=name) tooltipBacking.bg_color = (0.0, 0.0, 0.0, 0.8) tooltipBacking.add(self.labelClass(text)) tooltipBacking.shrink_wrap() return tooltipBacking def showTip(tip): tip.topleft = pos tip.top += 20 if (tip.bottom > self.bottom) or hasattr(widget, 'tooltipsUp'): tip.bottomleft = pos tip.top -= 4 if tip.right > self.right: tip.right = pos[0] self.add(tip) self.currentTooltip = tip if widget.tooltip is not None: tip = widget.tooltip showTip(tip) else: ttext = widget.tooltipText if ttext is not None: tip = TextTooltip(ttext, 'Panel.%s' % (repr(widget))) showTip(tip) def update_tooltip(self, pos=None): if pos is None: pos = pygame.mouse.get_pos() if self.captured_widget: mouse_widget = self.captured_widget pos = mouse_widget.center else: mouse_widget = self.find_widget(pos) self.show_tooltip(mouse_widget, pos) return mouse_widget def has_focus(self): return True def quit(self): if self.confirm_quit(): self.capture_mouse(None) sys.exit(0) @staticmethod def confirm_quit(): return True @staticmethod def get_mouse_for(widget): last = last_mouse_event event = Event(0, last.dict) event.dict['local'] = widget.global_to_local(event.pos) add_modifiers(event) return event def gl_clear(self): #from OpenGL import GL bg = self.bg_color if bg: r = bg[0] / 255.0 g = bg[1] / 255.0 b = bg[2] / 255.0 GL.glClearColor(r, g, b, 0.0) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) @staticmethod def music_end(): import music music.music_end()
class RootWidget(Widget): # surface Pygame display surface # is_gl True if OpenGL surface redraw_every_frame = False do_draw = False _is_gl_container = True def __init__(self, surface): global root_widget Widget.__init__(self, surface.get_rect()) self.surface = surface root_widget = self widget.root_widget = self self.is_gl = surface.get_flags() & OPENGL != 0 self.idle_handlers = [] def set_timer(self, ms): pygame.time.set_timer(USEREVENT, ms) def run(self): self.run_modal(None) captured_widget = None def capture_mouse(self, widget): #put the mouse in "virtual mode" and pass mouse moved events to the #specified widget if widget: pygame.mouse.set_visible(False) pygame.event.set_grab(True) get_root().captured_widget = widget else: pygame.mouse.set_visible(True) pygame.event.set_grab(False) get_root().captured_widget = None frames = 0 hover_widget = None def run_modal(self, modal_widget): old_captured_widget = None if self.captured_widget: old_captured_widget = self.captured_widget self.capture_mouse(None) global last_mouse_event, last_mouse_event_handler global top_widget, clicked_widget is_modal = modal_widget is not None modal_widget = modal_widget or self from OpenGL import GL try: old_top_widget = top_widget top_widget = modal_widget was_modal = modal_widget.is_modal modal_widget.is_modal = True modal_widget.modal_result = None if not modal_widget.focus_switch: modal_widget.tab_to_first() mouse_widget = None if clicked_widget: clicked_widget = modal_widget num_clicks = 0 last_click_time = start_time last_click_button = 0 self.do_draw = True while modal_widget.modal_result is None: try: self.hover_widget = self.find_widget(mouse.get_pos()) if self.do_draw: if self.is_gl: self.gl_clear() self.gl_draw_all(self, (0, 0)) GL.glFlush() else: self.draw_all(self.surface) self.do_draw = False pygame.display.flip() self.frames += 1 #events = [pygame.event.wait()] events = [pygame.event.poll()] events.extend(pygame.event.get()) for event in events: #if event.type: #log.debug("%s", event) type = event.type if type == QUIT: self.quit() elif type == MOUSEBUTTONDOWN: self.do_draw = True t = datetime.now() if t - last_click_time <= double_click_time and event.button == last_click_button: num_clicks += 1 else: num_clicks = 1 last_click_button = event.button last_click_time = t event.dict['num_clicks'] = num_clicks add_modifiers(event) mouse_widget = self.find_widget(event.pos) if self.captured_widget: mouse_widget = self.captured_widget if not mouse_widget.is_inside(modal_widget): mouse_widget = modal_widget #if event.button == 1: clicked_widget = mouse_widget last_mouse_event_handler = mouse_widget last_mouse_event = event mouse_widget.notify_attention_loss() mouse_widget.handle_mouse('mouse_down', event) elif type == MOUSEMOTION: self.do_draw = True add_modifiers(event) modal_widget.dispatch_key('mouse_delta', event) last_mouse_event = event mouse_widget = self.update_tooltip(event.pos) if clicked_widget: last_mouse_event_handler = clicked_widget clicked_widget.handle_mouse( 'mouse_drag', event) else: if not mouse_widget.is_inside(modal_widget): mouse_widget = modal_widget last_mouse_event_handler = mouse_widget mouse_widget.handle_mouse('mouse_move', event) elif type == MOUSEBUTTONUP: add_modifiers(event) self.do_draw = True mouse_widget = self.find_widget(event.pos) if self.captured_widget: mouse_widget = self.captured_widget if clicked_widget: last_mouse_event_handler = clicked_widget event.dict['clicked_widget'] = clicked_widget else: last_mouse_event_handler = mouse_widget event.dict['clicked_widget'] = None last_mouse_event = event clicked_widget = None last_mouse_event_handler.handle_mouse( 'mouse_up', event) elif type == KEYDOWN: key = event.key set_modifier(key, True) self.do_draw = True self.send_key(modal_widget, 'key_down', event) if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict['local'] = last_mouse_event.local last_mouse_event_handler.setup_cursor(event) elif type == KEYUP: key = event.key set_modifier(key, False) self.do_draw = True self.send_key(modal_widget, 'key_up', event) if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict['local'] = last_mouse_event.local last_mouse_event_handler.setup_cursor(event) elif type == MUSIC_END_EVENT: self.music_end() elif type == USEREVENT: make_scheduled_calls() if not is_modal: self.do_draw = self.redraw_every_frame if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict[ 'local'] = last_mouse_event.local add_modifiers(event) last_mouse_event_handler.setup_cursor( event) self.begin_frame() elif type == VIDEORESIZE: #add_modifiers(event) self.do_draw = True self.size = (event.w, event.h) #self.dispatch_key('reshape', event) elif type == ACTIVEEVENT: add_modifiers(event) self.dispatch_key('activeevent', event) elif type == NOEVENT: add_modifiers(event) self.call_idle_handlers(event) except Cancel: pass finally: modal_widget.is_modal = was_modal top_widget = old_top_widget if old_captured_widget: self.capture_mouse(old_captured_widget) clicked_widget = None def call_idle_handlers(self, event): def call(ref): widget = ref() if widget: widget.idleevent(event) else: print "Idle ref died!" return bool(widget) self.idle_handlers = filter(call, self.idle_handlers) def add_idle_handler(self, widget): from weakref import ref self.idle_handlers.append(ref(widget)) def remove_idle_handler(self, widget): from weakref import ref self.idle_handlers.remove(ref(widget)) def send_key(self, widget, name, event): add_modifiers(event) widget.dispatch_key(name, event) def begin_frame(self): pass def get_root(self): return self labelClass = lambda s, t: wrapped_label(t, 45) def show_tooltip(self, widget, pos): if hasattr(self, 'currentTooltip'): if self.currentTooltip != None: self.remove(self.currentTooltip) self.currentTooltip = None def TextTooltip(text): tooltipBacking = Panel() tooltipBacking.bg_color = (0.0, 0.0, 0.0, 0.6) tooltipBacking.add(self.labelClass(text)) tooltipBacking.shrink_wrap() return tooltipBacking def showTip(tip): tip.topleft = pos tip.top += 20 if (tip.bottom > self.bottom) or hasattr(widget, 'tooltipsUp'): tip.bottomleft = pos tip.top -= 4 if tip.right > self.right: tip.right = pos[0] self.add(tip) self.currentTooltip = tip if widget.tooltip is not None: tip = widget.tooltip showTip(tip) else: ttext = widget.tooltipText if ttext is not None: tip = TextTooltip(ttext) showTip(tip) def update_tooltip(self, pos=None): if pos is None: pos = mouse.get_pos() if self.captured_widget: mouse_widget = self.captured_widget pos = mouse_widget.center else: mouse_widget = self.find_widget(pos) self.show_tooltip(mouse_widget, pos) return mouse_widget def has_focus(self): return True def quit(self): if self.confirm_quit(): self.capture_mouse(None) sys.exit(0) def confirm_quit(self): return True def get_mouse_for(self, widget): last = last_mouse_event event = Event(0, last.dict) event.dict['local'] = widget.global_to_local(event.pos) add_modifiers(event) return event def gl_clear(self): from OpenGL import GL bg = self.bg_color if bg: r = bg[0] / 255.0 g = bg[1] / 255.0 b = bg[2] / 255.0 GL.glClearColor(r, g, b, 0.0) GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) def music_end(self): import music music.music_end()
def makeTabPage(self, tool, inputs, trn=None, **kwargs): page = Widget(**kwargs) page.is_gl_container = True rows = [] cols = [] max_height = tool.editor.mainViewport.height - tool.editor.toolbar.height - tool.editor.subwidgets[0].height -\ self._parent.filterSelectRow.height - self._parent.confirmButton.height - self.pages.tab_height page.optionDict = {} page.tool = tool title = "Tab" for optionSpec in inputs: optionName = optionSpec[0] optionType = optionSpec[1] if trn is not None: n = trn._(optionName) else: n = optionName if n == optionName: oName = _(optionName) else: oName = n if isinstance(optionType, tuple): if isinstance(optionType[0], (int, long, float)): if len(optionType) == 3: val, min, max = optionType increment = 0.1 elif len(optionType) == 2: min, max = optionType val = min increment = 0.1 else: val, min, max, increment = optionType rows.append(addNumField(page, optionName, oName, val, min, max, increment)) if isinstance(optionType[0], (str, unicode)): isChoiceButton = False if optionType[0] == "string": kwds = [] wid = None val = None for keyword in optionType: if isinstance(keyword, (str, unicode)) and keyword != "string": kwds.append(keyword) for keyword in kwds: splitWord = keyword.split('=') if len(splitWord) > 1: v = None try: v = int(splitWord[1]) except ValueError: pass key = splitWord[0] if v is not None: if key == "width": wid = v else: if key == "value": val = "=".join(splitWord[1:]) if val is None: val = "" if wid is None: wid = 200 field = TextFieldWrapped(value=val, width=wid) page.optionDict[optionName] = AttrRef(field, 'value') row = Row((Label(oName, doNotTranslate=True), field)) rows.append(row) else: isChoiceButton = True if isChoiceButton: if trn is not None: __ = trn._ else: __ = _ choices = [__("%s" % a) for a in optionType] choiceButton = ChoiceButton(choices, doNotTranslate=True) page.optionDict[optionName] = AttrRef(choiceButton, 'selectedChoice') rows.append(Row((Label(oName, doNotTranslate=True), choiceButton))) elif isinstance(optionType, bool): cbox = CheckBox(value=optionType) page.optionDict[optionName] = AttrRef(cbox, 'value') row = Row((Label(oName, doNotTranslate=True), cbox)) rows.append(row) elif isinstance(optionType, (int, float)): rows.append(addNumField(self, optionName, oName, optionType)) elif optionType == "blocktype" or isinstance(optionType, pymclevel.materials.Block): blockButton = BlockButton(tool.editor.level.materials) if isinstance(optionType, pymclevel.materials.Block): blockButton.blockInfo = optionType row = Column((Label(oName, doNotTranslate=True), blockButton)) page.optionDict[optionName] = AttrRef(blockButton, 'blockInfo') rows.append(row) elif optionType == "label": rows.append(wrapped_label(oName, 50, doNotTranslate=True)) elif optionType == "string": inp = None # not sure how to pull values from filters, # but leaves it open for the future. Use this variable to set field width. if inp is not None: size = inp else: size = 200 field = TextFieldWrapped(value="") row = TextInputRow(oName, ref=AttrRef(field, 'value'), width=size, doNotTranslate=True) page.optionDict[optionName] = AttrRef(field, 'value') rows.append(row) elif optionType == "title": title = oName elif type(optionType) == list and optionType[0].lower() == "nbttree": kw = {'close_text': None, 'load_text': None} if len(optionType) >= 3: def close(): self.pages.show_page(self.pages.pages[optionType[2]]) kw['close_action'] = close kw['close_text'] = "Go Back" if len(optionType) >= 4: if optionType[3]: kw['load_text'] = optionType[3] if hasattr(self.module, 'nbt_ok_action'): kw['ok_action'] = getattr(self.module, 'nbt_ok_action') self.nbttree = NBTExplorerToolPanel(self.tool.editor, nbtObject=optionType[1], height=max_height, no_header=True, copy_data=False, **kw) self.module.set_tree(self.nbttree.tree) for meth_name in dir(self.module): if meth_name.startswith('nbttree_'): setattr(self.nbttree.tree.treeRow, meth_name.split('nbttree_')[-1], getattr(self.module, meth_name)) # elif meth_name.startswith('nbt_'): # setattr(self.nbttree, meth_name.split('nbt_')[-1], getattr(self.module, meth_name)) page.optionDict[optionName] = AttrRef(self, 'rebuildTabPage') rows.append(self.nbttree) self.nbttree.page = len(self.pgs) else: raise ValueError(("Unknown option type", optionType)) height = sum(r.height for r in rows) + (len(rows) - 1) * self.spacing if height > max_height: h = 0 for i, r in enumerate(rows): h += r.height if h > height / 2: if rows[:i]: cols.append(Column(rows[:i], spacing=0)) rows = rows[i:] break if len(rows): cols.append(Column(rows, spacing=0)) if len(cols): page.add(Row(cols, spacing=0)) page.shrink_wrap() return title, page, page._rect
def makeTabPage(self, tool, inputs): page = Widget() page.is_gl_container = True rows = [] cols = [] height = 0 max_height = 550 page.optionDict = {} page.tool = tool title = "Tab" for optionName, optionType in inputs: if isinstance(optionType, tuple): if isinstance(optionType[0], (int, long, float)): if len(optionType) > 2: val, min, max = optionType elif len(optionType) == 2: min, max = optionType val = min rows.append(addNumField(page, optionName, val, min, max)) if isinstance(optionType[0], (str)): if len(optionType) == 3: a, b, c = optionType if a == "strValSize": field = TextField(value=b, width=c) page.optionDict[optionName] = AttrRef( field, 'value') row = Row((Label(optionName), field)) rows.append(row) elif len(optionType) == 2: a, b = optionType if a == "strVal": field = TextField(value=b, width=200) page.optionDict[optionName] = AttrRef( field, 'value') row = Row((Label(optionName), field)) rows.append(row) elif a == "strSize": field = TextField(value="Input String Here", width=b) page.optionDict[optionName] = AttrRef( field, 'value') row = Row((Label(optionName), field)) rows.append(row) if isinstance(optionType[0], (str, unicode)): choiceButton = ChoiceButton(map(str, optionType)) page.optionDict[optionName] = AttrRef( choiceButton, 'selectedChoice') rows.append(Row((Label(optionName), choiceButton))) elif isinstance(optionType, bool): cbox = CheckBox(value=optionType) page.optionDict[optionName] = AttrRef(cbox, 'value') row = Row((Label(optionName), cbox)) rows.append(row) elif isinstance(optionType, (int, float)): rows.append(addNumField(self, optionName, optionType)) elif optionType == "blocktype" or isinstance( optionType, materials.Block): blockButton = BlockButton(tool.editor.level.materials) if isinstance(optionType, materials.Block): blockButton.blockInfo = optionType row = Column((Label(optionName), blockButton)) page.optionDict[optionName] = AttrRef(blockButton, 'blockInfo') rows.append(row) elif optionType == "label": rows.append(wrapped_label(optionName, 50)) elif optionType == "string": field = TextField(value="Input String Here", width=200) page.optionDict[optionName] = AttrRef(field, 'value') row = Row((Label(optionName), field)) rows.append(row) elif optionType == "title": title = optionName else: raise ValueError(("Unknown option type", optionType)) height = sum(r.height for r in rows) if height > max_height: h = 0 for i, r in enumerate(rows): h += r.height if h > height / 2: break cols.append(Column(rows[:i])) rows = rows[i:] #cols.append(Column(rows)) if len(rows): cols.append(Column(rows)) if len(cols): page.add(Row(cols)) page.shrink_wrap() return (title, page, page._rect)
def __init__(self, tool, module, *args, **kw): Widget.__init__(self, *args, **kw) rows = [] self.optionDict = {} self.tool = tool cols = [] height = 0 max_height = 550 print "Creating options for ", module if hasattr(module, "inputs"): for optionName, optionType in module.inputs: if isinstance(optionType, tuple): if isinstance(optionType[0], (int, long, float)): if len(optionType) > 2: val, min, max = optionType elif len(optionType) == 2: min, max = optionType val = min rows.append(self.addNumberField(optionName, val, min, max)) if isinstance(optionType[0], (str, unicode)): choiceButton = ChoiceButton(map(str, optionType)) self.optionDict[optionName] = AttrRef(choiceButton, 'selectedChoice') rows.append(Row((Label(optionName), choiceButton))) elif isinstance(optionType, bool): cbox = CheckBox(value=optionType) self.optionDict[optionName] = AttrRef(cbox, 'value') row = Row((Label(optionName), cbox)) rows.append(row) elif isinstance(optionType, (int, float)): rows.append(self.addNumberField(optionName, optionType)) elif optionType == "blocktype" or isinstance(optionType, materials.Block): blockButton = BlockButton(self.tool.editor.level.materials) if isinstance(optionType, materials.Block): blockButton.blockInfo = optionType row = Column((Label(optionName), blockButton)) self.optionDict[optionName] = AttrRef(blockButton, 'blockInfo') rows.append(row) elif optionType == "label": rows.append(wrapped_label(optionName, 50)) else: raise ValueError(("Unknown option type", optionType)) height = sum(r.height for r in rows) if height > max_height: h = 0 for i, r in enumerate(rows): h += r.height if h > height / 2: break cols.append(Column(rows[:i])) rows = rows[i:] #cols.append(Column(rows)) if len(rows): cols.append(Column(rows)) if len(cols): self.add(Row(cols)) self.shrink_wrap() else: self.size = (0, 0)
def makeTabPage(self, tool, inputs): page = Widget() page.is_gl_container = True rows = [] cols = [] height = 0 max_height = 550 page.optionDict = {} page.tool = tool title = "Tab" for optionName, optionType in inputs: if isinstance(optionType, tuple): if isinstance(optionType[0], (int, long, float)): if len(optionType) > 2: val, min, max = optionType elif len(optionType) == 2: min, max = optionType val = min rows.append(addNumField(page, optionName, val, min, max)) if isinstance(optionType[0], (str, unicode)): isChoiceButton = False if len(optionType) == 3: a,b,c = optionType if a == "strValSize": field = TextField(value=b, width=c) page.optionDict[optionName] = AttrRef(field, 'value') row = Row((Label(optionName), field)) rows.append(row) else: isChoiceButton = True elif len(optionType) == 2: a,b = optionType if a == "strVal": field = TextField(value=b, width=200) page.optionDict[optionName] = AttrRef(field, 'value') row = Row((Label(optionName), field)) rows.append(row) elif a == "strSize": field = TextField(value="Input String Here", width=b) page.optionDict[optionName] = AttrRef(field, 'value') row = Row((Label(optionName), field)) rows.append(row) else: isChoiceButton = True else: isChoiceButton = True if isChoiceButton: choiceButton = ChoiceButton(map(str, optionType)) page.optionDict[optionName] = AttrRef(choiceButton, 'selectedChoice') rows.append(Row((Label(optionName), choiceButton))) elif isinstance(optionType, bool): cbox = CheckBox(value=optionType) page.optionDict[optionName] = AttrRef(cbox, 'value') row = Row((Label(optionName), cbox)) rows.append(row) elif isinstance(optionType, (int, float)): rows.append(addNumField(self, optionName, optionType)) elif optionType == "blocktype" or isinstance(optionType, materials.Block): blockButton = BlockButton(tool.editor.level.materials) if isinstance(optionType, materials.Block): blockButton.blockInfo = optionType row = Column((Label(optionName), blockButton)) page.optionDict[optionName] = AttrRef(blockButton, 'blockInfo') rows.append(row) elif optionType == "label": rows.append(wrapped_label(optionName, 50)) elif optionType == "string": field = TextField(value="Input String Here", width=200) page.optionDict[optionName] = AttrRef(field, 'value') row = Row((Label(optionName), field)) rows.append(row) elif optionType == "title": title = optionName else: raise ValueError(("Unknown option type", optionType)) height = sum(r.height for r in rows) if height > max_height: h = 0 for i, r in enumerate(rows): h += r.height if h > height / 2: break cols.append(Column(rows[:i])) rows = rows[i:] #cols.append(Column(rows)) if len(rows): cols.append(Column(rows)) if len(cols): page.add(Row(cols)) page.shrink_wrap() return (title, page, page._rect)
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)