forked from Podshot/MCEdit-Unified
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mcedit.py
1094 lines (937 loc) · 41.4 KB
/
mcedit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# !/usr/bin/env python2.7
# -*- coding: utf_8 -*-
# import resource_packs # not the right place, moving it a bit further
#-# Modified by D.C.-G. for translation purpose
#.# Marks the layout modifications. -- D.C.-G.
from __future__ import unicode_literals
"""
mcedit.py
Startup, main menu, keyboard configuration, automatic updating.
"""
import splash
import OpenGL
import sys
import os
if "--debug-ogl" not in sys.argv:
OpenGL.ERROR_CHECKING = False
import logging
# Setup file and stderr logging.
logger = logging.getLogger()
# Set the log level up while importing OpenGL.GL to hide some obnoxious warnings about old array handlers
logger.setLevel(logging.WARN)
logger.setLevel(logging.DEBUG)
logfile = 'mcedit.log'
if sys.platform == "darwin":
logfile = os.path.expanduser("~/Library/Logs/mcedit.log")
else:
logfile = os.path.join(os.getcwdu(), logfile)
fh = logging.FileHandler(logfile, mode="w")
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.WARN)
if "--log-info" in sys.argv:
ch.setLevel(logging.INFO)
if "--log-debug" in sys.argv:
ch.setLevel(logging.DEBUG)
class FileLineFormatter(logging.Formatter):
def format(self, record):
record.__dict__['fileline'] = "%(module)s.py:%(lineno)d" % record.__dict__
record.__dict__['nameline'] = "%(name)s.py:%(lineno)d" % record.__dict__
return super(FileLineFormatter, self).format(record)
fmt = FileLineFormatter(
'[%(levelname)8s][%(nameline)30s]:%(message)s'
)
fh.setFormatter(fmt)
ch.setFormatter(fmt)
logger.addHandler(fh)
logger.addHandler(ch)
import release
if __name__ == "__main__":
start_msg = 'Starting MCEdit-Unified v%s' % release.TAG
logger.info(start_msg)
print '[ ****** ] ~~~~~~~~~~ %s' % start_msg
#---------------------------------------------------------------------
# NEW FEATURES HANDLING
#
# The idea is to be able to implement and test/use new code without stripping off the current one.
# These features/new code will be in the released stuff, but unavailable until explicitly requested.
#
# The new features which are under development can be enabled using the 'new_features.def' file.
# This file is a plain text file with one feature to enable a line.
# The file is parsed and each feature is added to the builtins using the pattern 'mcenf_<feature>'.
# The value for these builtins is 'True'.
# Then, in the code, just check if the builtins has the key 'mcenf_<feature>' to use the new version of the code:
#
# ```
# def foo_old():
# # Was 'foo', code here is the one used unless the new version is wanted.
# [...]
#
# def foo_new():
# # This is the new version of the former 'foo' (current 'foo_old').
# [...]
#
# if __builtins__.get('mcenf_foo', False):
# foo = foo_new
# else:
# foo = foo_old
#
# ```
#
if __name__ == "__main__" and '--new-features' in sys.argv:
if not os.path.exists('new_features.def'):
logger.warning("New features requested, but file 'new_features.def' not found!")
else:
logger.warning("New features mode requested.")
lines = [a.strip() for a in open('new_features.def', 'r').readlines()]
for line in lines:
_ln = line.strip()
if _ln and not _ln.startswith("#"):
setattr(__builtins__, 'mcenf_%s' % line, True)
logger.warning("Activating 'mcenf_%s'" % line)
logger.warning("New features list loaded.")
from player_cache import PlayerCache
import directories
import keys
import albow
import locale
DEF_ENC = locale.getdefaultlocale()[1]
if DEF_ENC is None:
DEF_ENC = "UTF-8"
from albow.translate import _, getPlatInfo
from albow.openglwidgets import GLViewport
from albow.root import RootWidget
from config import config
if __name__ == "__main__":
#albow.resource.resource_dir = directories.getDataDir()
albow.resource.resource_dir = directories.getDataFile()
def create_mocked_pyclark():
import imp
class MockedPyClark(object):
class Clark(object):
def report(self, *args, **kwargs):
pass
global_clark = Clark()
mod = imp.new_module('pyClark')
mod = MockedPyClark()
sys.modules['pyClark'] = mod
return mod
global pyClark
pyClark = None
if getattr(sys, 'frozen', False) or '--report-errors' in sys.argv:
if config.settings.reportCrashes.get():
try:
import pyClark
pyClark.Clark('http://127.0.0.1', inject=True)
logger.info('Successfully setup pyClark')
except ImportError:
pyClark = create_mocked_pyclark()
logger.info('The \'pyClark\' module has not been installed, disabling error reporting')
pass
else:
logger.info('User has opted out of pyClark error reporting')
print type(create_mocked_pyclark())
pyClark = create_mocked_pyclark()
print pyClark
else:
pyClark = create_mocked_pyclark()
import panels
import leveleditor
# Building translation template
if __name__ == "__main__" and "-tt" in sys.argv:
sys.argv.remove('-tt')
# Overwrite the default marker to have one adapted to our specific needs.
albow.translate.buildTemplateMarker = """
### THE FOLLOWING LINES HAS BEEN ADDED BY THE TEMPLATE UPDATE FUNCTION.
### Please, consider to analyze them and remove the entries referring
### to ones containing string formatting.
###
### For example, if you have a line already defined with this text:
### My %{animal} has %d legs.
### you may find lines like these below:
### My parrot has 2 legs.
### My dog has 4 legs.
###
### You also may have unwanted partial strings, especially the ones
### used in hotkeys. Delete them too.
### And, remove this paragraph, or it will be displayed in the program...
"""
albow.translate.buildTemplate = True
albow.translate.loadTemplate()
# Save the language defined in config and set en_US as current one.
logging.warning('MCEdit is invoked to update the translation template.')
orglang = config.settings.langCode.get()
logging.warning('The actual language is %s.' % orglang)
logging.warning('Setting en_US as language for this session.')
config.settings.langCode.set('en_US')
import mceutils
import mcplatform
# The two next switches '--debug-wm' and '--no-wm' are used to debug/disable the internal window handler.
# They are exclusive. You can't debug if it is disabled.
if __name__ == "__main__":
if "--debug-wm" in sys.argv:
mcplatform.DEBUG_WM = True
if "--no-wm" in sys.argv:
mcplatform.DEBUG_WM = False
mcplatform.USE_WM = False
else:
mcplatform.setupWindowHandler()
DEBUG_WM = mcplatform.DEBUG_WM
USE_WM = mcplatform.USE_WM
#-# DEBUG
if mcplatform.hasXlibDisplay and DEBUG_WM:
print '*** Xlib version', str(mcplatform.Xlib.__version__).replace(' ', '').replace(',', '.')[1:-1], 'found in',
if os.path.expanduser('~/.local/lib/python2.7/site-packages') in mcplatform.Xlib.__file__:
print 'user\'s',
else:
print 'system\'s',
print 'libraries.'
#-#
from mcplatform import platform_open
import numpy
from pymclevel.minecraft_server import ServerJarStorage
import os.path
import pygame
from pygame import display, rect
import pymclevel
import shutil
import traceback
import threading
from utilities.gl_display_context import GLDisplayContext
import mclangres
from utilities import mcver_updater, mcworld_support
getPlatInfo(OpenGL=OpenGL, numpy=numpy, pygame=pygame)
ESCAPE = '\033'
class MCEdit(GLViewport):
def_enc = DEF_ENC
def __init__(self, displayContext, *args):
if DEBUG_WM:
print "############################ __INIT__ ###########################"
self.resizeAlert = config.settings.showWindowSizeWarning.get()
self.maximized = config.settings.windowMaximized.get()
self.saved_pos = config.settings.windowX.get(), config.settings.windowY.get()
if displayContext.win and DEBUG_WM:
print "* self.displayContext.win.state", displayContext.win.get_state()
print "* self.displayContext.win.position", displayContext.win.get_position()
self.dis = None
self.win = None
self.wParent = None
self.wGrandParent = None
self.linux = False
if sys.platform == 'linux2' and mcplatform.hasXlibDisplay:
self.linux = True
self.dis = dis = mcplatform.Xlib.display.Display()
self.win = win = dis.create_resource_object('window', display.get_wm_info()['window'])
curDesk = os.environ.get('XDG_CURRENT_DESKTOP')
if curDesk in ('GNOME', 'X-Cinnamon', 'Unity'):
self.geomReciever = self.maximizeHandler = wParent = win.query_tree().parent
self.geomSender = wGrandParent = wParent.query_tree().parent
elif curDesk == 'KDE':
self.maximizeHandler = win.query_tree().parent
wParent = win.query_tree().parent.query_tree().parent
wGrandParent = wParent.query_tree().parent.query_tree().parent
self.geomReciever = self.geomSender = win.query_tree().parent.query_tree().parent.query_tree().parent
else:
self.maximizeHandler = self.geomReciever = self.geomSender = wGrandParent = wParent = None
self.wParent = wParent
self.wGrandParent = wGrandParent
root = dis.screen().root
windowID = root.get_full_property(dis.intern_atom('_NET_ACTIVE_WINDOW'), mcplatform.Xlib.X.AnyPropertyType).value[0]
print "###\nwindowID", windowID
window = dis.create_resource_object('window', windowID)
print "###\nwindow.get_geometry()", window.get_geometry()
print "###\nself.win", self.win.get_geometry()
print "###\nself.wParent.get_geometry()", self.wParent.get_geometry()
print "###\nself.wGrandParent.get_geometry()", self.wGrandParent.get_geometry()
try:
print "###\nself.wGrandParent.query_tree().parent.get_geometry()", self.wGrandParent.query_tree().parent.get_geometry()
except:
pass
print "###\nself.maximizeHandler.get_geometry()", self.maximizeHandler.get_geometry()
print "###\nself.geomReciever.get_geometry()", self.geomReciever.get_geometry()
print "###\nself.geomSender.get_geometry()", self.geomSender.get_geometry()
print "###\nself.win", self.win
print "###\nself.wParent", self.wParent
print "###\nself.wGrandParent", self.wGrandParent
print "###\nself.maximizeHandler", self.maximizeHandler
print "###\nself.geomReciever", self.geomReciever
print "###\nself.geomSender", self.geomSender
ws = displayContext.getWindowSize()
r = rect.Rect(0, 0, ws[0], ws[1])
GLViewport.__init__(self, r)
if DEBUG_WM:
print "self.size", self.size, "ws", ws
if displayContext.win and self.maximized:
# Send a maximize event now
displayContext.win.set_state(mcplatform.MAXIMIZED)
# Flip pygame.display to avoid to see the splash un-centered.
pygame.display.flip()
self.displayContext = displayContext
self.bg_color = (0, 0, 0, 1)
self.anchor = 'tlbr'
if not config.config.has_section("Recent Worlds"):
config.config.add_section("Recent Worlds")
self.setRecentWorlds([""] * 5)
self.optionsPanel = panels.OptionsPanel(self)
if not albow.translate.buildTemplate:
self.optionsPanel.getLanguageChoices()
lng = config.settings.langCode.get()
if lng not in self.optionsPanel.sgnal:
lng = "en_US"
config.settings.langCode.set(lng)
albow.translate.setLang(lng)
# Set the window caption here again, since the initialization is done through several steps...
display.set_caption(('MCEdit ~ ' + release.get_version() % _("for")).encode('utf-8'), 'MCEdit')
self.optionsPanel.initComponents()
self.graphicsPanel = panels.GraphicsPanel(self)
#.#
self.keyConfigPanel = keys.KeyConfigPanel(self)
#.#
self.droppedLevel = None
self.nbtCopyBuffer = None
self.reloadEditor()
"""
check command line for files dropped from explorer
"""
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
f = arg.decode(sys.getfilesystemencoding())
if os.path.isdir(os.path.join(pymclevel.minecraftSaveFileDir, f)):
f = os.path.join(pymclevel.minecraftSaveFileDir, f)
self.droppedLevel = f
break
if os.path.exists(f):
self.droppedLevel = f
break
self.fileOpener = albow.FileOpener(self)
self.add(self.fileOpener)
self.fileOpener.focus()
#-# Translation live updtate preparation
def set_update_ui(self, v):
GLViewport.set_update_ui(self, v)
if v:
#&# Prototype for blocks/items names
if self.editor.level:
if self.editor.level.gamePlatform == "Java": # added this so the original functionality of this function does not change
mclangres.buildResources(self.editor.level.gameVersionNumber, albow.translate.getLang())
else:
mclangres.buildResources(self.editor.level.gamePlatform, albow.translate.getLang())
#&#
self.keyConfigPanel = keys.KeyConfigPanel(self)
self.graphicsPanel = panels.GraphicsPanel(self)
if self.fileOpener in self.subwidgets:
idx = self.subwidgets.index(self.fileOpener)
self.remove(self.fileOpener)
self.fileOpener = albow.FileOpener(self)
if idx is not None:
self.add(self.fileOpener)
self.fileOpener.focus()
#-#
editor = None
def reloadEditor(self):
reload(leveleditor)
level = None
pos = None
if self.editor:
level = self.editor.level
self.remove(self.editor)
c = self.editor.mainViewport
pos, yaw, pitch = c.position, c.yaw, c.pitch
self.editor = leveleditor.LevelEditor(self)
self.editor.anchor = 'tlbr'
if level:
self.add(self.editor)
self.editor.gotoLevel(level)
self.focus_switch = self.editor
if pos is not None:
c = self.editor.mainViewport
c.position, c.yaw, c.pitch = pos, yaw, pitch
def add_right(self, widget):
w, h = self.size
widget.centery = h // 2
widget.right = w
self.add(widget)
def showOptions(self):
self.optionsPanel.present()
def showGraphicOptions(self):
self.graphicsPanel.present()
def showKeyConfig(self):
self.keyConfigPanel.presentControls()
def loadRecentWorldNumber(self, i):
worlds = list(self.recentWorlds())
if i - 1 < len(worlds):
self.loadFile(worlds[i - 1])
numRecentWorlds = 5
@staticmethod
def removeLevelDat(filename):
if filename.endswith("level.dat"):
filename = os.path.dirname(filename)
return filename
def recentWorlds(self):
worlds = []
for i in xrange(self.numRecentWorlds):
if config.config.has_option("Recent Worlds", str(i)):
try:
filename = (config.config.get("Recent Worlds", str(i)).decode('utf-8'))
worlds.append(self.removeLevelDat(filename))
except Exception as e:
logging.error(repr(e))
return list((f for f in worlds if f and os.path.exists(f)))
def addRecentWorld(self, filename):
filename = self.removeLevelDat(filename)
rw = list(self.recentWorlds())
if filename in rw:
return
rw = [filename] + rw[:self.numRecentWorlds - 1]
self.setRecentWorlds(rw)
@staticmethod
def setRecentWorlds(worlds):
for i, filename in enumerate(worlds):
config.config.set("Recent Worlds", str(i), filename.encode('utf-8'))
def makeSideColumn1(self):
def showLicense():
#platform_open(os.path.join(directories.getDataDir(), "LICENSE.txt"))
platform_open(directories.getDataFile('LICENSE.txt'))
def refresh():
PlayerCache().force_refresh()
def update_mcver():
num = mcver_updater.run()
if num is None:
albow.alert("Error Updating")
elif num:
albow.alert("Version Definitions have been updated!\n\nPlease restart MCEdit-Unified to apply the changes")
else:
albow.alert("Version Definitions are already up-to-date!")
hotkeys = ([("",
"Controls",
self.showKeyConfig),
("",
"Graphics",
self.showGraphicOptions),
("",
"Options",
self.showOptions),
("",
"Homepage",
lambda: platform_open("http://www.mcedit-unified.net"),
"http://www.mcedit-unified.net"),
("",
"About MCEdit",
lambda: platform_open("http://www.mcedit-unified.net/about.html"),
"http://www.mcedit-unified.net/about.html"),
("",
"License",
showLicense,
#os.path.join(directories.getDataDir(), "LICENSE.txt")),
directories.getDataFile('LICENSE.txt')),
("",
"Refresh Player Names",
refresh),
("",
"Update Version Definitions",
update_mcver)
])
c = albow.HotkeyColumn(hotkeys)
return c
def makeSideColumn2(self):
def showCacheDir():
try:
os.mkdir(directories.getCacheDir())
except OSError:
pass
platform_open(directories.getCacheDir())
def showScreenshotsDir():
try:
os.mkdir(os.path.join(directories.getCacheDir(), "screenshots"))
except OSError:
pass
platform_open(os.path.join(directories.getCacheDir(), "screenshots"))
hotkeys = ([("",
"Config Files",
showCacheDir,
directories.getCacheDir()),
("",
"Screenshots",
showScreenshotsDir,
os.path.join(directories.getCacheDir(), "screenshots"))
])
c = albow.HotkeyColumn(hotkeys)
return c
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)
shouldResizeAlert = config.settings.shouldResizeAlert.property()
def loadFile(self, filename, addToRecent=True):
if os.path.exists(filename):
if filename.endswith(".mcworld"):
filename = mcworld_support.open_world(filename)
addToRecent = False
try:
self.editor.loadFile(filename, addToRecent=addToRecent)
except NotImplementedError as e:
albow.alert(e.message)
return None
except Exception as e:
logging.error(u'Failed to load file {0}: {1!r}'.format(
filename, e))
return None
self.remove(self.fileOpener)
self.fileOpener = None
if self.editor.level:
self.editor.size = self.size
self.add(self.editor)
self.focus_switch = self.editor
def createNewWorld(self):
level = self.editor.createNewLevel()
if level:
self.remove(self.fileOpener)
self.editor.size = self.size
self.add(self.editor)
self.focus_switch = self.editor
albow.alert(
"World created. To expand this infinite world, explore the world in Minecraft or use the Chunk Control tool to add or delete chunks.")
def removeEditor(self):
self.remove(self.editor)
self.fileOpener = albow.FileOpener(self)
self.add(self.fileOpener)
self.focus_switch = self.fileOpener
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 saveAndQuit(self):
self.editor.saveFile()
raise SystemExit
@staticmethod
def justQuit():
raise SystemExit
@classmethod
def fetch_version(cls):
with cls.version_lock:
cls.version_info = release.fetch_new_version_info()
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"]))
@classmethod
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 saveWindowPosition(self):
"""Save the window position in the configuration handler."""
if DEBUG_WM:
print "############################ EXITING ############################"
win = self.displayContext.win
# The following Windows specific code will not 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)
elif win:
config.settings.windowMaximized.set(self.maximized)
if not self.maximized:
x, y = win.get_position()
else:
x, y = self.saved_pos
if DEBUG_WM:
print "x", x, "y", y
config.settings.windowX.set(x)
config.settings.windowY.set(y)
def restart(self):
self.saveWindowPosition()
config.save()
self.editor.renderer.discardAllChunks()
self.editor.deleteAllCopiedSchematics()
if self.editor.level:
self.editor.level.close()
self.editor.root.RemoveEditFiles()
python = sys.executable
if sys.argv[0].endswith('.exe') or hasattr(sys, 'frozen'):
os.execl(python, python, *sys.argv[1:])
else:
os.execl(python, python, *sys.argv)
def main(argv):
"""
Setup display, bundled schematics. Handle unclean
shutdowns.
"""
try:
display.init()
except pygame.error:
os.environ['SDL_VIDEODRIVER'] = 'directx'
try:
display.init()
except pygame.error:
os.environ['SDL_VIDEODRIVER'] = 'windib'
display.init()
pygame.font.init()
try:
if not os.path.exists(directories.schematicsDir):
shutil.copytree(
#os.path.join(directories.getDataDir(), u'stock-schematics'),
directories.getDataFile('stock-schematics'),
directories.schematicsDir
)
except Exception as e:
logging.warning('Error copying bundled schematics: {0!r}'.format(e))
try:
os.mkdir(directories.schematicsDir)