upgrading code to use dejaqt

upgraded dejaqt to use folders
implemented correct folder matching
rearranged pagereply to be a resourcereply (and falling back on it)
This commit is contained in:
Gabor Körber 2014-06-25 17:10:49 +02:00
parent b6cb354446
commit ee289dc39e
7 changed files with 172 additions and 110 deletions

0
archive/__init__.py Normal file
View File

View File

@ -13,7 +13,9 @@ class FolderLibrary(object):
if settings: if settings:
self.folders.update( getattr(settings, 'DEJAQT_DIRS', {}) ) self.folders.update( getattr(settings, 'DEJAQT_DIRS', {}) )
except: except:
logging.error('DEJAQT_DIRS in django settings is corrupt.') logging.error('DEJAQT_DIRS in django settings threw error.')
import traceback
traceback.print_exc()
if folders: if folders:
# no try here: if this fails, you got yourself a programming error. # no try here: if this fails, you got yourself a programming error.
self.folders.update(folders) self.folders.update(folders)
@ -47,24 +49,27 @@ class FolderLibrary(object):
def matched_folder(self, url): def matched_folder(self, url):
m = self.match(url) m = self.match(url)
if m is not None: if m is not None:
real_folder = self._folders[m] folder = self._folders[m]
print m #heading, rest = url[:len(m)], url[len(m):]
print url rest = url[len(m):]
print url[len(m):] real_folder = os.path.abspath( os.path.join(folder, rest) )
print os.path.split(real_folder) if real_folder.startswith(os.path.abspath(folder)):
print os.path.split(url)
return real_folder return real_folder
else:
logging.error('%s does not seem to be a subpath of %s' % (real_folder, folder))
def print_folders(self): def print_folders(self):
print '{' print '{'
for k in self._keys: for k in self._keys:
print "'%s': '%s'" % (k, self._folders[k]) print "'%s': '%s'," % (k, self._folders[k])
print '}' print '}'
if __name__ == "__main__": if __name__ == "__main__":
# test this: # test this:
f = FolderLibrary({'abc/dab/': 'c:/dab', import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'scon.dj.settings'
f = FolderLibrary({'abc/dab/': 'c:/media',
'abc': 'd:/abc', 'abc': 'd:/abc',
'abc/dab/tmp': '/tmp', 'abc/dab/tmp': '/tmp',
'uiuiui': 'x:/', 'uiuiui': 'x:/',
@ -75,5 +80,5 @@ if __name__ == "__main__":
f.add_folder('abc/dub/', 'c:/dubdub') f.add_folder('abc/dub/', 'c:/dubdub')
f.print_folders() f.print_folders()
print f.matched_folder('abc/dab/okokok/hurnkint.pdf') print f.matched_folder('abc/dab/okokok/some.png')

View File

@ -4,6 +4,7 @@
import os, logging import os, logging
from PyQt4 import QtCore, QtGui, QtWebKit, QtNetwork from PyQt4 import QtCore, QtGui, QtWebKit, QtNetwork
from django.test import Client from django.test import Client
from folders import FolderLibrary
class DebugPage(QtWebKit.QWebPage): class DebugPage(QtWebKit.QWebPage):
def sayMyName(self): def sayMyName(self):
@ -11,17 +12,17 @@ class DebugPage(QtWebKit.QWebPage):
class DejaWebView(QtWebKit.QWebView): class DejaWebView(QtWebKit.QWebView):
''' '''
BaseDir. Get rid of it? Optional:
* folders: FolderLibrary() Instance.
* page: Initialized QWebPage instance for initial page (default DebugPage())
''' '''
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
basedir = kwargs.pop('basedir', None) self.folders = kwargs.pop('folders', FolderLibrary())
page = kwargs.pop('page', DebugPage())
QtWebKit.QWebView.__init__(self, *args, **kwargs) QtWebKit.QWebView.__init__(self, *args, **kwargs)
oldManager = self.page().networkAccessManager() #self.oldManager = self.page().networkAccessManager()
self.setPage(DebugPage()) self.setPage(page)
self.page().setNetworkAccessManager(DejaNetworkAccessManager(self, basedir)) self.page().setNetworkAccessManager(DejaNetworkAccessManager(self))
def set_basedir(self, basedir):
self.page().setNetworkAccessManager(DejaNetworkAccessManager(self, basedir))
class DejaNetworkAccessManager(QtNetwork.QNetworkAccessManager): class DejaNetworkAccessManager(QtNetwork.QNetworkAccessManager):
''' '''
@ -39,13 +40,10 @@ class DejaNetworkAccessManager(QtNetwork.QNetworkAccessManager):
Note2: not sure if cookies and sessions will work this way! Note2: not sure if cookies and sessions will work this way!
''' '''
USE_NETWORK = False USE_NETWORK = False
def __init__(self, parent=None, basedir=None): def __init__(self, parent=None):
QtNetwork.QNetworkAccessManager.__init__(self, parent=None) QtNetwork.QNetworkAccessManager.__init__(self, parent=None)
if not basedir: if parent:
# take current dir as basedir. self.folders = getattr(parent, 'folders', FolderLibrary())
self.basedir = os.path.dirname(os.path.abspath(__file__))
else:
self.basedir = basedir
def createRequest(self, operation, request, data): def createRequest(self, operation, request, data):
scheme = request.url().scheme() scheme = request.url().scheme()
@ -61,13 +59,13 @@ class DejaNetworkAccessManager(QtNetwork.QNetworkAccessManager):
#print reply #print reply
return reply return reply
elif operation == self.PostOperation: elif operation == self.PostOperation:
#print data.readAll() print data.readAll()
#print request #print request
reply = PageReply(self, request.url(), self.PostOperation) reply = PageReply(self, request.url(), self.PostOperation)
return reply return reply
elif scheme == 'res': elif scheme == 'res':
if operation == self.GetOperation: if operation == self.GetOperation:
return ImageReply(self, request.url(), self.GetOperation, self.basedir) return ResourceReply(self, request.url(), self.GetOperation)
else: else:
if self.USE_NETWORK: if self.USE_NETWORK:
return QtNetwork.QNetworkAccessManager.createRequest(self, operation, request, data) return QtNetwork.QNetworkAccessManager.createRequest(self, operation, request, data)
@ -113,7 +111,36 @@ class BasePageReply(QtNetwork.QNetworkReply):
self.offset = end self.offset = end
return data return data
class PageReply(BasePageReply): class ResourceReply(BasePageReply):
content_type = 'image/png'
def determine_content_type(self, path):
return self.content_type
def initialize_content(self, url, operation):
# determine folder:
path = unicode(url.path()).lstrip('/')
folders = getattr(self.parent(), 'folders')
if folders:
path = folders.matched_folder(path)
if path:
if os.path.exists(path):
try:
f = open(path, 'rb')
return f.read()
finally:
f.close()
else:
logging.warning('Path does not exist: %s' % path)
else:
logging.error('Containing Folder not found for %s' % path)
else:
logging.error('Configuration Error: No Folders found.')
return ''
class PageReply(ResourceReply):
content_type = 'text/html'
def initialize_content(self, url, operation): def initialize_content(self, url, operation):
c = Client() c = Client()
print "Response for %s, method %s" % (url.path(), operation) print "Response for %s, method %s" % (url.path(), operation)
@ -121,9 +148,12 @@ class PageReply(BasePageReply):
response = c.get(unicode(url.path()), ) response = c.get(unicode(url.path()), )
elif operation == DejaNetworkAccessManager.PostOperation: elif operation == DejaNetworkAccessManager.PostOperation:
response = c.post(unicode(url.path())) response = c.post(unicode(url.path()))
self.content_type = response.get('Content-Type', self.content_type)
# response code # response code
print "Response Status: %s" % response.status_code #print "Response Status: %s" % response.status_code
# note: on a 404, we might need to trigger file response. # note: on a 404, we might need to trigger file response.
if response.status_code == 404:
return ResourceReply.initialize_content(self, url, DejaNetworkAccessManager.GetOperation)
return response.content return response.content
class NoNetworkReply(BasePageReply): class NoNetworkReply(BasePageReply):
@ -137,26 +167,3 @@ class NoNetworkReply(BasePageReply):
</html> </html>
''' '''
class ResourceReply(BasePageReply):
content_type = 'image/png'
def __init__(self, parent, url, operation, basedir):
self.basedir = basedir
BasePageReply.__init__(self, parent, url, operation)
def determine_content_type(self, path):
return self.content_type
def initialize_content(self, url, operation):
path = os.path.join(self.basedir, unicode(url.path()).lstrip('/'))
if not os.path.exists(path):
logging.error('Image does not exist: %s' % path)
return ''
#h = url.host()
# @todo: host checks?
try:
f = open(path, 'rb')
return f.read()
finally:
f.close()

View File

@ -3,6 +3,30 @@
{% block css %} {% block css %}
<style> <style>
<!-- <!--
@media print {
.nobreak { page-break-inside: ''; }
tr { page-break-inside: '';
page-break-after: '';
page-break-before: ''; }
td { page-break-inside: '';
page-break-after: '';
page-break-before: ''; }
ul { page-break-inside: avoid; }
.item { page-break-inside: avoid;
page-break-after: avoid; }
.panel { page-break-inside: avoid;
page-break-after: ''; }
.item-sub { page-break-inside: avoid;
page-break-before: ''; }
.remarks { page-break-inside: avoid; }
.arrowright { page-break-inside: avoid; }
.breakable {
page-break-inside: auto !important;
page-break-before: auto !important;
page-break-after: auto !important;
}
}
.panel { .panel {
background-color: #2d2d2d; background-color: #2d2d2d;
color: #fafafa; color: #fafafa;
@ -87,6 +111,33 @@ content: "";
color: #d76d39; color: #d76d39;
} }
.row {
width: 800px;
}
.col1 {
width: 240px;
}
.col2 {
width: 20px;
}
.col3 {
width: 240px;
}
.col4 {
width: 240px;
}
.col {
display: inline-table;
}
--> -->
</style> </style>
{% endblock css %} {% endblock css %}

View File

@ -3,43 +3,40 @@
{% block context %} {% block context %}
<img src="{{MEDIA_URL}}scon/conflict-logo.png" style="position: absolute; float:left; top: -42px;"> <img src="{{MEDIA_URL}}scon/conflict-logo.png" style="position: absolute; float:left; top: -42px;">
<h1 style="margin-left: 160px;">Crafting Overview</h1> <h1 style="margin-left: 160px;">Crafting Overview</h1>
<table>
<thead>
<tr>
<th>Source</th>
<th style="width: 1em;">&nbsp;</th>
<th>Crafts into</th>
<th>Also used in</th>
</tr>
</thead>
<tbody>
{% for item in items %} {% for item in items %}
{% if item.primary_recipee %} {% if item.primary_recipee %}
<tr> <div class="row">
<td>
<div class="col1 col">
<div class="panel item"> <div class="panel item">
{% if item.icon %}<img src="{{ MEDIA_URL }}scon/icons/{{ item.icon }}.png">{% endif %} {{ item.name }} {% if item.icon %}<img src="{{ MEDIA_URL }}scon/icons/{{ item.icon }}.png">{% endif %} {{ item.name }}
{% if item.sell_price %}<br><i>Sell: {{item.sell_price}} cr</i>{% endif %} {% if item.sell_price %}<br><i>Sell: {{item.sell_price}} cr</i>{% endif %}
</div> </div>
</td> </div>
{% with item.primary_recipee as recipee %} {% with item.primary_recipee as recipee %}
<td> <div class="col2 col">&nbsp;
<div class="arrowright">{% if recipee.amount > 1 %}{{ recipee.amount }}{% endif %}</div> <div class="arrowright nobreak">{% if recipee.amount > 1 %}{{ recipee.amount }}{% endif %}</div>
</td> </div>
<td>
<div class="panel item"> <div class="col3 col">
<div class="nobreak">
<div class="panel item nobreak">
{% if recipee.output.icon %}<img src="{{ MEDIA_URL }}scon/icons/{{ recipee.output.icon }}.png">{% endif %} {{ recipee.output.html }} {% if recipee.output.icon %}<img src="{{ MEDIA_URL }}scon/icons/{{ recipee.output.icon }}.png">{% endif %} {{ recipee.output.html }}
{% if recipee.output.sell_price %}<br><i>Sell: {{recipee.output.sell_price}} cr</i>{% endif %} {% if recipee.output.sell_price %}<br><i>Sell: {{recipee.output.sell_price}} cr</i>{% endif %}
</div> </div>
<div class="panel-light item-sub"> <div class="panel-light item-sub nobreak">
<ul> <ul>
{% for ingredient in recipee.ingredients %} {% for ingredient in recipee.ingredients %}
<li>{{ ingredient.amount }} x {{ ingredient.item.html }}</li> <li>{{ ingredient.amount }} x {{ ingredient.item.html }}</li>
{% endfor %} {% endfor %}
</ul> </ul>
</div> </div>
</td> </div>
<td> </div>
<div class="col4 col">
<ul class="remarks"> <ul class="remarks">
{% for i1 in item.crafting_used_in %} {% for i1 in item.crafting_used_in %}
{% with i1.crafting.output as ci %} {% with i1.crafting.output as ci %}
@ -52,11 +49,10 @@
{% endwith %} {% endwith %}
{% endfor %} {% endfor %}
</ul> </ul>
</td> </div>
{% endwith %} {% endwith %}
</tr> </div>
<span class="breakable">&nbsp;</span>
{% endif %} {% endif %}
{% endfor %} {% endfor %}
</tbody>
</table>
{% endblock context %} {% endblock context %}

View File

@ -11,8 +11,9 @@ os.environ['DJANGO_SETTINGS_MODULE'] = 'scon.dj.settings'
#setup_environ(settings) #setup_environ(settings)
import sys import sys
from PyQt4 import QtCore, QtGui, QtWebKit, QtNetwork from PyQt4 import QtCore, QtGui, QtWebKit, QtNetwork
from scon.dejaqt.folders import FolderLibrary
from scon.dejaqt.qweb import DejaWebView
from treeview import TreeViewModel, Node from treeview import TreeViewModel, Node
from localbrowser import LocalWebView
class MenuTree(QtGui.QTreeView): class MenuTree(QtGui.QTreeView):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -64,7 +65,9 @@ class Browser(QtGui.QMainWindow):
self.gridLayout.addLayout(self.horizontalMainLayout) self.gridLayout.addLayout(self.horizontalMainLayout)
# #
#self.menu = MenuTree() #self.menu = MenuTree()
self.html = LocalWebView(basedir='D:/work/workspace/scon/src/scon/dj/scon/media/') self.html = DejaWebView(folders=FolderLibrary({'':
'D:/work/workspace/scon/src/scon/dj/scon/media/'})
)
#self.horizontalMainLayout.addWidget(self.menu) #self.horizontalMainLayout.addWidget(self.menu)
self.horizontalMainLayout.addWidget(self.html) self.horizontalMainLayout.addWidget(self.html)
self.mainLayout.addWidget(self.frame) self.mainLayout.addWidget(self.frame)