]> git.saurik.com Git - wxWidgets.git/blob - wxPython/samples/ide/activegrid/util/cachedloader.py
Added the ActiveGrid IDE as a sample application
[wxWidgets.git] / wxPython / samples / ide / activegrid / util / cachedloader.py
1 #----------------------------------------------------------------------------
2 # Name: cachedloader.py
3 # Purpose:
4 #
5 # Author: Joel Hare
6 #
7 # Created: 8/31/04
8 # CVS-ID: $Id$
9 # Copyright: (c) 2004-2005 ActiveGrid, Inc.
10 # License: wxWindows License
11 #----------------------------------------------------------------------------
12
13 import copy
14 import os.path
15 import string
16 import cStringIO
17
18 import time
19
20 # TODO: Instantiate the database and create a pool
21
22
23 class CachedLoader(object):
24 def __init__(self):
25 self.cache = {}
26 self.baseLoadDir = None
27
28 def fullPath(self, fileName):
29 if os.path.isabs(fileName):
30 absPath = fileName
31 elif self.baseLoadDir:
32 absPath = os.path.join(self.baseLoadDir, fileName)
33 else:
34 absPath = os.path.abspath(fileName)
35 return absPath
36
37 def setPrototype(self, fileName, loadedFile):
38 absPath = self.fullPath(fileName)
39 mtime = time.time() + 31536000.0 # Make sure prototypes aren't replaced by files on disk
40 self.cache[absPath] = (mtime, loadedFile)
41
42 def update(self, loader):
43 self.cache.update(loader.cache)
44
45 def clear(self):
46 self.cache.clear()
47
48 def delete(self, fileName):
49 absPath = self.fullPath(fileName)
50 del self.cache[absPath]
51
52 def needsLoad(self, fileName):
53 absPath = self.fullPath(fileName)
54 try:
55 cached = self.cache[absPath]
56 cachedTime = cached[0]
57 if cachedTime >= os.path.getmtime(absPath):
58 return False
59 except KeyError:
60 pass
61 return True
62
63 def load(self, fileName, loader):
64 absPath = self.fullPath(fileName)
65 loadedFile = None
66 try:
67 cached = self.cache[absPath]
68 except KeyError:
69 cached = None
70
71 if cached:
72 cachedTime = cached[0]
73 # ToDO We might need smarter logic for checking if a file needs to be reloaded
74 # ToDo We need a way to disable checking if this is a production server
75 if cachedTime >= os.path.getmtime(absPath):
76 loadedFile = cached[1]
77
78 if not loadedFile:
79 targetFile = file(absPath)
80 try:
81 mtime = os.path.getmtime(absPath)
82 loadedFile = loader(targetFile)
83 self.cache[absPath] = (mtime, loadedFile)
84 finally:
85 targetFile.close()
86 return loadedFile
87