-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7d2d_server_config_editor.py
More file actions
2226 lines (1912 loc) · 93.8 KB
/
7d2d_server_config_editor.py
File metadata and controls
2226 lines (1912 loc) · 93.8 KB
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 python3
# type: ignore
"""
7 Days to Die Server Configuration Editor™
A comprehensive Tkinter GUI for editing serverconfig.xml with meticulous attention to design details.
Version: 1.2.6
Author: Dance Monkey Dance Studios™
License: GNU AFFERO GENERAL PUBLIC LICENSE Version 3
"""
import os
import re
import sys
import json
import platform
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from datetime import datetime
import shutil
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from tkinter import font as tkfont
import threading
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import subprocess
import webbrowser
from urllib.parse import quote
from PIL import Image, ImageTk
# ============================================================================
# RESOURCE PATH HELPER (PyInstaller Support)
# ============================================================================
def resource_path(relative_path):
"""Get absolute path to resource, works for dev and for PyInstaller."""
try:
base_path = sys._MEIPASS # PyInstaller temp dir
except:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
# ============================================================================
# CORE CONFIGURATION
# ============================================================================
DEFAULT_CONFIG_PATH = r"C:\Program Files (x86)\Steam\steamapps\common\7 Days to Die Dedicated Server\serverconfig.xml"
SETTINGS_FILE = os.path.join(os.path.expanduser("~"), ".7d2d_config_editor_settings.json")
# EXACT property mappings per specification
TAB_DEFINITIONS = {
"🔧 General": [
"ServerName", "ServerDescription", "ServerWebsiteURL", "ServerPassword",
"ServerLoginConfirmationText", "Region", "Language", "ServerPort",
"ServerVisibility", "ServerDisabledNetworkProtocols", "ServerMaxWorldTransferSpeedKiBs",
"ServerMaxPlayerCount", "ServerReservedSlots", "ServerReservedSlotsPermission",
"ServerAdminSlots", "ServerAdminSlotsPermission", "WebDashboardEnabled",
"WebDashboardPort", "WebDashboardUrl", "EnableMapRendering", "TelnetEnabled",
"TelnetPort", "TelnetPassword", "TelnetFailedLoginLimit", "TelnetFailedLoginsBlocktime",
"TerminalWindowEnabled", "AdminFileName", "ServerAllowCrossplay", "EACEnabled",
"IgnoreEOSSanctions", "HideCommandExecutionLog", "MaxUncoveredMapChunksPerPlayer"
],
"🌍 World": [
"PersistentPlayerProfiles", "MaxChunkAge", "SaveDataLimit", "GameWorld",
"WorldGenSeed", "WorldGenSize", "GameName", "GameMode"
],
"⚔️ Difficulty": [
"GameDifficulty", "BlockDamagePlayer", "BlockDamageAI", "BlockDamageAIBM",
"XPMultiplier", "PlayerSafeZoneLevel", "PlayerSafeZoneHours"
],
"📜 Rules": [
"BuildCreate", "DayNightLength", "DayLightLength", "BiomeProgression",
"StormFreq", "DeathPenalty", "DropOnDeath", "DropOnQuit",
"BedrollDeadZoneSize", "BedrollExpiryTime", "AllowSpawnNearFriend",
"CameraRestrictionMode", "JarRefund"
],
"⚡ Performance": [
"MaxSpawnedZombies", "MaxSpawnedAnimals", "ServerMaxAllowedViewDistance",
"MaxQueuedMeshLayers"
],
"🧟 Zombies": [
"EnemySpawnMode", "EnemyDifficulty", "ZombieFeralSense", "ZombieMove",
"ZombieMoveNight", "ZombieFeralMove", "ZombieBMMove", "AISmellMode",
"BloodMoonFrequency", "BloodMoonRange", "BloodMoonWarning", "BloodMoonEnemyCount"
],
"💰 Loot": [
"LootAbundance", "LootRespawnDays", "AirDropFrequency", "AirDropMarker"
],
"👥 Multiplayer": [
"PartySharedKillRange", "PlayerKillingMode"
],
"🏠 Claims": [
"LandClaimCount", "LandClaimSize", "LandClaimDeadZone", "LandClaimExpiryTime",
"LandClaimDecayMode", "LandClaimOnlineDurabilityModifier", "LandClaimOfflineDurabilityModifier",
"LandClaimOfflineDelay", "DynamicMeshEnabled", "DynamicMeshLandClaimOnly",
"DynamicMeshLandClaimBuffer", "DynamicMeshMaxItemCache"
],
"🎮 Other": [
"TwitchServerPermission", "TwitchBloodMoonAllowed", "QuestProgressionDailyLimit"
]
}
# Comprehensive property descriptions
PROPERTY_DESCRIPTIONS = {
"ServerName": "Whatever you want the name of the server to be.",
"ServerDescription": "Whatever you want the server description to be, will be shown in the server browser.",
"ServerWebsiteURL": "Website URL for the server, will be shown in the server browser as a clickable link",
"ServerPassword": "Password to gain entry to the server",
"ServerLoginConfirmationText": "If set the user will see the message during joining the server and has to confirm it before continuing. For more complex changes to this window you can change the \"serverjoinrulesdialog\" window in XUi",
"Region": "The region this server is in. Values: NorthAmericaEast, NorthAmericaWest, CentralAmerica, SouthAmerica, Europe, Russia, Asia, MiddleEast, Africa, Oceania",
"Language": "Primary language for players on this server. Values: Use any language name that you would users expect to search for. Should be the English name of the language, e.g. not \"Deutsch\" but \"German\"",
"ServerPort": "Port you want the server to listen on. Keep it in the ranges 26900 to 26905 or 27015 to 27020 if you want PCs on the same LAN to find it as a LAN server.",
"ServerVisibility": "Visibility of this server: 2 = public, 1 = only shown to friends, 0 = not listed. As you are never friend of a dedicated server setting this to \"1\" will only work when the first player connects manually by IP.",
"ServerDisabledNetworkProtocols": "Networking protocols that should not be used. Separated by comma. Possible values: LiteNetLib, SteamNetworking. Dedicated servers should disable SteamNetworking if there is no NAT router in between your users and the server or when port-forwarding is set up correctly",
"ServerMaxWorldTransferSpeedKiBs": "Maximum (!) speed in kiB/s the world is transferred at to a client on first connect if it does not have the world yet. Maximum is about 1300 kiB/s, even if you set a higher value.",
"ServerMaxPlayerCount": "Maximum Concurrent Players",
"ServerReservedSlots": "Out of the MaxPlayerCount this many slots can only be used by players with a specific permission level",
"ServerReservedSlotsPermission": "Required permission level to use reserved slots above",
"ServerAdminSlots": "This many admins can still join even if the server has reached MaxPlayerCount",
"ServerAdminSlotsPermission": "Required permission level to use the admin slots above",
"WebDashboardEnabled": "Enable/disable the web dashboard",
"WebDashboardPort": "Port of the web dashboard",
"WebDashboardUrl": "External URL to the web dashboard if not just using the public IP of the server, e.g. if the web dashboard is behind a reverse proxy. Needs to be the full URL, like \"https://domainOfReverseProxy.tld:1234/\". Can be left empty if directly using the public IP and dashboard port",
"EnableMapRendering": "Enable/disable rendering of the map to tile images while exploring it. This is used e.g. by the web dashboard to display a view of the map.",
"TelnetEnabled": "Enable/Disable the telnet",
"TelnetPort": "Port of the telnet server",
"TelnetPassword": "Password to gain entry to telnet interface. If no password is set the server will only listen on the local loopback interface",
"TelnetFailedLoginLimit": "After this many wrong passwords from a single remote client the client will be blocked from connecting to the Telnet interface",
"TelnetFailedLoginsBlocktime": "How long will the block persist (in seconds)",
"TerminalWindowEnabled": "Show a terminal window for log output / command input (Windows only)",
"AdminFileName": "Server admin file name. Path relative to UserDataFolder/Saves",
"ServerAllowCrossplay": "Enables/Disables crossplay, crossplay servers will only be found in searches and joinable if sanctions are not ignored, and have a default or fewer player slot count",
"EACEnabled": "Enables/Disables EasyAntiCheat",
"IgnoreEOSSanctions": "Ignore EOS sanctions when allowing players to join",
"HideCommandExecutionLog": "Hide logging of command execution. 0 = show everything, 1 = hide only from Telnet/ControlPanel, 2 = also hide from remote game clients, 3 = hide everything",
"MaxUncoveredMapChunksPerPlayer": "Override how many chunks can be uncovered on the in-game map by each player. Resulting max map file size limit per player is (x * 512 Bytes), uncovered area is (x * 256 m²). Default 131072 means max 32 km² can be uncovered at any time",
"PersistentPlayerProfiles": "If disabled a player can join with any selected profile. If true they will join with the last profile they joined with",
"MaxChunkAge": "The number of in-game days which must pass since visiting a chunk before it will reset to its original state if not revisited or protected (e.g. by a land claim or bedroll being in close proximity).",
"SaveDataLimit": "The maximum disk space allowance for each saved game in megabytes (MB). Saved chunks may be forcibly reset to their original states to free up space when this limit is reached. Negative values disable the limit.",
"GameWorld": "\"RWG\" (see WorldGenSeed and WorldGenSize options below) or any already existing world name in the Worlds folder (currently shipping with e.g. \"Navezgane\", \"Pregen06k01\", \"Pregen06k02\", \"Pregen08k01\", \"Pregen08k02\", ...)",
"WorldGenSeed": "If RWG this is the seed for the generation of the new world. If a world with the resulting name already exists it will simply load it",
"WorldGenSize": "6144, 8192, 10240 If GameWorld = RWG, this controls the width and height of the created world. Officially supported sizes are between 6144 and 10240 and must be a multiple of 2048, e.g. 6144, 8192, 10240.",
"GameName": "Whatever you want the game name to be (allowed [A-Za-z0-9_-. ]). This affects the save game name as well as the seed used when placing decoration (trees etc.) in the world. It does not control the generic layout of the world if creating an RWG world",
"GameMode": "GameModeSurvival",
"GameDifficulty": "0 - 5, 0=easiest, 5=hardest",
"BlockDamagePlayer": "How much damage do players to blocks (percentage in whole numbers)",
"BlockDamageAI": "How much damage do AIs to blocks (percentage in whole numbers)",
"BlockDamageAIBM": "How much damage do AIs during blood moons to blocks (percentage in whole numbers)",
"XPMultiplier": "XP gain multiplier (percentage in whole numbers)",
"PlayerSafeZoneLevel": "If a player is less or equal this level he will create a safe zone (no enemies) when spawned",
"PlayerSafeZoneHours": "Hours in world time this safe zone exists",
"BuildCreate": "cheat mode on/off",
"DayNightLength": "real time minutes per in game day: 60 minutes",
"DayLightLength": "in game hours the sun shines per day: 18 hours day light per in game day",
"BiomeProgression": "Enables biome hazards and loot stage caps to promote biome progression. Loot stage caps are increased by completing biome challenges.",
"StormFreq": "Adjusts the frequency of storms. 0% turns them off. Vanilla values: 0, 50, 100, 150, 200, 300, 400, 500",
"DeathPenalty": "Penalty after dying. 0 = Nothing. 1 = Default: Classic XP Penalty. 2 = Injured: You keep most of your de-buffs. Food and Water is set to 50% on respawn. 3 = Permanent Death: Your character is completely reset. You will respawn with a fresh start within the saved game.",
"DropOnDeath": "0 = nothing, 1 = everything, 2 = toolbelt only, 3 = backpack only, 4 = delete all",
"DropOnQuit": "0 = nothing, 1 = everything, 2 = toolbelt only, 3 = backpack only",
"BedrollDeadZoneSize": "Size (box \"radius\", so a box with 2 times the given value for each side's length) of bedroll dead zone, no zombies will spawn inside this area, and any cleared sleeper volumes that touch a bedroll deadzone will not spawn after they've been cleared.",
"BedrollExpiryTime": "Number of real world days a bedroll stays active after owner was last online",
"AllowSpawnNearFriend": "Can new players joining the server for the first time select to join near any friend playing at the same time? 0 = Disabled, 1 = Always, 2 = Only near friends in forest biome",
"CameraRestrictionMode": "0 = Players can freely swap between first and third person camera modes, 1 = Restricted to first person, 2 = Restricted to third person",
"JarRefund": "0, 5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100% The empty jar refund percentage after consuming an item.",
"MaxSpawnedZombies": "This setting covers the entire map. There can only be this many zombies on the entire map at one time. Changing this setting has a huge impact on performance.",
"MaxSpawnedAnimals": "If your server has a large number of players you can increase this limit to add more wildlife. Animals don't consume as much CPU as zombies. NOTE: That this doesn't cause more animals to spawn arbitrarily: The biome spawning system only spawns a certain number of animals in a given area, but if you have lots of players that are all spread out then you may be hitting the limit and can increase it.",
"ServerMaxAllowedViewDistance": "Max view distance a client may request (6 - 12). High impact on memory usage and performance.",
"MaxQueuedMeshLayers": "Maximum amount of Chunk mesh layers that can be enqueued during mesh generation. Reducing this will improve memory usage but may increase Chunk generation time",
"EnemySpawnMode": "Enable/Disable enemy spawning",
"EnemyDifficulty": "0 = Normal, 1 = Feral",
"ZombieFeralSense": "0-3 (Off, Day, Night, All)",
"ZombieMove": "0-4 (walk, jog, run, sprint, nightmare)",
"ZombieMoveNight": "0-4 (walk, jog, run, sprint, nightmare)",
"ZombieFeralMove": "0-4 (walk, jog, run, sprint, nightmare)",
"ZombieBMMove": "0-4 (walk, jog, run, sprint, nightmare)",
"AISmellMode": "0-5 (off, walk, jog, run, sprint, nightmare)",
"BloodMoonFrequency": "What frequency (in days) should a blood moon take place. Set to \"0\" for no blood moons",
"BloodMoonRange": "How many days can the actual blood moon day randomly deviate from the above setting. Setting this to 0 makes blood moons happen exactly each Nth day as specified in BloodMoonFrequency",
"BloodMoonWarning": "The Hour number that the red day number begins on a blood moon day. Setting this to -1 makes the red never show.",
"BloodMoonEnemyCount": "This is the number of zombies that can be alive (spawned at the same time) at any time PER PLAYER during a blood moon horde, however, MaxSpawnedZombies overrides this number in multiplayer games. Also note that your game stage sets the max number of zombies PER PARTY. Low game stage values can result in lower number of zombies than the BloodMoonEnemyCount setting. Changing this setting has a huge impact on performance.",
"LootAbundance": "Percentage in whole numbers",
"LootRespawnDays": "Days in whole numbers",
"AirDropFrequency": "How often airdrop occur in game-hours, 0 == never",
"AirDropMarker": "Sets if a marker is added to map/compass for air drops.",
"PartySharedKillRange": "The distance you must be within to receive party shared kill XP and quest party kill objective credit.",
"PlayerKillingMode": "Player Killing Settings (0 = No Killing, 1 = Kill Allies Only, 2 = Kill Strangers Only, 3 = Kill Everyone)",
"LandClaimCount": "Maximum allowed land claims per player.",
"LandClaimSize": "Size in blocks that is protected by a keystone",
"LandClaimDeadZone": "Keystones must be this many blocks apart (unless you are friends with the other player)",
"LandClaimExpiryTime": "The number of real world days a player can be offline before their claims expire and are no longer protected",
"LandClaimDecayMode": "Controls how offline players land claims decay. 0=Slow (Linear) , 1=Fast (Exponential), 2=None (Full protection until claim is expired).",
"LandClaimOnlineDurabilityModifier": "How much protected claim area block hardness is increased when a player is online. 0 means infinite (no damage will ever be taken). Default is 4x",
"LandClaimOfflineDurabilityModifier": "How much protected claim area block hardness is increased when a player is offline. 0 means infinite (no damage will ever be taken). Default is 4x",
"LandClaimOfflineDelay": "The number of minutes after a player logs out that the land claim area hardness transitions from online to offline. Default is 0",
"DynamicMeshEnabled": "Is Dynamic Mesh system enabled",
"DynamicMeshLandClaimOnly": "Is Dynamic Mesh system only active in player LCB areas",
"DynamicMeshLandClaimBuffer": "Dynamic Mesh LCB chunk radius",
"DynamicMeshMaxItemCache": "How many items can be processed concurrently, higher values use more RAM",
"TwitchServerPermission": "Required permission level to use twitch integration on the server",
"TwitchBloodMoonAllowed": "If the server allows twitch actions during a blood moon. This could cause server lag with extra zombies being spawned during blood moon.",
"QuestProgressionDailyLimit": "Limits the number of quests that contribute to quest tier progression a player can complete each day. Quests after the limit can still be completed for rewards.",
}
# ============================================================================
# UTILITY CLASSES
# ============================================================================
class ToolTip:
"""Tooltip widget that appears on hover with word wrapping."""
def __init__(self, widget, text: str):
self.widget = widget
self.text = text
self.tip_window = None
self.id = None
self.x = self.y = 0
widget.bind("<Enter>", self._on_enter, add="+")
widget.bind("<Leave>", self._on_leave, add="+")
widget.bind("<Motion>", self._on_motion, add="+")
def _on_enter(self, event):
self._schedule_show()
def _on_motion(self, event):
self.x, self.y = event.x_root + 15, event.y_root + 15
if self.tip_window:
self.tip_window.wm_geometry(f"+{self.x}+{self.y}")
def _on_leave(self, event):
self._cancel_show()
self._hide()
def _schedule_show(self):
self._cancel_show()
self.id = self.widget.after(500, self._show)
def _cancel_show(self):
if self.id:
self.widget.after_cancel(self.id)
self.id = None
def _show(self):
if self.tip_window or not self.text:
return
self.tip_window = tw = tk.Toplevel(self.widget)
tw.wm_overrideredirect(True)
tw.wm_geometry(f"+{self.x}+{self.y}")
label = tk.Label(
tw,
text=self.text,
background="#ffffe0",
foreground="#000000",
relief=tk.SOLID,
borderwidth=1,
font=("Segoe UI", 9),
wraplength=350,
justify=tk.LEFT,
padx=8,
pady=6
)
label.pack()
try:
tw.attributes('-topmost', True)
except tk.TclError:
pass
def _hide(self):
if self.tip_window:
self.tip_window.destroy()
self.tip_window = None
class ScrollableFrame(ttk.Frame):
"""Canvas-based scrollable frame with mousewheel support."""
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
# Create canvas
self.canvas = tk.Canvas(self, bg="#f0f0f0", highlightthickness=0, height=400)
scrollbar = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
# Create scrollable frame
self.scrollable_frame = ttk.Frame(self.canvas)
self.scrollable_frame.bind(
"<Configure>",
lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all"))
)
# Place frame in canvas
self.canvas_window = self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
self.canvas.configure(yscrollcommand=scrollbar.set)
# Pack widgets
self.canvas.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
# Bind mousewheel
self.canvas.bind_all("<MouseWheel>", self._on_mousewheel)
self.canvas.bind_all("<Button-4>", self._on_mousewheel_linux)
self.canvas.bind_all("<Button-5>", self._on_mousewheel_linux)
def _on_mousewheel(self, event):
"""Handle Windows mousewheel."""
self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
def _on_mousewheel_linux(self, event):
"""Handle Linux mousewheel."""
if event.num == 4:
self.canvas.yview_scroll(-3, "units")
elif event.num == 5:
self.canvas.yview_scroll(3, "units")
# ============================================================================
# XML UTILITIES
# ============================================================================
def extract_comments_from_xml(filepath: str) -> Dict[str, str]:
"""Extract comments that appear after property elements on the same line.
Looks for:
<property name="PropertyName" value="..." /> <!-- Comment text -->
Returns mapping of property names to comment text.
"""
comments = {}
try:
with open(filepath, 'r', encoding='utf-8', errors='replace') as f:
content = f.read()
except Exception:
return comments
# Pattern: property tag followed by comment on same line
# <property name="PropName" ... /> <!-- comment -->
pattern = re.compile(
r'<\s*property\s+[^>]*?name\s*=\s*["\']([^"\']+)["\'][^>]*?/>\s*<!--\s*(.*?)\s*-->',
re.IGNORECASE
)
for match in pattern.finditer(content):
prop_name = match.group(1)
comment_text = match.group(2).strip()
if prop_name and comment_text:
# Normalize whitespace in comment
comment_text = re.sub(r'\s+', ' ', comment_text)
comments[prop_name] = comment_text
return comments
def repair_xml_encoding(filepath: str) -> bool:
"""Repair common XML encoding issues without modifying original until save.
Handles:
- UTF-8 BOM removal
- UTF-16 detection and conversion
- Stray bytes before XML declaration
"""
try:
with open(filepath, 'rb') as f:
original_data = f.read()
data = bytearray(original_data)
modified = False
# Check and remove UTF-8 BOM
if data.startswith(b'\xef\xbb\xbf'):
data = data[3:]
modified = True
# Check for UTF-16 LE BOM and convert
elif data.startswith(b'\xff\xfe'):
try:
text = bytes(data).decode('utf-16-le')
data = bytearray(text.encode('utf-8'))
modified = True
except Exception:
pass
# Check for UTF-16 BE BOM and convert
elif data.startswith(b'\xfe\xff'):
try:
text = bytes(data).decode('utf-16-be')
data = bytearray(text.encode('utf-8'))
modified = True
except Exception:
pass
# Remove stray bytes before XML declaration
xml_start = bytes(data).find(b'<?xml')
if xml_start > 0:
data = data[xml_start:]
modified = True
# Verify it's valid XML
try:
ET.fromstring(bytes(data))
except ET.ParseError as e:
return False
return modified
except Exception:
return False
# ============================================================================
# MAIN APPLICATION CLASS
# ============================================================================
class ServerConfigEditor:
"""Main application for 7 Days to Die server configuration editing."""
VERSION = "1.2.6"
def __init__(self, root):
self.root = root
self.root.title("7 Days to Die Server Config Editor™")
self.root.geometry("1200x750")
self.root.minsize(900, 600)
self.root.configure(bg="#f0f0f0")
# Set window icon with multiple methods for best compatibility
try:
icon_path = resource_path('icon.ico')
# Method 1: iconbitmap (for window border)
self.root.iconbitmap(default=icon_path)
# Method 2: iconphoto (for taskbar on some systems)
try:
# Load icon and convert to PhotoImage
icon_img = Image.open(icon_path)
# Use the largest size from the ico (usually 256x256 or 128x128)
icon_photo = ImageTk.PhotoImage(icon_img)
# Store reference to prevent garbage collection
self.root.icon_photo = icon_photo
self.root.iconphoto(True, icon_photo)
except Exception as e:
print(f"Debug: iconphoto failed: {e}")
# Method 3: Set window attributes for Windows
if platform.system() == 'Windows':
try:
# Force update the window
self.root.update_idletasks()
except:
pass
except Exception as e:
print(f"Debug: Icon loading failed: {e}")
# Center window on screen
self._center_window()
# Data
self.config_file = DEFAULT_CONFIG_PATH
self.xml_tree = None
self.xml_root = None
self.properties_map = {} # name -> Element
self.property_vars = {} # name -> tk.StringVar
self.comments = {} # name -> comment text
self.property_rows = {} # name -> (Frame, tab_name) tuple
self.is_dirty = False
# Load saved settings
self._load_settings()
# Load tooltip icon image
self.tooltip_icon_photo = None
self._load_tooltip_icon()
# Search tracking
self.search_results = [] # List of (tab_name, prop_name) tuples
self.current_result_index = 0
self.result_counter_var = tk.StringVar(value="")
# Setup styles
self._configure_styles()
# Build UI
self._build_ui()
# Load configuration
self._load_configuration()
# Window close handler
self.root.protocol("WM_DELETE_WINDOW", self._on_window_close)
# Bind shortcuts
self.root.bind("<Control-s>", lambda e: self.save_configuration())
self.root.bind("<Control-r>", lambda e: self._load_configuration())
def _configure_styles(self):
"""Configure ttk theme and colors."""
style = ttk.Style()
try:
style.theme_use("clam")
except Exception:
pass
# Configure colors for clam theme
style.configure("TFrame", background="#f0f0f0")
style.configure("TLabel", background="#f0f0f0")
style.configure("TNotebook", background="#f0f0f0")
style.configure("TNotebook.Tab", font=("Segoe UI", 10))
def _load_tooltip_icon(self):
"""Load and scale the tooltip icon image."""
try:
tooltip_icon_path = resource_path(os.path.join("Logos and Images", "tooltip-icon.png"))
if os.path.exists(tooltip_icon_path):
# Load the image
img = Image.open(tooltip_icon_path)
# Scale to 16x16 pixels to fit nicely with property box
img_resized = img.resize((16, 16), Image.Resampling.LANCZOS)
# Convert to PhotoImage
self.tooltip_icon_photo = ImageTk.PhotoImage(img_resized)
else:
print(f"Debug: Tooltip icon not found at {tooltip_icon_path}")
except Exception as e:
print(f"Debug: Failed to load tooltip icon: {e}")
def _center_window(self):
"""Center the window on the screen after it's fully rendered."""
def do_center():
self.root.update_idletasks()
# Get window dimensions
window_width = 1200
window_height = 750
# Get screen dimensions
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
# Calculate center position
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
# Ensure position is not negative
x = max(0, x)
y = max(0, y)
# Set window position
self.root.geometry(f"{window_width}x{window_height}+{x}+{y}")
# Schedule centering after window is fully initialized
self.root.after(100, do_center)
def _build_ui(self):
"""Construct the complete user interface."""
# Header bar (blue)
self._create_header()
# Menu bar
self._create_menubar()
# Search bar
self._create_search_bar()
# Notebook with tabs
self._create_notebook()
# Save/Reload buttons and bug button
self._create_action_buttons()
# Status bar
self._create_status_bar()
# Footer
self._create_footer()
def _create_header(self):
"""Create the blue header banner with logo."""
header = tk.Frame(self.root, bg="#007acc", height=70)
header.pack(fill="x", side="top")
header.pack_propagate(False)
# Load and display left logo
left_logo_url = "https://i.imgur.com/TlzRI3x.jpeg"
left_logo_path = os.path.join(os.path.expanduser("~"), ".7d2d_config_editor_left_logo.jpeg")
# Download left logo if not cached
try:
if not os.path.exists(left_logo_path):
import urllib.request
import socket
socket.setdefaulttimeout(10)
# Create request with User-Agent to bypass imgur blocks
req = urllib.request.Request(
left_logo_url,
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
)
with urllib.request.urlopen(req) as response:
with open(left_logo_path, 'wb') as out_file:
out_file.write(response.read())
except Exception as e:
print(f"Debug: Left logo download failed: {e}")
if os.path.exists(left_logo_path) and os.path.getsize(left_logo_path) > 0:
try:
# Load left logo image and resize
img = Image.open(left_logo_path)
header_height = 70
max_width = 150 # Prevent logo from being too wide
aspect_ratio = img.width / img.height
new_height = header_height - 10
new_width = int(new_height * aspect_ratio)
# Constrain width to max_width
if new_width > max_width:
new_width = max_width
new_height = int(new_width / aspect_ratio)
img_resized = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
self.left_header_photo = ImageTk.PhotoImage(img_resized)
# Create label for left logo
left_logo_label = tk.Label(
header,
image=self.left_header_photo,
bg="#007acc",
borderwidth=0
)
left_logo_label.pack(side="left", padx=20, pady=5)
except Exception as e:
print(f"Debug: Left logo display failed: {e}")
title_label = tk.Label(
header,
text="7 Days to Die Server Config Editor™",
font=("Segoe UI", 23, "bold"),
bg="#007acc",
fg="white"
)
title_label.pack(side="left", padx=20, pady=15)
# Load and display right logo (Mayhem logo)
logo_url = "https://i.imgur.com/iQaAn2V.png"
logo_path = os.path.join(os.path.expanduser("~"), ".7d2d_config_editor_logo.png")
# Download logo if not cached
try:
if not os.path.exists(logo_path):
import urllib.request
import socket
socket.setdefaulttimeout(10)
# Create request with User-Agent to bypass imgur blocks
req = urllib.request.Request(
logo_url,
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
)
with urllib.request.urlopen(req) as response:
with open(logo_path, 'wb') as out_file:
out_file.write(response.read())
except Exception as e:
# Logo download failed, continue without it
print(f"Debug: Logo download failed: {e}")
if os.path.exists(logo_path) and os.path.getsize(logo_path) > 0:
try:
# Load image and resize to fit header height (70px) while maintaining aspect ratio
img = Image.open(logo_path)
header_height = 70
# Calculate width to maintain aspect ratio
aspect_ratio = img.width / img.height
new_height = header_height - 10 # Leave 5px padding top and bottom
new_width = int(new_height * aspect_ratio)
# Resize image with high-quality resampling
img_resized = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
# Convert to PhotoImage for Tkinter
self.header_photo = ImageTk.PhotoImage(img_resized)
# Create label with image
logo_label = tk.Label(
header,
image=self.header_photo,
bg="#007acc",
borderwidth=0
)
logo_label.pack(side="right", padx=20, pady=5)
except Exception as e:
# If logo fails to load, silently continue without logo
print(f"Debug: Logo display failed: {e}")
def _create_bug_button(self):
"""Create bug report button in top-right."""
container = tk.Frame(self.root, bg="#f0f0f0")
container.pack(fill="x", padx=15, pady=8)
btn = tk.Button(
container,
text="🐛",
font=("Arial", 13),
width=5,
height=1,
bg="#e0e0e0",
activebackground="#d0d0d0",
relief="raised",
command=self._copy_debug_info
)
btn.pack(side="left")
ToolTip(btn, "Copy debug information to clipboard")
def _create_menubar(self):
"""Create application menu bar."""
menubar = tk.Menu(self.root)
# File menu
file_menu = tk.Menu(menubar, tearoff=0)
file_menu.add_command(
label="Save Configuration",
accelerator="Ctrl+S",
command=self.save_configuration
)
file_menu.add_command(
label="Reload Configuration",
accelerator="Ctrl+R",
command=self._load_configuration
)
file_menu.add_separator()
file_menu.add_command(
label="Open File...",
command=self._browse_for_file
)
file_menu.add_separator()
file_menu.add_command(
label="Settings...",
command=self._show_settings_dialog
)
file_menu.add_separator()
file_menu.add_command(
label="Exit",
command=self._on_window_close
)
menubar.add_cascade(label="File", menu=file_menu)
# Help menu
help_menu = tk.Menu(menubar, tearoff=0)
help_menu.add_command(
label="About",
command=self._show_about_dialog
)
help_menu.add_command(
label="Change Log",
command=self._show_changelog
)
help_menu.add_command(
label="Report a Bug",
command=self._show_bug_report_dialog
)
menubar.add_cascade(label="Help", menu=help_menu)
self.root.config(menu=menubar)
def _create_search_bar(self):
"""Create search and filter bar with global search across all tabs."""
search_frame = tk.Frame(self.root, bg="#f0f0f0")
search_frame.pack(fill="x", padx=15, pady=12)
# Icon
icon_label = tk.Label(search_frame, text="🔍", bg="#f0f0f0", font=("Segoe UI", 10))
icon_label.pack(side="left", padx=(0, 10))
# Search input
self.search_var = tk.StringVar()
search_entry = tk.Entry(
search_frame,
textvariable=self.search_var,
font=("Segoe UI", 11),
relief="solid",
borderwidth=1,
bg="white",
fg="#000000"
)
# Add placeholder text
placeholder_text = "Search for specific Properties or keywords in Descriptions"
placeholder_color = "#808080" # 50% grey
def on_focus_in(event):
if self.search_var.get() == placeholder_text:
search_entry.delete(0, tk.END)
search_entry.config(fg="#000000")
search_entry.config(font=("Segoe UI", 10))
def on_focus_out(event):
if self.search_var.get() == "":
search_entry.insert(0, placeholder_text)
search_entry.config(fg=placeholder_color)
search_entry.config(font=("Segoe UI", 10, "italic"))
# Insert placeholder text initially
search_entry.insert(0, placeholder_text)
search_entry.config(fg=placeholder_color)
search_entry.config(font=("Segoe UI", 10, "italic"))
# Bind focus events
search_entry.bind("<FocusIn>", on_focus_in)
search_entry.bind("<FocusOut>", on_focus_out)
search_entry.pack(side="left", fill="x", expand=True, padx=(0, 10))
search_entry.bind("<KeyRelease>", lambda e: self._global_search())
search_entry.bind("<Return>", lambda e: self._go_to_next_result())
# Result counter
counter_label = tk.Label(
search_frame,
textvariable=self.result_counter_var,
bg="#f0f0f0",
fg="#666666",
font=("Segoe UI", 10),
width=10
)
counter_label.pack(side="right", padx=(10, 0))
# Next button
next_btn = tk.Button(
search_frame,
text="Next ▶",
font=("Segoe UI", 10),
bg="#e0e0e0",
activebackground="#d0d0d0",
relief="raised",
width=7,
command=self._go_to_next_result
)
next_btn.pack(side="right", padx=(5, 0))
# Previous button
prev_btn = tk.Button(
search_frame,
text="◀ Prev",
font=("Segoe UI", 10),
bg="#e0e0e0",
activebackground="#d0d0d0",
relief="raised",
width=7,
command=self._go_to_prev_result
)
prev_btn.pack(side="right", padx=(5, 0))
# Clear button
clear_btn = tk.Button(
search_frame,
text="Clear",
font=("Segoe UI", 10),
bg="#e0e0e0",
activebackground="#d0d0d0",
relief="raised",
width=7,
command=self._clear_search
)
clear_btn.pack(side="right", padx=(5, 0))
def _create_notebook(self):
"""Create tabbed notebook with all property tabs."""
self.notebook = ttk.Notebook(self.root)
self.notebook.pack(fill="both", expand=True, padx=15, pady=(0, 12))
self.tab_frames = {}
for tab_name in TAB_DEFINITIONS.keys():
frame = ScrollableFrame(self.notebook)
self.tab_frames[tab_name] = frame
self.notebook.add(frame, text=tab_name)
def _create_action_buttons(self):
"""Create Save, Reload, and Debug buttons."""
button_frame = tk.Frame(self.root, bg="#f0f0f0")
button_frame.pack(fill="x", padx=15, pady=12)
# Left side - Bug report button
left_container = tk.Frame(button_frame, bg="#f0f0f0")
left_container.pack(side="left")
debug_btn = tk.Button(
left_container,
text="🐛",
font=("Arial", 13),
width=5,
height=1,
bg="#e0e0e0",
activebackground="#d0d0d0",
relief="raised",
command=self._copy_debug_info
)
debug_btn.pack(side="left")
ToolTip(debug_btn, "Copy debug information to clipboard")
# Right side - Save and Reload buttons
buttons_container = tk.Frame(button_frame, bg="#f0f0f0")
buttons_container.pack(side="right")
# Reload button
reload_btn = tk.Button(
buttons_container,
text="Reload",
font=("Segoe UI", 10),
bg="#007acc",
fg="white",
activebackground="#005f9e",
activeforeground="white",
relief="raised",
padx=15,
pady=6,
command=self._load_configuration
)
reload_btn.pack(side="right", padx=(10, 0))
# Save button
save_btn = tk.Button(
buttons_container,
text="Save",
font=("Segoe UI", 10),
bg="#007acc",
fg="white",
activebackground="#005f9e",
activeforeground="white",
relief="raised",
padx=15,
pady=6,
command=self.save_configuration
)
save_btn.pack(side="right")
def _create_status_bar(self):
"""Create status bar at bottom."""
self.status_var = tk.StringVar(value="Ready")
status_bar = tk.Label(
self.root,
textvariable=self.status_var,
anchor="w",
bg="#e0e0e0",
fg="#333333",
font=("Segoe UI", 9),
padx=15,
pady=6
)
status_bar.pack(fill="x", side="bottom")
def _create_footer(self):
"""Create footer bar."""
footer = tk.Label(
self.root,
text=f"Version {self.VERSION} © 7 Days to Die Server Config Editor™ by Dance Monkey Dance™",
bg="#dcdcdc",
fg="#666666",
font=("Segoe UI", 8),
padx=15,
pady=4
)
footer.pack(fill="x", side="bottom")
def _load_configuration(self):
"""Load XML configuration file."""
if not os.path.exists(self.config_file):
response = messagebox.askyesno(
"File Not Found",
f"Configuration file not found:\n\n{self.config_file}\n\nBrowse for file?"
)
if response:
self._browse_for_file()
else:
self.status_var.set("Error: Configuration file not found")
return
try:
# Parse XML
self.xml_tree = ET.parse(self.config_file)
self.xml_root = self.xml_tree.getroot()
except ET.ParseError as parse_error:
# Attempt repair
if repair_xml_encoding(self.config_file):
try:
self.xml_tree = ET.parse(self.config_file)
self.xml_root = self.xml_tree.getroot()
self.status_var.set("Loaded (XML was repaired)")
except Exception as e:
messagebox.showerror("XML Error", f"Failed to parse XML after repair:\n{e}")
self.status_var.set("Error: XML parsing failed")
return
else:
messagebox.showerror(