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)
def togglePortable(self): if sys.platform == "darwin": return False textChoices = [ _("This will make your MCEdit \"portable\" by moving your settings and schematics into the same folder as {0}. Continue?").format( (sys.platform == "darwin" and _("the MCEdit application") or _("MCEditData"))), _("This will move your settings and schematics to your Documents folder. Continue?"), ] useExisting = False alertText = textChoices[directories.portable] if albow.ask(alertText) == "OK": if [directories.hasPreviousPortableInstallation, directories.hasPreviousFixedInstallation][directories.portable](): asked = albow.ask("Found a previous " + ["portable", "fixed"][directories.portable] + " installation", responses=["Use", "Overwrite", "Cancel"]) if asked == "Use": useExisting = True elif asked == "Overwrite": useExisting = False elif asked == "Cancel": return False try: [directories.goPortable, directories.goFixed][directories.portable](useExisting) except Exception, e: traceback.print_exc() albow.alert(_(u"Error while moving files: {0}").format(repr(e)))
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)
def togglePortable(self): if sys.platform == "darwin": return False textChoices = [ _("This will make your MCEdit \"portable\" by moving your settings and schematics into the same folder as {0}. Continue?" ).format( (sys.platform == "darwin" and _("the MCEdit application") or _("MCEditData"))), _("This will move your settings and schematics to your Documents folder. Continue?" ), ] useExisting = False alertText = textChoices[directories.portable] if albow.ask(alertText) == "OK": if [ directories.hasPreviousPortableInstallation, directories.hasPreviousFixedInstallation ][directories.portable](): asked = albow.ask("Found a previous %s installation" % ["portable", "fixed"][directories.portable], responses=["Use", "Overwrite", "Cancel"]) if asked == "Use": useExisting = True elif asked == "Overwrite": useExisting = False elif asked == "Cancel": return False try: [directories.goPortable, directories.goFixed][directories.portable](useExisting) except Exception, e: traceback.print_exc() albow.alert( _(u"Error while moving files: {0}").format(repr(e)))
def perform(self, recordUndo=True): self.player = input_text_buttons("Enter a Player Name: ", 160) if not self.player: return if len(self.player) > 16: alert("Name to long. Maximum name length is 16.") return elif len(self.player) < 4: alert("Name to short. Minimum name length is 4.") return try: self.uuid = version_utils.getUUIDFromPlayerName(self.player) self.player = version_utils.getPlayerNameFromUUID(self.uuid) #Case Corrected except: action = ask("Could not get {}'s UUID. Please make sure that you are connected to the internet and that the player {} exists.".format(self.player, self.player), ["Enter UUID manually", "Cancel"]) if action != "Enter UUID manually": return self.uuid = input_text_buttons("Enter a Player UUID: ", 160) if not self.uuid: return self.player = version_utils.getPlayerNameFromUUID(self.uuid) if self.player == self.uuid.replace("-", ""): if ask("UUID was not found. Continue anyways?") == "Cancel": return if self.uuid in self.level.players: alert("Player already exists in this World.") return self.playerTag = self.newPlayer() if self.tool.panel: self.tool.panel.players.append(self.player) if self.level.oldPlayerFolderFormat: self.level.playerTagCache[self.level.getPlayerPath(self.player)] = self.playerTag self.level.players.append(self.player) if self.tool.panel: self.tool.panel.player_UUID[self.player] = self.player else: self.level.playerTagCache[self.level.getPlayerPath(self.uuid)] = self.playerTag self.level.players.append(self.uuid) if self.tool.panel: self.tool.panel.player_UUID[self.player] = self.uuid self.tool.playerPos[(0,0,0)] = self.uuid self.tool.revPlayerPos[self.uuid] = (0,0,0) self.tool.playerTexture[self.uuid] = loadPNGTexture(version_utils.getPlayerSkin(self.uuid, force=False)) self.tool.markerList.invalidate() self.tool.recordMove = False self.tool.movingPlayer = self.uuid if self.tool.panel: self.tool.hidePanel() self.tool.showPanel() self.canUndo = True
def _alertException(*args, **kw): try: return func(*args, **kw) except root.Cancel: alert("Canceled.") except pymclevel.infiniteworld.SessionLockLost as e: alert(e.message + _("\n\nYour changes cannot be saved.")) except Exception, e: logging.exception("Exception:") ask(_("Error during {0}: {1!r}").format(func, e)[:1000], ["OK"], cancel=0)
def destroyChunks(self, chunks=None): if "No" == ask("Really delete these chunks? This cannot be undone.", ("Yes", "No")): return if chunks is None: chunks = self.selectedChunks() chunks = list(chunks) def _destroyChunks(): i = 0 chunkCount = len(chunks) for cx, cz in chunks: i += 1 yield (i, chunkCount) if self.editor.level.containsChunk(cx, cz): try: self.editor.level.deleteChunk(cx, cz) except Exception as e: print "Error during chunk delete: ", e with setWindowCaption("DELETING - "): showProgress("Deleting chunks...", _destroyChunks()) self.editor.renderer.invalidateChunkMarkers() self.editor.renderer.discardAllChunks()
def key_down(self, evt): keyname = self.root.getKey(evt) if keyname == 'Escape': if self.changesNum: result = albow.ask("Do you want to save your changes?", ["Save", "Don't Save", "Cancel"]) if result == "Save": self.done() elif result == "Don't Save": for k in self.changes.keys(): config.keys[config.convert(k)].set(self.changes[k]) self.changesNum = False self.changes = {} self.choiceButton.selectedChoice = self.oldChoice config.save() self.dismiss() else: self.dismiss() elif keyname == 'Up' and self.selectedKeyIndex > 0: self.selectedKeyIndex -= 1 elif keyname == 'Down' and self.selectedKeyIndex < len( self.keyConfigKeys) - 1: self.selectedKeyIndex += 1 elif keyname == 'Return': self.enter += 1 self.askAssignSelectedKey() self.root.handling_ctrl(evt)
def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return if self.player == "Player": answer = ask(_("Are you sure you want to delete the default player?"), ["Yes", "Cancel"]) if answer == "Cancel": return if recordUndo: self.undoTag = self.level.getPlayerTag(self.player) self.level.players.remove(self.player) if self.tool.panel: if self.player != "Player": self.tool.panel.players.remove(version_utils.getPlayerNameFromUUID(self.player)) else: self.tool.panel.players.remove("Player") while self.tool.panel.table.index >= len(self.tool.panel.players): self.tool.panel.table.index -= 1 if len(self.tool.panel.players) == 0: self.tool.hidePanel() self.tool.showPanel() self.tool.markerList.invalidate() pos = self.tool.revPlayerPos[self.player] del self.tool.playerPos[pos] if self.player != "Player": del self.tool.playerTexture[self.player] else: del self.level.root_tag["Data"]["Player"] del self.tool.revPlayerPos[self.player] self.canUndo = True
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)
def pruneChunks(self): if "No" == ask( "Save these chunks and remove the rest? This cannot be undone.", ("Yes", "No")): return self.editor.saveFile() def _pruneChunks(): maxChunks = self.editor.level.chunkCount selectedChunks = self.selectedChunks() for i, cPos in enumerate(list(self.editor.level.allChunks)): if cPos not in selectedChunks: try: self.editor.level.deleteChunk(*cPos) except Exception as e: print "Error during chunk delete: ", e yield i, maxChunks with setWindowCaption("PRUNING - "): showProgress("Pruning chunks...", _pruneChunks()) self.editor.renderer.invalidateChunkMarkers() self.editor.discardAllChunks()
def key_down(self, evt): keyname = self.root.getKey(evt) if keyname == 'Escape': if self.changesNum: result = albow.ask("Do you want to save your changes?", ["Save", "Don't Save", "Cancel"]) if result == "Save": self.done() elif result == "Don't Save": for k in self.changes.keys(): config.keys[config.convert(k)].set(self.changes[k]) self.changesNum = False self.changes = {} self.choiceButton.selectedChoice = self.oldChoice config.save() self.dismiss() else: self.dismiss() elif keyname == 'Up' and self.selectedKeyIndex > 0: self.selectedKeyIndex -= 1 elif keyname == 'Down' and self.selectedKeyIndex < len(self.keyConfigKeys) - 1: self.selectedKeyIndex += 1 elif keyname == 'Return': self.enter += 1 self.askAssignSelectedKey() self.root.handling_ctrl(evt)
def extractUndoChunks(self, level, chunks, chunkCount=None): if not isinstance(level, pymclevel.MCInfdevOldLevel): chunks = numpy.array(list(chunks)) mincx, mincz = numpy.min(chunks, 0) maxcx, maxcz = numpy.max(chunks, 0) box = BoundingBox((mincx << 4, 0, mincz << 4), (maxcx << 4, level.Height, maxcz << 4)) return self.extractUndoSchematic(level, box) undoLevel = pymclevel.MCInfdevOldLevel(mkundotemp(), create=True) if not chunkCount: try: chunkCount = len(chunks) except TypeError: chunkCount = -1 def _extractUndo(): yield 0, 0, "Recording undo..." for i, (cx, cz) in enumerate(chunks): undoLevel.copyChunkFrom(level, cx, cz) yield i, chunkCount, _("Copying chunk %s...") % ((cx, cz),) undoLevel.saveInPlace() if chunkCount > 25 or chunkCount < 1: if "Canceled" == showProgress("Recording undo...", _extractUndo(), cancel=True): if albow.ask("Continue with undo disabled?", ["Continue", "Cancel"]) == "Cancel": raise Cancel else: return None else: exhaust(_extractUndo()) return undoLevel
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)
def perform(level, box, options): destroy = [] keep = [] for (chunk, slices, point) in level.getChunkSlices(box): entities = [] for e in chunk.Entities: x = e["Pos"][0].value y = e["Pos"][1].value z = e["Pos"][2].value if (x, y, z) in box: if e["id"].value == "ArmorStand": try: if e["CustomName"].value not in destroy and e[ "CustomName"].value not in keep: answer = albow.ask(e["CustomName"].value, ['Destroy', 'Keep'], default=0, cancel=1) if answer == 'Destroy': destroy.append(e["CustomName"].value) elif answer == 'Keep': keep.append(e["CustomName"].value) if e["CustomName"].value in destroy: continue elif e["CustomName"].value in keep: entities.append(e) except: entities.append(e) else: entities.append(e) else: entities.append(e) chunk.Entities.value[:] = entities chunk.dirty = True
def saveFile(fName, data, savePolicy): if fName is None: return if os.path.exists(fName): r = ask("File already exists.\nClick 'OK' to choose one.") if r == 'OK': folder, name = os.path.split(fName) suffix = os.path.splitext(name)[-1][1:] fName = mcplatform.askSaveFile(folder, "Choose a NBT file...", name, 'Folder\0*.dat\0*.*\0\0', suffix) else: return if savePolicy == -1: if hasattr(data, 'name'): data.name = "" if not os.path.isdir(fName): if savePolicy <= 0: data.save(fName) elif savePolicy == 1: with littleEndianNBT(): toSave = data.save(compressed=False) toSave = struct.Struct('<i').pack(4) + struct.Struct('<i').pack(len(toSave)) + toSave with open(fName, 'w') as f: f.write(toSave) else: alert("The selected object is not a file.\nCan't save it.")
def saveFile(fName, data, savePolicy): if fName is None: return if os.path.exists(fName): r = ask("File already exists.\nClick 'OK' to choose one.") if r == 'OK': folder, name = os.path.split(fName) suffix = os.path.splitext(name)[-1][1:] fName = mcplatform.askSaveFile(folder, "Choose a NBT file...", name, 'Folder\0*.dat\0*.*\0\0', suffix) else: return if savePolicy == -1: if hasattr(data, 'name'): data.name = "" if not os.path.isdir(fName): if savePolicy <= 0: data.save(fName) elif savePolicy == 1: with littleEndianNBT(): toSave = data.save(compressed=False) toSave = struct.Struct('<i').pack(4) + struct.Struct( '<i').pack(len(toSave)) + toSave with open(fName, 'w') as f: f.write(toSave) else: alert("The selected object is not a file.\nCan't save it.")
def _alertException(*args, **kw): try: return func(*args, **kw) except root.Cancel: alert("Canceled.") except Exception, e: if ask("Error during {0}: {1!r}".format(func, e)[:1000], ["Report Error", "Okay"], default=1, cancel=0) == "Report Error": reportException(e)
def refreshLang(self=None, suppressAlert=False, build=True): """Refreshes and returns the current language string""" global oldlang import config import leveleditor from leveleditor import Settings try: cancel = False lang = Settings.langCode.get() #.langCode isRealLang = verifyLangCode(lang) if build: buildTranslation(lang) if not oldlang == lang and not suppressAlert and isRealLang: import albow if leveleditor.LevelEditor(self).unsavedEdits: result = albow.ask( "You must restart MCEdit to see language changes", ["Save and Restart", "Restart", "Cancel"]) else: result = albow.ask( "You must restart MCEdit to see language changes", ["Restart", "Cancel"]) if result == "Save and Restart": editor.saveFile() restart(self) elif result == "Restart": restart(self) else: isRealLang = False cancel = True elif not suppressAlert and not isRealLang: import albow albow.alert("{} is not a valid language".format(lang)) if not isRealLang: Settings.langCode.set(oldlang) else: oldlang = lang if cancel == True: return "" else: return lang except Exception as inst: print inst return ""
def refreshLang(self=None,suppressAlert=False,build=True): """Refreshes and returns the current language string""" global oldlang import config import leveleditor from leveleditor import Settings try: cancel = False lang = Settings.langCode.get() #.langCode isRealLang = verifyLangCode(lang) if build: buildTranslation(lang) if not oldlang == lang and not suppressAlert and isRealLang: import albow if leveleditor.LevelEditor(self).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() restart(self) elif result == "Restart": restart(self) elif result == "Later": pass else: isRealLang = False cancel = True elif not suppressAlert and not isRealLang: import albow albow.alert("{} is not a valid language ({})".format(lang,os.path.join(langPath, lang + ".json"))) if not isRealLang: Settings.langCode.set(oldlang) else: oldlang = lang if cancel == True: return "" else: return lang except Exception as inst: print inst return ""
def _alertException(*args, **kw): try: return func(*args, **kw) except root.Cancel: alert("Canceled.") except pymclevel.infiniteworld.SessionLockLost as e: alert(e.message + "\n\nYour changes cannot be saved.") except Exception, e: logging.exception("Exception:") if ask("Error during {0}: {1!r}".format(func, e)[:1000], ["Report Error", "Okay"], default=1, cancel=0) == "Report Error": reportException()
def perform(self, recordUndo=True): self.player = input_text("Enter a Player Name: ", 160) if len(self.player) > 16: alert("Name to long. Maximum name length is 16.") return elif len(self.player) < 4: alert("Name to short. Minimum name length is 4.") return else: try: self.uuid = version_utils.getUUIDFromPlayerName(self.player) self.player = version_utils.getPlayerNameFromUUID(self.uuid) #Case Corrected except: action = ask("Could not get {}'s UUID. Please make sure, that you are connectedto the internet and that the player {} exists".format(self.player, self.player), ["Enter UUID manually", "Cancel"]) if action == "Enter UUID manually": self.uuid = input_text("Enter a Player UUID: ", 160) self.player = version_utils.getPlayerNameFromUUID(self.uuid) if self.player == self.uuid.replace("-", ""): if ask("UUID was not found. Continue anyways?") == "Cancel": return else: return if self.uuid in self.level.players: alert("Player already exists in this World.") return self.playerTag = self.newPlayer() self.level.playerTagCache[self.level.getPlayerPath(self.uuid)] = self.playerTag self.level.players.append(self.uuid) self.tool.panel.players.append(self.player) self.tool.panel.player_UUID[self.player] = self.uuid self.tool.markerList.invalidate() self.tool.movingPlayer = self.uuid print(self.level.players) print(self.tool.panel.players)
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)
def check_for_version(self): new_version = release.check_for_new_version(self.version_info) if new_version is not False: answer = albow.ask(_('Version {} is available').format( new_version["tag_name"]), ['Download', 'View', 'Ignore'], default=1, cancel=2) if answer == "View": platform_open(new_version["html_url"]) elif answer == "Download": platform_open(new_version["asset"]["browser_download_url"]) albow.alert( _(' {} should now be downloading via your browser. You will still need to extract the downloaded file to use the updated version.' ).format(new_version["asset"]["name"]))
def mouseDown(self, evt, pos, direction): pos = map(lambda p, d: p + d, pos, direction) op = PlayerSpawnMoveOperation(self, pos) try: op.perform() self.editor.addOperation(op) self.editor.addUnsavedEdit() self.markerList.invalidate() except SpawnPositionInvalid, e: if "Okay" != ask(str(e), responses=["Okay", "Fix it for me!"]): level = self.editor.level status = "" if not okayAt63(level, pos): level.setBlockAt(pos[0], 63, pos[2], 1) status += _("Block added at y=63.\n") if 59 < pos[1] < 63: pos[1] = 63 status += _("Spawn point moved upward to y=63.\n") if not okayAboveSpawn(level, pos): if pos[1] > 63 or pos[1] < 59: lpos = (pos[0], pos[1] - 1, pos[2]) if level.blockAt(*pos) == 0 and level.blockAt( *lpos) != 0 and okayAboveSpawn(level, lpos): pos = lpos status += _( "Spawn point shifted down by one block.\n") if not okayAboveSpawn(level, pos): for i in range(1, 4): level.setBlockAt(pos[0], pos[1] + i, pos[2], 0) status += _("Blocks above spawn point cleared.\n") self.editor.invalidateChunks([(pos[0] // 16, pos[2] // 16)]) op = PlayerSpawnMoveOperation(self, pos) try: op.perform() except SpawnPositionInvalid, e: alert(str(e)) return self.editor.addOperation(op) self.editor.addUnsavedEdit() self.markerList.invalidate() if len(status): alert(_("Spawn point fixed. Changes: \n\n") + status)
def cancel(self): if self.changesNum: result = albow.ask("Do you want to save your changes?", ["Save", "Don't Save", "Cancel"]) if result == "Save": self.done() elif result == "Don't Save": for k in self.changes.keys(): config.keys[config.convert(k)].set(self.changes[k]) self.changesNum = False self.changes = {} self.choiceButton.selectedChoice = self.oldChoice config.save() self.dismiss() else: self.dismiss()
def togglePortable(self): if sys.platform == "darwin": return False textChoices = [ _("This will make your MCEdit \"portable\" by moving your settings and schematics into the same folder as {0}. Continue?").format( (sys.platform == "darwin" and _("the MCEdit application") or _("MCEditData"))), _("This will move your settings and schematics to your Documents folder. Continue?"), ] alertText = textChoices[directories.portable] if albow.ask(alertText) == "OK": try: [directories.goPortable, directories.goFixed][directories.portable]() except Exception, e: traceback.print_exc() albow.alert(_(u"Error while moving files: {0}").format(repr(e)))
def pruneChunks(self): if "No" == ask("Save these chunks and remove the rest? This cannot be undone.", ("Yes", "No")): return self.editor.saveFile() def _pruneChunks(): selectedChunks = self.selectedChunks() for i, cPos in enumerate(list(self.editor.level.allChunks)): if cPos not in selectedChunks: try: self.editor.level.deleteChunk(*cPos) except Exception, e: print "Error during chunk delete: ", e yield i, self.editor.level.chunkCount
def saveFile(fName, data, dontSaveRootTag): if os.path.exists(fName): r = ask("File already exists.\nClick 'OK' to choose one.") if r == 'OK': folder, name = os.path.split(fName) suffix = os.path.splitext(name)[-1][1:] fName = mcplatform.askSaveFile(folder, "Choose a NBT file...", name, 'Folder\0*.dat\0*.*\0\0', suffix) else: return if dontSaveRootTag: if hasattr(data, 'name'): data.name = "" if not os.path.isdir(fName): data.save(fName) else: alert("The selected object is not a file.\nCan't save it.")
def mouseDown(self, evt, pos, direction): pos = map(lambda p, d: p + d, pos, direction) op = PlayerSpawnMoveOperation(self, pos) try: op.perform() self.editor.addOperation(op) self.editor.addUnsavedEdit() self.markerList.invalidate() except SpawnPositionInvalid, e: if "Okay" != ask(str(e), responses=["Okay", "Fix it for me!"]): level = self.editor.level status = "" if not okayAt63(level, pos): level.setBlockAt(pos[0], 63, pos[2], 1) status += "Block added at y=63.\n" if 59 < pos[1] < 63: pos[1] = 63 status += "Spawn point moved upward to y=63.\n" if not okayAboveSpawn(level, pos): if pos[1] > 63 or pos[1] < 59: lpos = (pos[0], pos[1] - 1, pos[2]) if level.blockAt(*pos) == 0 and level.blockAt(*lpos) != 0 and okayAboveSpawn(level, lpos): pos = lpos status += "Spawn point shifted down by one block.\n" if not okayAboveSpawn(level, pos): for i in range(1, 4): level.setBlockAt(pos[0], pos[1] + i, pos[2], 0) status += "Blocks above spawn point cleared.\n" self.editor.invalidateChunks([(pos[0] // 16, pos[2] // 16)]) op = PlayerSpawnMoveOperation(self, pos) try: op.perform() except SpawnPositionInvalid, e: alert(str(e)) return self.editor.addOperation(op) self.editor.addUnsavedEdit() self.markerList.invalidate() if len(status): alert("Spawn point fixed. Changes: \n\n" + status)
def pruneChunks(self): if "No" == ask("Save these chunks and remove the rest? This cannot be undone.", ("Yes", "No")): return self.editor.saveFile() def _pruneChunks(): maxChunks = self.editor.level.chunkCount selectedChunks = self.selectedChunks() for i, cPos in enumerate(list(self.editor.level.allChunks)): if cPos not in selectedChunks: try: self.editor.level.deleteChunk(*cPos) except Exception, e: print "Error during chunk delete: ", e yield i, maxChunks
def confirm_quit(self): #-# saving language template if hasattr(albow.translate, "saveTemplate"): albow.translate.saveTemplate() #-# self.saveWindowPosition() config.save() if self.editor.unsavedEdits: result = albow.ask(_("There are {0} unsaved changes.").format(self.editor.unsavedEdits), responses=["Save and Quit", "Quit", "Cancel"]) if result == "Save and Quit": self.saveAndQuit() elif result == "Quit": self.justQuit() elif result == "Cancel": return False else: raise SystemExit
def check_for_version(self): new_version = release.check_for_new_version(self.version_info) if new_version is not False: answer = albow.ask( _('Version {} is available').format(new_version["tag_name"]), [ 'Download', 'View', 'Ignore' ], default=1, cancel=2 ) if answer == "View": platform_open(new_version["html_url"]) elif answer == "Download": platform_open(new_version["asset"]["browser_download_url"]) albow.alert(_(' {} should now be downloading via your browser. You will still need to extract the downloaded file to use the updated version.').format(new_version["asset"]["name"]))
def _alertException(*args, **kw): try: return func(*args, **kw) except root.Cancel: alert("Canceled.") except pymclevel.infiniteworld.SessionLockLost as e: alert(e.message + "\n\nYour changes cannot be saved.") except Exception, e: logging.exception("Exception:") if ask("Error during {0}: {1!r}".format(func, e)[:1000], ["Report Error", "Okay"], default=1, cancel=0) == "Report Error": try: import squash_python squash_python.get_client().recordException(*sys.exc_info()) except ImportError: pass except Exception: logging.exception("Error while recording exception data:")
def destroyChunks(self, chunks=None): if "No" == ask("Really delete these chunks? This cannot be undone.", ("Yes", "No")): return if chunks is None: chunks = self.selectedChunks() chunks = list(chunks) def _destroyChunks(): i = 0 chunkCount = len(chunks) for cx, cz in chunks: i += 1 yield (i, chunkCount) if self.editor.level.containsChunk(cx, cz): try: self.editor.level.deleteChunk(cx, cz) except Exception, e: print "Error during chunk delete: ", e
def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return if self.player == "Player (Single Player)": answer = ask( _("Are you sure you want to delete the default player?"), ["Yes", "Cancel"]) if answer == "Cancel": return self.player = "Player" if recordUndo: self.undoTag = self.level.getPlayerTag(self.player) self.level.players.remove(self.player) if self.tool.panel: if self.player != "Player": #self.tool.panel.players.remove(player_cache.getPlayerNameFromUUID(self.player)) #self.tool.panel.players.remove(self.playercache.getPlayerInfo(self.player)[0]) str() else: self.tool.panel.players.remove("Player (Single Player)") while self.tool.panel.table.index >= len(self.tool.panel.players): self.tool.panel.table.index -= 1 #if len(self.tool.panel.players) == 0: # self.tool.hidePanel() # self.tool.showPanel() self.tool.hidePanel() self.tool.showPanel() self.tool.markerList.invalidate() self.tool.movingPlayer = None pos = self.tool.revPlayerPos[self.editor.level.dimNo][self.player] del self.tool.playerPos[self.editor.level.dimNo][pos] if self.player != "Player": del self.tool.playerTexture[self.player] else: del self.level.root_tag["Data"]["Player"] del self.tool.revPlayerPos[self.editor.level.dimNo][self.player] self.canUndo = True
def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return if self.player == "Player (Single Player)": answer = ask(_("Are you sure you want to delete the default player?"), ["Yes", "Cancel"]) if answer == "Cancel": return self.player = "Player" if recordUndo: self.undoTag = self.level.getPlayerTag(self.player) self.level.players.remove(self.player) if self.tool.panel: if self.player != "Player": #self.tool.panel.players.remove(player_cache.getPlayerNameFromUUID(self.player)) #self.tool.panel.players.remove(self.playercache.getPlayerInfo(self.player)[0]) str() else: self.tool.panel.players.remove("Player (Single Player)") while self.tool.panel.table.index >= len(self.tool.panel.players): self.tool.panel.table.index -= 1 #if len(self.tool.panel.players) == 0: # self.tool.hidePanel() # self.tool.showPanel() self.tool.hidePanel() self.tool.showPanel() self.tool.markerList.invalidate() self.tool.movingPlayer = None pos = self.tool.revPlayerPos[self.editor.level.dimNo][self.player] del self.tool.playerPos[self.editor.level.dimNo][pos] if self.player != "Player": del self.tool.playerTexture[self.player] else: del self.level.root_tag["Data"]["Player"] del self.tool.revPlayerPos[self.editor.level.dimNo][self.player] self.canUndo = True
def confirm_quit(self): #-# saving language template if hasattr(albow.translate, "saveTemplate"): albow.translate.saveTemplate() #-# self.saveWindowPosition() config.save() if self.editor.unsavedEdits: # if config.settings.savePositionOnClose.get(): # self.editor.waypointManager.saveLastPosition(self.editor.mainViewport, self.editor.level.getPlayerDimension()) # self.editor.waypointManager.save() result = albow.ask(_("There are {0} unsaved changes.").format(self.editor.unsavedEdits), responses=["Save and Quit", "Quit", "Cancel"]) if result == "Save and Quit": self.saveAndQuit() elif result == "Quit": self.justQuit() elif result == "Cancel": return False else: raise SystemExit
def key_down(self, evt): keyname = getKey(evt) if keyname == 'Escape': if self.changesNum >= 1: result = albow.ask("Do you want to save your changes?", ["Save", "Don't Save", "Cancel"]) if result == "Save": self.done() elif result == "Don't Save": for key in self.changes.keys(): config.config.set("Keys", key, self.changes[key]) self.changesNum = 0 self.changes = {} self.dismiss() else: self.dismiss() elif keyname == 'Up' and self.selectedKeyIndex > 0: self.selectedKeyIndex -= 1 elif keyname == 'Down' and self.selectedKeyIndex < len(self.keyConfigKeys)-1: self.selectedKeyIndex += 1 elif keyname == 'Return': self.enter += 1 self.askAssignSelectedKey()
def perform(self, recordUndo=True): if self.level.saving: alert(_("Cannot perform action while saving is taking place")) return if self.player == "Player": answer = ask( _("Are you sure you want to delete the default player?"), ["Yes", "Cancel"]) if answer == "Cancel": return if recordUndo: self.undoTag = self.level.getPlayerTag(self.player) self.level.players.remove(self.player) if self.tool.panel: if self.player != "Player": self.tool.panel.players.remove( version_utils.getPlayerNameFromUUID(self.player)) else: self.tool.panel.players.remove("Player") while self.tool.panel.table.index >= len(self.tool.panel.players): self.tool.panel.table.index -= 1 if len(self.tool.panel.players) == 0: self.tool.hidePanel() self.tool.showPanel() self.tool.markerList.invalidate() pos = self.tool.revPlayerPos[self.player] del self.tool.playerPos[pos] if self.player != "Player": del self.tool.playerTexture[self.player] else: del self.level.root_tag["Data"]["Player"] del self.tool.revPlayerPos[self.player] self.canUndo = True
def pruneChunks(self): if "No" == ask("Save these chunks and remove the rest? This cannot be undone.", ("Yes", "No")): return self.editor.saveFile() def _pruneChunks(): maxChunks = self.editor.level.chunkCount selectedChunks = self.selectedChunks() for i, cPos in enumerate(list(self.editor.level.allChunks)): if cPos not in selectedChunks: try: self.editor.level.deleteChunk(*cPos) except Exception as e: print "Error during chunk delete: ", e yield i, maxChunks with setWindowCaption("PRUNING - "): showProgress("Pruning chunks...", _pruneChunks()) self.editor.renderer.invalidateChunkMarkers() self.editor.discardAllChunks()
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)
def perform(self, recordUndo=True): self.player = input_text_buttons("Enter a Player Name: ", 160) if not self.player: return if len(self.player) > 16: alert("Name to long. Maximum name length is 16.") return elif len(self.player) < 4: alert("Name to short. Minimum name length is 4.") return try: ''' print "Player: \""+str(self.player)+"\"" self.uuid = version_utils.playercache.getPlayerFromPlayername(self.player) print "UUID: \""+str(self.uuid)+"\"" self.player = version_utils.playercache.getPlayerFromUUID(self.uuid) #Case Corrected ''' self.uuid, self.player, other_uuid = version_utils.playercache.getPlayerInfo(self.player) except: action = ask("Could not get {}'s UUID. Please make sure that you are connected to the internet and that the player {} exists.".format(self.player, self.player), ["Enter UUID manually", "Cancel"]) if action != "Enter UUID manually": return self.uuid = input_text_buttons("Enter a Player UUID: ", 160) if not self.uuid: return self.player = version_utils.playercache.getPlayerFromUUID(self.uuid) if self.player == self.uuid.replace("-", ""): if ask("UUID was not found. Continue anyways?") == "Cancel": return if self.uuid in self.level.players: alert("Player already exists in this World.") return self.playerTag = self.newPlayer() if self.tool.panel: self.tool.panel.players.append(self.player) if self.level.oldPlayerFolderFormat: self.level.playerTagCache[self.level.getPlayerPath(self.player)] = self.playerTag self.level.players.append(self.player) if self.tool.panel: self.tool.panel.player_UUID[self.player] = self.player else: self.level.playerTagCache[self.level.getPlayerPath(self.uuid)] = self.playerTag self.level.players.append(self.uuid) if self.tool.panel: self.tool.panel.player_UUID[self.player] = self.uuid self.tool.playerPos[(0,0,0)] = self.uuid self.tool.revPlayerPos[self.uuid] = (0,0,0) self.tool.playerTexture[self.uuid] = loadPNGTexture(version_utils.getPlayerSkin(self.uuid, force=False)) self.tool.markerList.invalidate() self.tool.recordMove = False self.tool.movingPlayer = self.uuid if self.tool.panel: self.tool.hidePanel() self.tool.showPanel() self.canUndo = True
def perform(self, recordUndo=True): initial = "" allowed_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_" while True: self.player = input_text_buttons("Enter a Player Name: ", 160, initial=initial, allowed_chars=allowed_chars) if self.player is None: return elif len(self.player) > 16: alert("Name too long. Maximum name length is 16.") initial = self.player elif len(self.player) < 1: alert("Name too short. Minimum name length is 1.") initial = self.player else: break try: ''' print "Player: \""+str(self.player)+"\"" self.uuid = version_utils.playercache.getPlayerFromPlayername(self.player) print "UUID: \""+str(self.uuid)+"\"" self.player = version_utils.playercache.getPlayerFromUUID(self.uuid) #Case Corrected ''' data = version_utils.playercache.getPlayerInfo(self.player, force=True) if isinstance(data, tuple): self.uuid = data[0] self.player = data[1] else: self.uuid = data except: action = ask( "Could not get {}'s UUID. Please make sure that you are connected to the internet and that the player {} exists." .format(self.player, self.player), ["Enter UUID manually", "Cancel"]) if action != "Enter UUID manually": return self.uuid = input_text_buttons("Enter a Player UUID: ", 160) if not self.uuid: return self.player = version_utils.playercache.getPlayerFromUUID( self.uuid) if self.player == self.uuid.replace("-", ""): if ask("UUID was not found. Continue anyways?") == "Cancel": return if self.uuid in self.level.players: alert("Player already exists in this World.") return self.playerTag = self.newPlayer() if self.tool.panel: self.tool.panel.players.append(self.player) if self.level.oldPlayerFolderFormat: self.level.playerTagCache[self.level.getPlayerPath( self.player)] = self.playerTag self.level.players.append(self.player) if self.tool.panel: self.tool.panel.player_UUID[self.player] = self.player else: self.level.playerTagCache[self.level.getPlayerPath( self.uuid)] = self.playerTag self.level.players.append(self.uuid) if self.tool.panel: self.tool.panel.player_UUID[self.player] = self.uuid self.tool.playerPos[(0, 0, 0)] = self.uuid self.tool.revPlayerPos[self.uuid] = (0, 0, 0) self.tool.playerTexture[self.uuid] = loadPNGTexture( version_utils.getPlayerSkin(self.uuid, force=False)) self.tool.markerList.invalidate() self.tool.recordMove = False self.tool.movingPlayer = self.uuid if self.tool.panel: self.tool.hidePanel() self.tool.showPanel() self.canUndo = True self.playerTag.save(self.level.getPlayerPath(self.uuid)) self.tool.nonSavedPlayers.append(self.level.getPlayerPath(self.uuid)) self.tool.inOtherDimension[self.editor.level.dimNo].append(self.uuid)
def main(cls): PlayerCache().load() displayContext = GLDisplayContext(splash.splash, caption=(('MCEdit ~ ' + release.get_version()%_("for")).encode('utf-8'), 'MCEdit')) os.environ['SDL_VIDEO_CENTERED'] = '0' rootwidget = RootWidget(displayContext.display) mcedit = MCEdit(displayContext) rootwidget.displayContext = displayContext rootwidget.confirm_quit = mcedit.confirm_quit rootwidget.mcedit = mcedit rootwidget.add(mcedit) rootwidget.focus_switch = mcedit if 0 == len(pymclevel.alphaMaterials.yamlDatas): albow.alert("Failed to load minecraft.yaml. Check the console window for details.") if mcedit.droppedLevel: mcedit.loadFile(mcedit.droppedLevel) cls.version_lock = threading.Lock() cls.version_info = None cls.version_checked = False fetch_version_thread = threading.Thread(target=cls.fetch_version) fetch_version_thread.start() # Disabled old update code # if hasattr(sys, 'frozen'): # # We're being run from a bundle, check for updates. # import esky # # app = esky.Esky( # sys.executable.decode(sys.getfilesystemencoding()), # 'https://bitbucket.org/codewarrior0/mcedit/downloads' # ) # try: # update_version = app.find_update() # except: # # FIXME: Horrible, hacky kludge. # update_version = None # logging.exception('Error while checking for updates') # # if update_version: # answer = albow.ask( # 'Version "%s" is available, would you like to ' # 'download it?' % update_version, # [ # 'Yes', # 'No', # ], # default=0, # cancel=1 # ) # if answer == 'Yes': # def callback(args): # status = args['status'] # status_texts = { # 'searching': u"Finding updates...", # 'found': u"Found version {new_version}", # 'downloading': u"Downloading: {received} / {size}", # 'ready': u"Downloaded {path}", # 'installing': u"Installing {new_version}", # 'cleaning up': u"Cleaning up...", # 'done': u"Done." # } # text = status_texts.get(status, 'Unknown').format(**args) # # panel = Dialog() # panel.idleevent = lambda event: panel.dismiss() # label = albow.Label(text, width=600) # panel.add(label) # panel.size = (500, 250) # panel.present() # # try: # app.auto_update(callback) # except (esky.EskyVersionError, EnvironmentError): # albow.alert(_("Failed to install update %s") % update_version) # else: # albow.alert(_("Version %s installed. Restart MCEdit to begin using it.") % update_version) # raise SystemExit() if config.settings.closeMinecraftWarning.get(): answer = albow.ask( "Warning: Only open a world in one program at a time. If you open a world at the same time in MCEdit and in Minecraft, you will lose your work and possibly damage your save file.\n\n If you are using Minecraft 1.3 or earlier, you need to close Minecraft completely before you use MCEdit.", ["Don't remind me again.", "OK"], default=1, cancel=1) if answer == "Don't remind me again.": config.settings.closeMinecraftWarning.set(False) # Disabled Crash Reporting Option # if not config.settings.reportCrashesAsked.get(): # answer = albow.ask( # "When an error occurs, MCEdit can report the details of the error to its developers. " # "The error report will include your operating system version, MCEdit version, " # "OpenGL version, plus the make and model of your CPU and graphics processor. No personal " # "information will be collected.\n\n" # "Error reporting can be enabled or disabled in the Options dialog.\n\n" # "Enable error reporting?", # ["Yes", "No"], # default=0) # config.settings.reportCrashes.set(answer == "Yes") # config.settings.reportCrashesAsked.set(True) config.settings.reportCrashes.set(False) config.settings.reportCrashesAsked.set(True) config.save() if "update" in config.version.version.get(): answer = albow.ask("There are new default controls. Do you want to replace your current controls with the new ones?", ["Yes", "No"]) if answer == "Yes": for configKey, k in keys.KeyConfigPanel.presets["WASD"]: config.keys[config.convert(configKey)].set(k) config.version.version.set("1.1.2.0") config.save() if "-causeError" in sys.argv: raise ValueError("Error requested via -causeError") while True: try: rootwidget.run() except (SystemExit, KeyboardInterrupt): print "Shutting down..." exc_txt = traceback.format_exc() if mcedit.editor.level: if config.settings.savePositionOnClose.get(): mcedit.editor.waypointManager.saveLastPosition(mcedit.editor.mainViewport, mcedit.editor.level.getPlayerDimension()) mcedit.editor.waypointManager.save() # The following Windows specific code won't be executed if we're using '--debug-wm' switch. if not USE_WM and sys.platform == "win32" and config.settings.setWindowPlacement.get(): (flags, showCmd, ptMin, ptMax, rect) = mcplatform.win32gui.GetWindowPlacement( display.get_wm_info()['window']) X, Y, r, b = rect #w = r-X #h = b-Y if (showCmd == mcplatform.win32con.SW_MINIMIZE or showCmd == mcplatform.win32con.SW_SHOWMINIMIZED): showCmd = mcplatform.win32con.SW_SHOWNORMAL config.settings.windowX.set(X) config.settings.windowY.set(Y) config.settings.windowShowCmd.set(showCmd) # Restore the previous language if we ran with '-tt' (update translation template). if albow.translate.buildTemplate: logging.warning('Restoring %s.'%orglang) config.settings.langCode.set(orglang) # config.save() mcedit.editor.renderer.discardAllChunks() mcedit.editor.deleteAllCopiedSchematics() if mcedit.editor.level: mcedit.editor.level.close() mcedit.editor.root.RemoveEditFiles() if 'SystemExit' in traceback.format_exc() or 'KeyboardInterrupt' in traceback.format_exc(): raise else: if 'SystemExit' in exc_txt: raise SystemExit if 'KeyboardInterrupt' in exc_txt: raise KeyboardInterrupt except MemoryError: traceback.print_exc() mcedit.editor.handleMemoryError()
def resized(self, dw, dh): """ Handle window resizing events. """ if DEBUG_WM: print "############################ RESIZED ############################" (w, h) = self.size config_w, config_h = config.settings.windowWidth.get(), config.settings.windowHeight.get() win = self.displayContext.win if DEBUG_WM and win: print "dw", dw, "dh", dh print "self.size (w, h) 1", self.size, "win.get_size", win.get_size() print "size 1", config_w, config_h elif DEBUG_WM and not win: print "win is None, unable to print debug messages" if win: x, y = win.get_position() if DEBUG_WM: print "position", x, y print "config pos", (config.settings.windowX.get(), config.settings.windowY.get()) if w == 0 and h == 0: # The window has been minimized, no need to draw anything. self.editor.renderer.render = False return # Mac window handling works better now, but `win` # doesn't exist. So to get this alert to show up # I'm checking if the platform is darwin. This only # works because the code block never actually references # `win`, otherwise it WOULD CRASH!!! # You cannot change further if statements like this # because they reference `win` if win or sys.platform == "darwin": # Handling too small resolutions. # Dialog texts. # "MCEdit does not support window resolutions below 1000x700.\nYou may not be able to access all functions at this resolution." # New buttons: # "Don't warn me again": disable the window popup across sessions. # Tooltip: "Disable this message. Definitively. Even the next time you start MCEdit." # "OK": dismiss the window and let go, don't pop up again for the session # Tooltip: "Continue and not see this message until you restart MCEdit" # "Cancel": resizes the window to the minimum size # Tooltip: "Resize the window to the minimum recommended resolution." # If the config showWindowSizeWarning is true and self.resizeAlert is true, show the popup if (w < 1000 or h < 680) and config.settings.showWindowSizeWarning.get(): _w = w _h = h if self.resizeAlert: answer = "_OK" # Force the size only for the dimension that needs it. if w < 1000 and h < 680: _w = 1000 _h = 680 elif w < 1000: _w = 1000 elif h < 680: _h = 680 if not albow.dialogs.ask_tied_to: answer = albow.ask( "MCEdit does not support window resolutions below 1000x700.\nYou may not be able to access all functions at this resolution.", ["Don't remind me again.", "OK", "Cancel"], default=1, cancel=1, responses_tooltips={ "Don't remind me again.": "Disable this message. Definitively. Even the next time you start MCEdit.", "OK": "Continue and not see this message until you restart MCEdit", "Cancel": "Resize the window to the minimum recommended resolution."}, tie_widget_to=True) else: if not albow.dialogs.ask_tied_to._visible: albow.dialogs.ask_tied_to._visible = True answer = albow.dialogs.ask_tied_to.present() if answer == "Don't remind me again.": config.settings.showWindowSizeWarning.set(False) self.resizeAlert = False elif answer == "OK": w, h = self.size self.resizeAlert = False elif answer == "Cancel": w, h = _w, _h else: if albow.dialogs.ask_tied_to: albow.dialogs.ask_tied_to.dismiss("_OK") del albow.dialogs.ask_tied_to albow.dialogs.ask_tied_to = None elif w >= 1000 or h >= 680: if albow.dialogs.ask_tied_tos: for ask_tied_to in albow.dialogs.ask_tied_tos: ask_tied_to._visible = False ask_tied_to.dismiss("_OK") ask_tied_to.set_parent(None) del ask_tied_to if not win: if w < 1000: config.settings.windowWidth.set(1000) w = 1000 x = config.settings.windowX.get() if h < 680: config.settings.windowHeight.set(680) h = 680 y = config.settings.windowY.get() if not self.editor.renderer.render: self.editor.renderer.render = True save_geom = True if win: maximized = win.get_state() == mcplatform.MAXIMIZED sz = map(max, win.get_size(), (w, h)) if DEBUG_WM: print "sz", sz print "maximized", maximized, "self.maximized", self.maximized if maximized: if DEBUG_WM: print "maximize, saving maximized size" config.settings.windowMaximizedWidth.set(sz[0]) config.settings.windowMaximizedHeight.set(sz[1]) config.save() self.saved_pos = config.settings.windowX.get(), config.settings.windowY.get() save_geom = False self.resizing = 0 win.set_mode(sz, self.displayContext.displayMode()) else: if DEBUG_WM: print "size 2", config.settings.windowWidth.get(), config.settings.windowHeight.get() print "config_w", config_w, "config_h", config_h print "pos", config.settings.windowX.get(), config.settings.windowY.get() if self.maximized != maximized: if DEBUG_WM: print "restoring window pos and size" print "(config.settings.windowX.get(), config.settings.windowY.get())", ( config.settings.windowX.get(), config.settings.windowY.get()) (w, h) = (config_w, config_h) win.set_state(1, (w, h), self.saved_pos) else: if DEBUG_WM: print "window resized" print "setting size to", (w, h), "and pos to", (x, y) win.set_mode((w, h), self.displayContext.displayMode()) win.set_position((x, y)) config.settings.windowMaximizedWidth.set(0) config.settings.windowMaximizedHeight.set(0) config.save() self.maximized = maximized if DEBUG_WM: print "self.size (w, h) 2", self.size, (w, h) surf = pygame.display.get_surface() print "display surf rect", surf.get_rect() if win: if hasattr(win.base_handler, 'get_geometry'): print "win.base_handler geometry", win.base_handler.get_geometry() print "win.base_handler.parent geometry", win.base_handler.query_tree().parent.get_geometry() print "win.base_handler.parent.parent geometry", win.base_handler.query_tree().parent.query_tree().parent.get_geometry() if save_geom: config.settings.windowWidth.set(w) config.settings.windowHeight.set(h) config.save() # The alert window is disabled if win is not None if not win and (dw > 20 or dh > 20): if not hasattr(self, 'resizeAlert'): self.resizeAlert = self.shouldResizeAlert if self.resizeAlert: albow.alert( "Window size increased. You may have problems using the cursor until MCEdit is restarted.") self.resizeAlert = False if win: win.sync() GLViewport.resized(self, dw, dh)
def main(cls): PlayerCache().load() displayContext = GLDisplayContext(splash.splash, caption=( ('MCEdit ~ ' + release.get_version() % _("for")).encode('utf-8'), 'MCEdit')) os.environ['SDL_VIDEO_CENTERED'] = '0' rootwidget = RootWidget(displayContext.display) mcedit = MCEdit(displayContext) rootwidget.displayContext = displayContext rootwidget.confirm_quit = mcedit.confirm_quit rootwidget.mcedit = mcedit rootwidget.add(mcedit) rootwidget.focus_switch = mcedit if mcedit.droppedLevel: mcedit.loadFile(mcedit.droppedLevel) cls.version_lock = threading.Lock() cls.version_info = None cls.version_checked = False fetch_version_thread = threading.Thread(target=cls.fetch_version) fetch_version_thread.start() if config.settings.closeMinecraftWarning.get(): answer = albow.ask( "Warning: Only open a world in one program at a time. If you open a world at the same time in MCEdit and in Minecraft, you will lose your work and possibly damage your save file.\n\n If you are using Minecraft 1.3 or earlier, you need to close Minecraft completely before you use MCEdit.", ["Don't remind me again.", "OK"], default=1, cancel=1) if answer == "Don't remind me again.": config.settings.closeMinecraftWarning.set(False) if not config.settings.reportCrashesAsked.get(): answer = albow.ask( 'Would you like to send anonymous error reports to the MCEdit-Unified Team to help with improving future releases?\n\nError reports are stripped of any identifying user information before being sent.\n\nPyClark, the library used, is open source under the GNU LGPL v3 license and is maintained by Podshot. The source code can be located here: https://github.com/Podshot/pyClark.\n\nThere has been no modification to the library in any form.', ['Allow', 'Deny'], default=1, cancel=1 ) if answer == 'Allow': albow.alert("Error reporting will be enabled next time MCEdit-Unified is launched") config.settings.reportCrashes.set(answer == 'Allow') config.settings.reportCrashesAsked.set(True) config.save() if "update" in config.version.version.get(): answer = albow.ask( "There are new default controls. Do you want to replace your current controls with the new ones?", ["Yes", "No"]) if answer == "Yes": for configKey, k in keys.KeyConfigPanel.presets["WASD"]: config.keys[config.convert(configKey)].set(k) config.version.version.set("1.6.0.0") config.save() if "-causeError" in sys.argv: raise ValueError("Error requested via -causeError") while True: try: rootwidget.run() except (SystemExit, KeyboardInterrupt): print "Shutting down..." exc_txt = traceback.format_exc() if mcedit.editor.level: if config.settings.savePositionOnClose.get(): mcedit.editor.waypointManager.saveLastPosition(mcedit.editor.mainViewport, mcedit.editor.level.dimNo) mcedit.editor.waypointManager.save() # The following Windows specific code won't be executed if we're using '--debug-wm' switch. if not USE_WM and sys.platform == "win32" and config.settings.setWindowPlacement.get(): (flags, showCmd, ptMin, ptMax, rect) = mcplatform.win32gui.GetWindowPlacement( display.get_wm_info()['window']) X, Y, r, b = rect if (showCmd == mcplatform.win32con.SW_MINIMIZE or showCmd == mcplatform.win32con.SW_SHOWMINIMIZED): showCmd = mcplatform.win32con.SW_SHOWNORMAL config.settings.windowX.set(X) config.settings.windowY.set(Y) config.settings.windowShowCmd.set(showCmd) # Restore the previous language if we ran with '-tt' (update translation template). if albow.translate.buildTemplate: logging.warning('Restoring %s.' % orglang) config.settings.langCode.set(orglang) # config.save() mcedit.editor.renderer.discardAllChunks() mcedit.editor.deleteAllCopiedSchematics() if mcedit.editor.level: mcedit.editor.level.close() mcedit.editor.root.RemoveEditFiles() if 'SystemExit' in traceback.format_exc() or 'KeyboardInterrupt' in traceback.format_exc(): raise else: if 'SystemExit' in exc_txt: raise SystemExit if 'KeyboardInterrupt' in exc_txt: raise KeyboardInterrupt except MemoryError: traceback.print_exc() mcedit.editor.handleMemoryError()
def resized(self, dw, dh): """ Handle window resizing events. """ if DEBUG_WM: print "############################ RESIZED ############################" (w, h) = self.size config_w, config_h = config.settings.windowWidth.get(), config.settings.windowHeight.get() win = self.displayContext.win if DEBUG_WM and win: print "dw", dw, "dh", dh print "self.size (w, h) 1", self.size, "win.get_size", win.get_size() print "size 1", config_w, config_h elif DEBUG_WM and not win: print "win is None, unable to print debug messages" if win: x, y = win.get_position() if DEBUG_WM: print "position", x, y print "config pos", (config.settings.windowX.get(), config.settings.windowY.get()) if w == 0 and h == 0: # The window has been minimized, no need to draw anything. self.editor.renderer.render = False return # Mac window handling works better now, but `win` # doesn't exist. So to get this alert to show up # I'm checking if the platform is darwin. This only # works because the code block never actually references # `win`, otherwise it WOULD CRASH!!! # You cannot change further if statements like this # because they reference `win` if win or sys.platform == "darwin": # Handling too small resolutions. # Dialog texts. # "MCEdit does not support window resolutions below 1000x700.\nYou may not be able to access all functions at this resolution." # New buttons: # "Don't warn me again": disable the window popup across sessions. # Tooltip: "Disable this message. Definitively. Even the next time you start MCEdit." # "OK": dismiss the window and let go, don't pop up again for the session # Tooltip: "Continue and not see this message until you restart MCEdit" # "Cancel": resizes the window to the minimum size # Tooltip: "Resize the window to the minimum recommended resolution." # If the config showWindowSizeWarning is true and self.resizeAlert is true, show the popup if (w < 1000 or h < 680) and config.settings.showWindowSizeWarning.get(): _w = w _h = h if self.resizeAlert: answer = "_OK" # Force the size only for the dimension that needs it. if w < 1000 and h < 680: _w = 1000 _h = 680 elif w < 1000: _w = 1000 elif h < 680: _h = 680 if not albow.dialogs.ask_tied_to: answer = albow.ask( "MCEdit does not support window resolutions below 1000x700.\nYou may not be able to access all functions at this resolution.", ["Don't remind me again.", "OK", "Cancel"], default=1, cancel=1, responses_tooltips = {"Don't remind me again.": "Disable this message. Definitively. Even the next time you start MCEdit.", "OK": "Continue and not see this message until you restart MCEdit", "Cancel": "Resize the window to the minimum recommended resolution."}, tie_widget_to=True) else: if not albow.dialogs.ask_tied_to._visible: albow.dialogs.ask_tied_to._visible = True answer = albow.dialogs.ask_tied_to.present() if answer == "Don't remind me again.": config.settings.showWindowSizeWarning = False self.resizeAlert = False elif answer == "OK": w, h = self.size self.resizeAlert = False elif answer == "Cancel": w, h = _w, _h else: if albow.dialogs.ask_tied_to: albow.dialogs.ask_tied_to.dismiss("_OK") del albow.dialogs.ask_tied_to albow.dialogs.ask_tied_to = None elif (w >= 1000 or h >= 680): if albow.dialogs.ask_tied_tos: for ask_tied_to in albow.dialogs.ask_tied_tos: ask_tied_to._visible = False ask_tied_to.dismiss("_OK") ask_tied_to.set_parent(None) del ask_tied_to if not win: if w < 1000: config.settings.windowWidth.set(1000) w = 1000 x = config.settings.windowX.get() if h < 680: config.settings.windowHeight.set(680) h = 680 y = config.settings.windowY.get() if not self.editor.renderer.render: self.editor.renderer.render = True save_geom = True if win: maximized = win.get_state() == mcplatform.MAXIMIZED sz = map(max, win.get_size(), (w, h)) if DEBUG_WM: print "sz", sz print "maximized", maximized, "self.maximized", self.maximized if maximized: if DEBUG_WM: print "maximize, saving maximized size" config.settings.windowMaximizedWidth.set(sz[0]) config.settings.windowMaximizedHeight.set(sz[1]) config.save() self.saved_pos = config.settings.windowX.get(), config.settings.windowY.get() save_geom = False self.resizing = 0 win.set_mode(sz, self.displayContext.displayMode()) else: if DEBUG_WM: print "size 2", config.settings.windowWidth.get(), config.settings.windowHeight.get() print "config_w", config_w, "config_h", config_h print "pos", config.settings.windowX.get(), config.settings.windowY.get() if self.maximized != maximized: if DEBUG_WM: print "restoring window pos and size" print "(config.settings.windowX.get(), config.settings.windowY.get())", (config.settings.windowX.get(), config.settings.windowY.get()) (w, h) = (config_w, config_h) win.set_state(1, (w, h), self.saved_pos) else: if DEBUG_WM: print "window resized" print "setting size to", (w, h), "and pos to", (x,y) win.set_mode((w, h), self.displayContext.displayMode()) win.set_position((x, y)) config.settings.windowMaximizedWidth.set(0) config.settings.windowMaximizedHeight.set(0) config.save() self.maximized = maximized if DEBUG_WM: print "self.size (w, h) 2", self.size, (w, h) surf = pygame.display.get_surface() print "display surf rect", surf.get_rect() if win: if hasattr(win.base_handler, 'get_geometry'): print "win.base_handler geometry", win.base_handler.get_geometry() print "win.base_handler.parent geometry", win.base_handler.query_tree().parent.get_geometry() print "win.base_handler.parent.parent geometry", win.base_handler.query_tree().parent.query_tree().parent.get_geometry() if save_geom: config.settings.windowWidth.set(w) config.settings.windowHeight.set(h) config.save() # The alert window is disabled if win is not None if not win and (dw > 20 or dh > 20): if not hasattr(self, 'resizeAlert'): self.resizeAlert = self.shouldResizeAlert if self.resizeAlert: albow.alert( "Window size increased. You may have problems using the cursor until MCEdit is restarted.") self.resizeAlert = False if win: win.sync() GLViewport.resized(self, dw, dh)