0

Fixed some crashes in assetManager

Copy in the rest of the web assets
This commit is contained in:
Andrew Chin
2012-01-07 23:56:08 -05:00
parent 0537733bca
commit 4255b26fc7
5 changed files with 48 additions and 300 deletions

View File

@@ -16,8 +16,13 @@
import json import json
import os import os
import codecs import codecs
import locale
import time
from PIL import Image from PIL import Image
import util
import overviewer_version
class AssetManager(object): class AssetManager(object):
"""\ """\
These objects provide an interface to metadata and persistent data, and at the These objects provide an interface to metadata and persistent data, and at the
@@ -115,11 +120,12 @@ directory.
global_assets = os.path.join(util.get_program_path(), "overviewer_core", "data", "web_assets") global_assets = os.path.join(util.get_program_path(), "overviewer_core", "data", "web_assets")
if not os.path.isdir(global_assets): if not os.path.isdir(global_assets):
global_assets = os.path.join(util.get_program_path(), "web_assets") global_assets = os.path.join(util.get_program_path(), "web_assets")
mirror_dir(global_assets, self.destdir) util.mirror_dir(global_assets, self.outputdir)
# do the same with the local copy, if we have it # do the same with the local copy, if we have it
if self.web_assets_path: # TODO
mirror_dir(self.web_assets_path, self.destdir) # if self.web_assets_path:
# util.mirror_dir(self.web_assets_path, self.outputdir)
@@ -130,88 +136,17 @@ directory.
return info['label'] return info['label']
return rendermode.capitalize() return rendermode.capitalize()
# create generated map type data, from given quadtrees
maptypedata = map(lambda q: {'label' : get_render_mode_label(q.rendermode),
'shortname' : q.rendermode,
'path' : q.tiledir,
'bg_color': self.bg_color,
'overlay' : 'overlay' in get_render_mode_inheritance(q.rendermode),
'imgformat' : q.imgformat},
self.quadtrees)
config = config.replace("{maptypedata}", json.dumps(maptypedata))
with codecs.open(os.path.join(self.destdir, "overviewerConfig.js"), 'w', encoding='UTF-8') as output:
output.write(config)
# Add time and version in index.html # Add time and version in index.html
indexpath = os.path.join(self.destdir, "index.html") indexpath = os.path.join(self.outputdir, "index.html")
index = codecs.open(indexpath, 'r', encoding='UTF-8').read() index = codecs.open(indexpath, 'r', encoding='UTF-8').read()
index = index.replace("{title}", "%s Map - Minecraft Overviewer" % self.world.name) index = index.replace("{title}", "Minecraft Overviewer")
index = index.replace("{time}", strftime("%a, %d %b %Y %H:%M:%S %Z", localtime()).decode(locale.getpreferredencoding())) index = index.replace("{time}", time.strftime("%a, %d %b %Y %H:%M:%S %Z", time.localtime()).decode(locale.getpreferredencoding()))
versionstr = "%s (%s)" % (overviewer_version.VERSION, overviewer_version.HASH[:7]) versionstr = "%s (%s)" % (overviewer_version.VERSION, overviewer_version.HASH[:7])
index = index.replace("{version}", versionstr) index = index.replace("{version}", versionstr)
with codecs.open(os.path.join(self.destdir, "index.html"), 'w', encoding='UTF-8') as output: with codecs.open(os.path.join(self.outputdir, "index.html"), 'w', encoding='UTF-8') as output:
output.write(index) output.write(index)
# the following bit of code came from world.py
# if it exists, open overviewer.dat, and read in the data structure
# info self.persistentData. This dictionary can hold any information
# that may be needed between runs.
# Currently only holds into about POIs (more more details, see quadtree)
self.pickleFile = os.path.join(self.outputdir, "overviewer.dat")
### TODO: Deal with old picklefiles that still live in the world directory
if os.path.exists(self.pickleFile):
self.persistentDataIsNew = False
with open(self.pickleFile,"rb") as p:
self.persistentData = cPickle.load(p)
if not self.persistentData.get('north_direction', False):
# this is a pre-configurable-north map, so add the north_direction key
self.persistentData['north_direction'] = 'lower-left'
else:
# some defaults, presumably a new map
self.persistentData = dict(POI=[], north_direction='lower-left')
self.persistentDataIsNew = True # indicates that the values in persistentData are new defaults, and it's OK to override them
# the following bit of code came from googlemap.py
# since we will only discover PointsOfInterest in chunks that need to be
# [re]rendered, POIs like signs in unchanged chunks will not be listed
# in self.world.POI. To make sure we don't remove these from markers.js
# we need to merge self.world.POI with the persistant data in world.PersistentData
self.world.POI += filter(lambda x: x['type'] != 'spawn', self.world.persistentData['POI'])
if self.nosigns:
markers = filter(lambda x: x['type'] != 'sign', self.world.POI)
else:
markers = self.world.POI
# save persistent data
self.world.persistentData['POI'] = self.world.POI
self.world.persistentData['north_direction'] = self.world.north_direction
with open(self.world.pickleFile,"wb") as f:
cPickle.dump(self.world.persistentData,f)
### TODO find a better mechanism than --skipjs
if self.skipjs:
if self.web_assets_hook:
self.web_assets_hook(self)
# write out the default marker table
with codecs.open(os.path.join(self.outputdir, "markers.js"), 'w', encoding='UTF-8') as output:
output.write("// This is a generated file. Please do not edit it!\n")
output.write("overviewer.collections.markerDatas.push(\n")
output.write("// --start marker json dump--\n")
json.dump(markers, output, indent=1)
output.write("\n// --end marker json dump--\n")
output.write(");\n")

View File

@@ -15,8 +15,6 @@
<script type="text/javascript" src="overviewerConfig.js"></script> <script type="text/javascript" src="overviewerConfig.js"></script>
<script type="text/javascript" src="overviewer.js"></script> <script type="text/javascript" src="overviewer.js"></script>
<script type="text/javascript" src="markers.js"></script>
<script type="text/javascript" src="regions.js"></script>
</head> </head>

View File

@@ -1,188 +0,0 @@
var overviewerConfig = {
/**
* These are things that will probably not need to be changed, but are there
* because otherwise changing them is a giant PITA. If you, the user, sees
* that its crucial for you to change these settings then the document
* repository might be able to assist you.
* http://docs.overviewer.org/en/latest/options/#customizing-web-assets
*/
'CONST': {
/**
* Height and width of the tiles in pixels.
*/
'tileSize': 384,
/**
* Various images used for markers and stuff.
*/
'image': {
'defaultMarker': 'signpost.png',
'signMarker': 'signpost_icon.png',
'compass': 'compass_{north_direction}.png',
'spawnMarker': 'http://google-maps-icons.googlecode.com/files/home.png',
'queryMarker': 'http://google-maps-icons.googlecode.com/files/regroup.png'
},
'mapDivId': 'mcmap',
'regionStrokeWeight': 2
},
/**
* General map settings.
*/
'map': {
/**
* Control the visibility of various controls.
*/
'controls': {
/**
* Pan control is the hand with the arrows around it in the upper left.
*/
'pan': true,
/**
* Zoom control is the zoom slider bar in the upper left.
*/
'zoom': true,
/**
* Spawn control is the "Spawn" button that centers the map on spawn.
*/
'spawn': true,
/**
* The compass in the upper right.
*/
'compass': true,
/**
* The mapType control is the slider for selecting different map types.
*/
'mapType': true,
/**
* The coordsBox control is the box showing the XYZ coordinates
* under the cursor.
*/
'coordsBox': true,
/**
* The overlays control is the drop-down box for selecting overlays.
*/
'overlays': true,
/**
* The searchBox control is the search box for markers.
*/
'searchBox': true
},
/**
* The zoom level when the page is loaded without a specific zoom setting
*/
'defaultZoom': 0,
/**
* This controls how far you can zoom out.
*/
'minZoom': {minzoom},
/**
* This controls how close you can zoom in.
*/
'maxZoom': {maxzoom},
/**
* This tells us how many total zoom levels Overviewer rendered.
* DO NOT change this, even if you change minZoom and maxZoom, because
* it's used for marker position calculations and map resizing.
*/
'zoomLevels': {zoomlevels},
/**
* Center on this point, in world coordinates. Should be an array, ex:
* [0,0,0]
*/
'center': {spawn_coords},
/**
* Set this to tell browsers how long they should cache tiles in minutes.
* Essentially if set to 0, the url for tiles will end in .png
* if not set to 0 it will amend a number derived from the current time
* to the end of the url, like .png?c=123456. This is a great method for
* preventing browsers from caching the images. 0 saves bandwidth, not 0
* prevents caching.
*/
'cacheMinutes': 0,
/**
* Set to true to turn on debug mode, which adds a grid to the map along
* with co-ordinates and a bunch of console output.
*/
'debug': false,
/**
* Set which way north points.
*/
'north_direction': '{north_direction}'
},
/**
* Group definitions for objects that are partially selectable (signs and
* regions).
*/
'objectGroups': {
/* signs -- A list of signpost groups. A signpost can fall into zero,
* one, or more than one group. See below for some examples.
*
* Required:
* label : string. Displayed in the drop down menu control.
* match : function. Applied to each marker (from markers.js). It
* is returns true if the marker should be part
* of the group.
*
* Optional:
* checked : boolean. Set to true to have the group visible by default
* icon : string. Used to specify an icon url.
*/
'signs': [
//{label: "'To'", checked: false, match: function(s) {return s.msg.match(/to/)}},
//{label: "Storage", match: function(s) {return s.msg.match(/storage/i) || s.msg.match(/dirt/i) || s.msg.match(/sand/)}},
//{label: "Below Sealevel", match: function(s) { return s.y<64;}},
//{label: "Info", match: function(s) { return s.msg.match("\\[info\\]");}, icon:"http://google-maps-icons.googlecode.com/files/info.png"},
{'label':'All', 'match':function(sign){return true;}}
],
/* regions -- A list of region groups. A region can fall into zero,
* one, or more than one group. See below for some examples.
* Regions have been designed to work with the WorldGuard Overviewer
* Region importer at @link http://goo.gl/dc0tV but your
* host must support php in order to run WG2OvR. You can also continue
* to use any other region format.
*
* Required:
* label : string. Displayed in the drop down menu control.
* clickable : boolean. Will determine if we should generate an
* experimental info window that shows details
* about the clicked region.
* NOTE: if a region (as defined in region.js)
* does not have a label, this will default to
* false.
* match : function. Applied to each region (from region.js). It
* returns true if the region should be part of
* the group.
*
* Optional:
* checked : boolean. Set to true to have the group visible by default
*/
'regions': [
//{'label':'All','clickable':true,'match':function(region){return true;}}
]
},
/* mapTypes -- a list of alternate map renderings available. At least one
* rendering must be listed. When more than one are provided, controls to
* switch between them are provided, with the first one being the default.
*
* Required:
* label : string. Displayed on the control.
* path : string. Location of the rendered tiles.
* Optional:
* base : string. Base of the url path for tile locations, useful
* for serving tiles from a different server than
* the js/html server.
* imgformat : string. File extension used for these tiles. Defaults to png.
* overlay : bool. If true, this tile set will be treated like an overlay
* bg_color : string. A #RRGGBB format background color.
* shortname : string. Used in the dynamic anchor link mechanism. If not
* present, label is used instead.
*
* Example:
* 'mapTypes': [
* {'label': 'Day', 'path': 'lighting/tiles'},
* {'label': 'Night', 'path': 'night/tiles', 'imgformat': 'jpg'},
* {'label': 'Spawn', 'path': 'spawn/tiles', 'base': 'http://example.cdn.amazon.com/'},
* {'label': 'Overlay', 'path': 'overlay/tiles', 'overlay': true}
* ]
*/
'mapTypes': {maptypedata}
};

View File

@@ -34,38 +34,6 @@ interface out of a set of tiles.
""" """
def mirror_dir(src, dst, entities=None):
'''copies all of the entities from src to dst'''
if not os.path.exists(dst):
os.mkdir(dst)
if entities and type(entities) != list: raise Exception("Expected a list, got a %r instead" % type(entities))
# files which are problematic and should not be copied
# usually, generated by the OS
skip_files = ['Thumbs.db', '.DS_Store']
for entry in os.listdir(src):
if entry in skip_files:
continue
if entities and entry not in entities:
continue
if os.path.isdir(os.path.join(src,entry)):
mirror_dir(os.path.join(src, entry), os.path.join(dst, entry))
elif os.path.isfile(os.path.join(src,entry)):
try:
shutil.copy(os.path.join(src, entry), os.path.join(dst, entry))
except IOError as outer:
try:
# maybe permission problems?
src_stat = os.stat(os.path.join(src, entry))
os.chmod(os.path.join(src, entry), src_stat.st_mode | stat.S_IRUSR)
dst_stat = os.stat(os.path.join(dst, entry))
os.chmod(os.path.join(dst, entry), dst_stat.st_mode | stat.S_IWUSR)
except OSError: # we don't care if this fails
pass
shutil.copy(os.path.join(src, entry), os.path.join(dst, entry))
# if this stills throws an error, let it propagate up
class MapGen(object): class MapGen(object):
def __init__(self, quadtrees, configInfo): def __init__(self, quadtrees, configInfo):

View File

@@ -27,6 +27,7 @@ from cStringIO import StringIO
import ctypes import ctypes
import platform import platform
from itertools import cycle, islice, product from itertools import cycle, islice, product
import shutil
def get_program_path(): def get_program_path():
if hasattr(sys, "frozen") or imp.is_frozen("__main__"): if hasattr(sys, "frozen") or imp.is_frozen("__main__"):
@@ -358,3 +359,37 @@ class ANSIColorFormatter(HighlightingFormatter):
else: else:
# No coloring if it's not to be highlighted or colored # No coloring if it's not to be highlighted or colored
return logging.Formatter.format(self, record) return logging.Formatter.format(self, record)
def mirror_dir(src, dst, entities=None):
'''copies all of the entities from src to dst'''
if not os.path.exists(dst):
os.mkdir(dst)
if entities and type(entities) != list: raise Exception("Expected a list, got a %r instead" % type(entities))
# files which are problematic and should not be copied
# usually, generated by the OS
skip_files = ['Thumbs.db', '.DS_Store']
for entry in os.listdir(src):
if entry in skip_files:
continue
if entities and entry not in entities:
continue
if os.path.isdir(os.path.join(src,entry)):
mirror_dir(os.path.join(src, entry), os.path.join(dst, entry))
elif os.path.isfile(os.path.join(src,entry)):
try:
shutil.copy(os.path.join(src, entry), os.path.join(dst, entry))
except IOError as outer:
try:
# maybe permission problems?
src_stat = os.stat(os.path.join(src, entry))
os.chmod(os.path.join(src, entry), src_stat.st_mode | stat.S_IRUSR)
dst_stat = os.stat(os.path.join(dst, entry))
os.chmod(os.path.join(dst, entry), dst_stat.st_mode | stat.S_IWUSR)
except OSError: # we don't care if this fails
pass
shutil.copy(os.path.join(src, entry), os.path.join(dst, entry))
# if this stills throws an error, let it propagate up