index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
14,201
|
fumpen/marbar
|
refs/heads/master
|
/marbar/score_board/views.py
|
from django.urls import reverse
from django.shortcuts import render, redirect, HttpResponse
from .models import ScoreUnit
from management.models import MarBar
from django.http import JsonResponse
import json
from django.contrib import messages
def help_order(d):
xs = []
for x in d:
xs.append(x)
return xs
def help_order_v2(d):
xs = []
for x in d:
xs.append({'title': x.title, 'points': x.points})
return xs
def score_board(request):
try:
active_marbar = MarBar.objects.get(is_active=True)
all_data = ScoreUnit.objects.filter(marbar__pk=active_marbar.pk).order_by('title')
return render(request, 'score_board.html',
{'collum_0': help_order(all_data.filter(placement=0)),
'collum_1': help_order(all_data.filter(placement=1)),
'collum_2': help_order(all_data.filter(placement=2)),
'collum_3': help_order(all_data.filter(placement=3)),
'collum_4': help_order(all_data.filter(placement=4)),
'countdown_date': active_marbar.end_date})
except:
return render(request, 'score_board.html', {})
def get_points(request):
active_marbar = MarBar.objects.get(is_active=True)
all_data = ScoreUnit.objects.filter(marbar__pk=active_marbar.pk).order_by('title')
return JsonResponse(help_order_v2(all_data), safe=False)
def get_graph(request):
active_marbar = MarBar.objects.get(is_active=True)
D = ScoreUnit.objects.filter(marbar__pk=active_marbar.pk).order_by('title')
points = []
labels = []
for d in D:
points.append(d.points)
labels.append(d.title)
fin = [a for a in zip(labels, points)]
#return JsonResponse({'points': json.dumps(points), 'graph_labels': json.dumps(labels)}, safe=False)
return JsonResponse({'points': json.dumps(fin)}, safe=False)
def assign_points(request):
active_bar = MarBar.objects.filter(is_active=True)
if active_bar.exists():
active_bar = MarBar.objects.get(is_active=True)
if request.user.is_authenticated and (request.user in active_bar.users.all() or request.user.is_superuser):
if request.method == 'GET':
all_data = ScoreUnit.objects.filter(marbar__pk=active_bar.pk).order_by('title')
return render(request, 'assign_points.html',
{'collum_0': all_data.filter(placement=0),
'collum_1': all_data.filter(placement=1),
'collum_2': all_data.filter(placement=2),
'collum_3': all_data.filter(placement=3),
'collum_4': all_data.filter(placement=4)})
elif request.method == 'POST':
try:
su = ScoreUnit.objects.get(pk=int(request.POST.get('scoreUnitPk')))
new_val = request.POST.get('scoreUnitValue')
if new_val:
if new_val[0] == '-':
front_opr = -1
new_val = new_val[1:]
elif new_val[0] == '+':
front_opr = 1
new_val = new_val[1:]
else:
front_opr = 1
if str.isdigit(new_val):
new_score = su.points + (front_opr * int(new_val))
if new_score < 0:
new_score = 0
su.points = new_score
su.save()
else:
messages.add_message(request, messages.ERROR,
'The points field was not correctly filled and the points was not added')
return redirect(reverse('score_board:assign_points'))
else:
messages.add_message(request, messages.ERROR,
'The points field was not correctly filled and the points was not added')
return redirect(reverse('score_board:assign_points'))
return redirect(reverse('score_board:assign_points'))
except:
messages.add_message(request, messages.ERROR, 'An error occurred and the points was not added')
return redirect(reverse('score_board:assign_points'))
else:
return redirect(reverse('score_board'))
else:
messages.add_message(request, messages.ERROR,
'You must be logged in and connected to the Active MarBar to access this')
return redirect(reverse('score_board'))
else:
messages.add_message(request, messages.ERROR, 'There is no active MarBar at this time')
return redirect(reverse('score_board'))
|
{"/marbar/score_board/views.py": ["/marbar/score_board/models.py"], "/marbar/management/admin.py": ["/marbar/management/models.py"], "/marbar/management/views.py": ["/marbar/management/models.py", "/marbar/management/forms.py"]}
|
14,202
|
fumpen/marbar
|
refs/heads/master
|
/marbar/marbar/urls.py
|
"""marbar URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from score_board.views import score_board
# from django.contrib.auth import views as auth_views #https://simpleisbetterthancomplex.com/tutorial/2016/06/27/how-to-use-djangos-built-in-login-system.html
urlpatterns = [
path('', score_board, name='score_board'),
path(r'admin/', admin.site.urls),
path(r'management/', include(('management.urls', 'management'), namespace='management')),
path(r'score_board/', include(('score_board.urls', 'score_board'), namespace='score_board')),
]
|
{"/marbar/score_board/views.py": ["/marbar/score_board/models.py"], "/marbar/management/admin.py": ["/marbar/management/models.py"], "/marbar/management/views.py": ["/marbar/management/models.py", "/marbar/management/forms.py"]}
|
14,203
|
fumpen/marbar
|
refs/heads/master
|
/marbar/management/migrations/0001_initial.py
|
# Generated by Django 2.1.1 on 2018-10-26 15:02
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(default='', max_length=200)),
('info', models.TextField(default='', max_length=200)),
('start_date', models.DateTimeField(auto_now_add=True)),
('end_date', models.DateTimeField(auto_now_add=True)),
],
),
migrations.CreateModel(
name='MarBar',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(default='', max_length=200)),
('banner', models.ImageField(blank=True, upload_to='banners/', verbose_name='banner')),
('end_date', models.DateTimeField()),
('is_active', models.BooleanField(default=False)),
('user', models.ManyToManyField(to=settings.AUTH_USER_MODEL)),
],
),
]
|
{"/marbar/score_board/views.py": ["/marbar/score_board/models.py"], "/marbar/management/admin.py": ["/marbar/management/models.py"], "/marbar/management/views.py": ["/marbar/management/models.py", "/marbar/management/forms.py"]}
|
14,204
|
fumpen/marbar
|
refs/heads/master
|
/marbar/management/migrations/0003_auto_20190215_1354.py
|
# Generated by Django 2.1.5 on 2019-02-15 13:54
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('management', '0002_auto_20190131_1745'),
]
operations = [
migrations.AddField(
model_name='event',
name='marbar',
field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='management.MarBar'),
),
migrations.AlterField(
model_name='event',
name='end_date',
field=models.DateTimeField(),
),
migrations.AlterField(
model_name='event',
name='start_date',
field=models.DateTimeField(),
),
]
|
{"/marbar/score_board/views.py": ["/marbar/score_board/models.py"], "/marbar/management/admin.py": ["/marbar/management/models.py"], "/marbar/management/views.py": ["/marbar/management/models.py", "/marbar/management/forms.py"]}
|
14,205
|
fumpen/marbar
|
refs/heads/master
|
/marbar/management/admin.py
|
from django.contrib import admin
from .models import MarBar
admin.site.register(MarBar)
|
{"/marbar/score_board/views.py": ["/marbar/score_board/models.py"], "/marbar/management/admin.py": ["/marbar/management/models.py"], "/marbar/management/views.py": ["/marbar/management/models.py", "/marbar/management/forms.py"]}
|
14,206
|
fumpen/marbar
|
refs/heads/master
|
/marbar/score_board/urls.py
|
from django.urls import path
from . import views
urlpatterns = [
path('get_points', views.get_points, name='get_points'),
path('get_graph', views.get_graph, name='get_graph'),
path('assign_points/', views.assign_points, name='assign_points'),
]
|
{"/marbar/score_board/views.py": ["/marbar/score_board/models.py"], "/marbar/management/admin.py": ["/marbar/management/models.py"], "/marbar/management/views.py": ["/marbar/management/models.py", "/marbar/management/forms.py"]}
|
14,207
|
fumpen/marbar
|
refs/heads/master
|
/marbar/score_board/models.py
|
from django.db import models
class ScoreUnit(models.Model):
title = models.CharField(max_length=200, default="")
points = models.IntegerField(default=0)
placement = models.IntegerField(default=0)
marbar = models.ForeignKey('management.MarBar', on_delete=models.CASCADE)
def __str__(self):
return self.title
|
{"/marbar/score_board/views.py": ["/marbar/score_board/models.py"], "/marbar/management/admin.py": ["/marbar/management/models.py"], "/marbar/management/views.py": ["/marbar/management/models.py", "/marbar/management/forms.py"]}
|
14,208
|
fumpen/marbar
|
refs/heads/master
|
/marbar/management/models.py
|
from django.db import models
from django.contrib.auth.models import User
class MarBar(models.Model):
title = models.CharField(max_length=200, default="", unique=True)
banner = models.ImageField(upload_to='banners/',
verbose_name='banner', blank=True)
users = models.ManyToManyField(User)
end_date = models.DateTimeField(blank=False)
is_active = models.BooleanField(default=False, blank=False)
def __str__(self):
return self.title
class Event(models.Model):
marbar = models.ForeignKey(MarBar, on_delete=models.CASCADE, default=None)
title = models.CharField(max_length=200, default="")
info = models.TextField(max_length=200, default="")
start_date = models.DateTimeField(blank=False)
end_date = models.DateTimeField(blank=False)
def __str__(self):
return self.title
|
{"/marbar/score_board/views.py": ["/marbar/score_board/models.py"], "/marbar/management/admin.py": ["/marbar/management/models.py"], "/marbar/management/views.py": ["/marbar/management/models.py", "/marbar/management/forms.py"]}
|
14,209
|
fumpen/marbar
|
refs/heads/master
|
/marbar/management/migrations/0002_auto_20190131_1745.py
|
# Generated by Django 2.1.5 on 2019-01-31 17:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('management', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='marbar',
old_name='user',
new_name='users',
),
migrations.AlterField(
model_name='marbar',
name='title',
field=models.CharField(default='', max_length=200, unique=True),
),
]
|
{"/marbar/score_board/views.py": ["/marbar/score_board/models.py"], "/marbar/management/admin.py": ["/marbar/management/models.py"], "/marbar/management/views.py": ["/marbar/management/models.py", "/marbar/management/forms.py"]}
|
14,210
|
fumpen/marbar
|
refs/heads/master
|
/marbar/management/views.py
|
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .models import MarBar, Event
from .forms import MarBarForm, EventForm
from score_board.models import ScoreUnit
from django.contrib import messages
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
def general_management(request):
if not request.user.is_authenticated:
messages.add_message(request, messages.INFO, 'plz log in to access this site')
return redirect(reverse('management:login_view'))
else:
response_context = {}
if request.user.is_superuser:
response_context['superuser'] = True
response_context['createUser'] = UserCreationForm
marbar_form = MarBarForm()
response_context['createMarBar'] = marbar_form
marbars = MarBar.objects.all()
else:
response_context['superuser'] = False
marbars = MarBar.objects.filter(users__in=[request.user])
t = [{'title': m.title, 'pk': m.pk,
'form': MarBarForm({'title': m.title, 'users': m.users, 'end_date': m.end_date, 'intended_pk': m.pk})}
for m in marbars]
response_context['manageMarbars'] = t
return render(request, 'manage_marbar.html', response_context)
def crude_login_view(request):
return render(request, "login.html")
def crude_login(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect(reverse('management:management_view'))
else:
messages.add_message(request, messages.ERROR, 'Either username or password were incorrect')
return redirect(reverse('management:login_view'))
def logout_user(request):
logout(request)
return redirect(reverse('score_board'))
def create_marbar(request):
if not request.user.is_authenticated & request.user.is_superuser:
messages.add_message(request, messages.INFO, 'plz log in to access this site')
return redirect(reverse('management:login_view'))
if request.method == 'POST':
form = MarBarForm(request.POST, request.FILES)
if form.is_valid():
form.save(new_instance=True)
messages.add_message(request, messages.INFO, 'MarBar was successfully created')
return redirect(reverse('management:management_view'))
else:
messages.add_message(request, messages.WARNING, "Please recheck that the form is filled as intended")
return redirect(reverse('management:management_view'))
else:
messages.add_message(request, messages.ERROR,
"You have beers to drink and records to break, Stop playing around")
return redirect(reverse('management:management_view'))
def create_user(request):
if not request.user.is_authenticated & request.user.is_superuser:
messages.add_message(request, messages.INFO, 'plz log in to access this site')
return redirect(reverse('management:login_view'))
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
messages.add_message(request, messages.INFO, 'User was successfully created')
return redirect(reverse('management:management_view'))
else:
messages.add_message(request, messages.WARNING, "The user input did not fulfill with the requirements")
return redirect(reverse('management:management_view'))
else:
messages.add_message(request, messages.ERROR,
"You have beers to drink and records to break, Stop playing around")
return redirect(reverse('management:management_view'))
def update_marbar(request):
if not request.user.is_authenticated:
messages.add_message(request, messages.INFO, 'plz log in to access this site')
return redirect(reverse('management:login_view'))
if request.method == 'POST':
form = MarBarForm(request.POST, request.FILES)
if form.is_valid():
form.save(new_instance=False, update_instance=True)
messages.add_message(request, messages.INFO, 'MarBar was successfully updated')
return redirect(reverse('management:management_view'))
else:
messages.add_message(request, messages.WARNING, "Please recheck that the form is filled as intended")
return redirect(reverse('management:management_view'))
else:
messages.add_message(request, messages.ERROR,
"You have beers to drink and records to break, Stop playing around")
return redirect(reverse('management:management_view'))
def activate_marbar(request):
if not request.user.is_authenticated & request.user.is_superuser:
messages.add_message(request, messages.INFO, 'plz log in to access this site')
return redirect(reverse('management:login_view'))
if request.method == 'POST':
if 'activateMarBar' in request.POST:
activation_pk = int(request.POST.get('activateMarBar'))
try:
m = MarBar.objects.get(pk=activation_pk)
if not m.is_active:
with transaction.atomic():
if MarBar.objects.filter(is_active=True).exists():
old_active = MarBar.objects.get(is_active=True)
old_active.is_active = False
old_active.save()
m.is_active = True
m.save()
messages.add_message(request, messages.INFO, '{} is now the active MarBar'.format(m.title))
else:
messages.add_message(request, messages.INFO, 'This MarBar is already active')
except ObjectDoesNotExist:
messages.add_message(request, messages.WARNING, 'An error occurred, please try again')
return redirect(reverse('management:management_view'))
else:
messages.add_message(request, messages.WARNING, "Refresh the page or contact someone that has coded this")
return redirect(reverse('management:management_view'))
else:
messages.add_message(request, messages.ERROR,
"You have beers to drink and records to break, Stop playing around")
return redirect(reverse('management:management_view'))
def events_view(request):
active_bar = MarBar.objects.filter(is_active=True)
if active_bar.exists() and active_bar.count() == 1:
active_bar = MarBar.objects.get(is_active=True)
if request.method == 'GET':
response_context = {}
events = Event.objects.filter(marbar=active_bar).order_by('start_date')
if events.exists():
response_context = {'current_events': [e for e in events]}
if request.user.is_authenticated and (request.user in active_bar.users.all() or request.user.is_superuser):
response_context['event_form'] = EventForm()
return render(request, 'events.html', response_context)
elif request.method == 'POST':
if request.user.is_authenticated and (request.user in active_bar.users.all() or request.user.is_superuser):
new_event = EventForm(request.POST)
if new_event.is_valid():
new_event.save(active_marbar=active_bar)
messages.add_message(request, messages.INFO, 'Event was successfully created')
return redirect(reverse('management:events'))
else:
messages.add_message(request, messages.WARNING, 'Please recheck the information filled in the from')
return redirect(reverse('management:events'))
else:
messages.add_message(request, messages.WARNING, 'Please log in again to access this functionality')
return redirect(reverse('management:login'))
else:
return redirect(reverse('score_board'))
else:
messages.add_message(request, messages.ERROR, 'There is currently no active MarBar')
return redirect(reverse('score_board'))
def delete_event(request):
active_bar = MarBar.objects.filter(is_active=True)
if active_bar.exists() and active_bar.count() == 1:
active_bar = MarBar.objects.get(is_active=True)
if request.user.is_authenticated and (request.user in active_bar.users.all() or request.user.is_superuser):
if request.method == 'POST':
try:
e = Event.objects.get(pk=int(request.POST.get('event_pk')), marbar=active_bar)
e.delete()
messages.add_message(request, messages.INFO, 'The event was deleted')
return redirect(reverse('management:events'))
except:
messages.add_message(request, messages.ERROR, 'Refresh the page and try again')
return redirect(reverse('management:events'))
else:
messages.add_message(request, messages.ERROR, 'Stop fooling around!')
return redirect(reverse('management:events'))
else:
messages.add_message(request, messages.INFO, 'plz log in to access this functionality')
return redirect(reverse('management:login_view'))
messages.add_message(request, messages.ERROR, 'There is currently no active MarBar')
return redirect(reverse('score_board'))
|
{"/marbar/score_board/views.py": ["/marbar/score_board/models.py"], "/marbar/management/admin.py": ["/marbar/management/models.py"], "/marbar/management/views.py": ["/marbar/management/models.py", "/marbar/management/forms.py"]}
|
14,245
|
hujun-open/litebook
|
refs/heads/master
|
/ltbsearchdiag.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Mon Aug 13 11:10:41 2012
import sys
import wx
from wx.lib.mixins.listctrl import CheckListCtrlMixin
import thread
import wx.lib.newevent
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
import xmlrpclib
import traceback
import cPickle
import base64
import platform
import os
(SearchReportEvent,EVT_SRE)=wx.lib.newevent.NewEvent()
# begin wxGlade: extracode
# end wxGlade
report_rpc_path='/REPORT'
report_port=50202
MYOS = platform.system()
def cur_file_dir():
#获取脚本路径
global MYOS
if MYOS == 'Linux':
path = sys.path[0]
elif MYOS == 'Windows':
return os.path.dirname(os.path.abspath(sys.argv[0]))
else:
if sys.argv[0].find('/') != -1:
path = sys.argv[0]
else:
path = sys.path[0]
if isinstance(path,str):
path=path.decode('utf-8')
#判断为脚本文件还是py2exe编译后的文件,如果是脚本文件,则返回的是脚本的目录,如果是编译后的文件,则返回的是编译后的文件路径
if os.path.isdir(path):
return path
elif os.path.isfile(path):
return os.path.dirname(path)
class XMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
global report_rpc_path
rpc_paths = (report_rpc_path,)
class ReportSVRThread():
global report_port
"""
A XML RPC svr for receiving LTBNET search result
"""
def __init__(self,win):
self.win=win
## self.running=True
self.port = report_port
self.server = SimpleXMLRPCServer(("localhost", self.port),
logRequests=False,
requestHandler=XMLRPCRequestHandler)
self.server.register_introspection_functions()
self.server.register_function(self.report)
thread.start_new_thread(self.run,())
## def stop(self):
## self.running=False
def report(self,search_results):
sr=cPickle.loads(base64.b16decode(search_results))
evt=SearchReportEvent(result=sr)
try:
wx.PostEvent(self.win, evt)
except Exception, inst:
print "LTBSearchDiag: catched except:"
print traceback.format_exc()
print inst
return 'ok'
def run(self):
self.server.serve_forever()
class CheckListCtrl(wx.ListCtrl, CheckListCtrlMixin):
def __init__(self, parent):
wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT)
CheckListCtrlMixin.__init__(self)
self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated)
self.InsertColumn(0, u"文件名",width=150)
self.InsertColumn(1, u"书名",width=150)
self.InsertColumn(2, u"作者")
self.InsertColumn(3, u"URL",width=300)
self.InsertColumn(4, u"大小")
def addResult(self,r):
index = self.InsertStringItem(sys.maxint, r['rdata'])
self.SetStringItem(index, 3, r['rloc'])
try:
self.SetStringItem(index, 1, r['meta_list']['title'])
self.SetStringItem(index, 2, r['meta_list']['creator'])
self.SetStringItem(index, 4, r['meta_list']['size'])
except:
pass
def OnItemActivated(self, evt):
self.ToggleItem(evt.m_itemIndex)
# this is called by the base class when an item is checked/unchecked
def OnCheckItem(self, index, flag):
data = self.GetItemData(index)
def GetAllChecked(self):
"""
Get all checked items
"""
nextid = -1
rlist=[]
while True:
nextid = self.GetNextItem(nextid)
if nextid == -1: break
if self.IsChecked(nextid)==True:
r={'filename':self.GetItem(nextid,0).GetText(),
'novelname':self.GetItem(nextid,1).GetText(),
'author':self.GetItem(nextid,2).GetText(),
'url':self.GetItem(nextid,3).GetText(),
'size':self.GetItem(nextid,4).GetText(),
}
rlist.append(r)
return rlist
class LTBSearchDiag(wx.Frame):
def __init__(self, parent,downloadFunc=None,kadp_url=None):
"""
downloadFunc is a function to add download task
kadp_url is a url of KADP XMLRPC control server
"""
# begin wxGlade: LTBSearchDiag.__init__
wx.Frame.__init__(self, parent,-1)
self.sizer_3_staticbox = wx.StaticBox(self, -1, u"搜索结果")
self.sizer_2_staticbox = wx.StaticBox(self, -1, u"输入")
self.frame_1_statusbar = self.CreateStatusBar(1, 0)
self.label_1 = wx.StaticText(self, -1, u"搜索关键词:")
self.text_ctrl_1 = wx.TextCtrl(self, -1, "",style=wx.TE_PROCESS_ENTER)
self.list_ctrl_1 = CheckListCtrl(self)
self.downloadFunc=downloadFunc
self.ongoing_kw = 0
## index = self.list_ctrl_1.InsertStringItem(sys.maxint,u'小说1')
## self.list_ctrl_1.SetStringItem(index, 3, 'http://10.10.10.10/1.txt')
##
## index = self.list_ctrl_1.InsertStringItem(sys.maxint,u'小说2')
## self.list_ctrl_1.SetStringItem(index, 3, 'http://20.20.20.20/2.txt')
##
## index = self.list_ctrl_1.InsertStringItem(sys.maxint,u'小说3')
## self.list_ctrl_1.SetStringItem(index, 3, 'http://30.30.30.30/3.txt')
self.button_1 = wx.Button(self, -1, u"下载")
self.button_2 = wx.Button(self, -1, u"关闭")
self.button_3 = wx.Button(self, -1, u"搜索")
self.Bind(wx.EVT_BUTTON, self.OnDownload, self.button_1)
self.Bind(wx.EVT_BUTTON, self.OnCancell, self.button_2)
self.Bind(wx.EVT_TEXT_ENTER, self.OnSearch, self.text_ctrl_1)
self.Bind(wx.EVT_BUTTON, self.OnSearch, self.button_3)
self.Bind(EVT_SRE,self.OnReport)
self.Bind(wx.EVT_CLOSE,self.OnClose)
self.__set_properties()
self.__do_layout()
self.rs_thread = ReportSVRThread(self)
if kadp_url != None:
self.kadp_ctrl = xmlrpclib.Server(kadp_url)
# end wxGlade
def __set_properties(self):
# begin wxGlade: LTBSearchDiag.__set_properties
_icon = wx.EmptyIcon()
_icon.CopyFromBitmap(wx.Bitmap(cur_file_dir()+u"/icon/litebook-icon_32x32.png", wx.BITMAP_TYPE_ANY))
self.SetIcon(_icon)
self.SetTitle(u"LTBNET搜索")
self.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
self.frame_1_statusbar.SetStatusWidths([-1])
# statusbar fields
frame_1_statusbar_fields = ["Ready."]
for i in range(len(frame_1_statusbar_fields)):
self.frame_1_statusbar.SetStatusText(frame_1_statusbar_fields[i], i)
# end wxGlade
def __do_layout(self):
# begin wxGlade: LTBSearchDiag.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
sizer_3 = wx.StaticBoxSizer(self.sizer_3_staticbox, wx.HORIZONTAL)
sizer_2 = wx.StaticBoxSizer(self.sizer_2_staticbox, wx.HORIZONTAL)
sizer_2.Add(self.label_1, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
sizer_2.Add(self.text_ctrl_1, 1, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
sizer_2.Add(self.button_3, 0, 0, 0)
sizer_1.Add(sizer_2, 0, wx.EXPAND, 0)
sizer_3.Add(self.list_ctrl_1, 1, wx.EXPAND, 0)
sizer_1.Add(sizer_3, 1, wx.EXPAND, 0)
sizer_4.Add((20, 20), 1, wx.EXPAND, 0)
sizer_4.Add(self.button_1, 0, 0, 0)
sizer_4.Add((20, 20), 1, wx.EXPAND, 0)
sizer_4.Add(self.button_2, 0, 0, 0)
sizer_4.Add((20, 20), 1, wx.EXPAND, 0)
sizer_1.Add(sizer_4, 0, wx.EXPAND, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
self.SetSize((800,380))
# end wxGlade
def OnSearch(self,evt):
global report_port,report_rpc_path
self.list_ctrl_1.DeleteAllItems() #can NOT use ClearAll here, because it will del all columns too
kw_list = self.text_ctrl_1.GetValue().strip().split()
for kw in kw_list:
if len(kw)<=1:
dlg = wx.MessageDialog(None, u'每个关键词长度都要大于1',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return
if kw_list==[]: return
utfklist=[]
for k in kw_list:
utfklist.append(k.encode('utf-8'))
self.ongoing_kw = len(kw_list)
## print "prepare start searching"
## print kw_list
## try:
self.kadp_ctrl.search(utfklist,'http://127.0.0.1:'+str(report_port)+report_rpc_path)
## except Exception, inst:
## dlg = wx.MessageDialog(None, u'无法连接到KADP协议进程!建议稍后重试或是重启程序。\n'+str(inst),u"错误!",wx.OK|wx.ICON_ERROR)
## dlg.ShowModal()
## dlg.Destroy()
## print traceback.format_exc()
## print inst
## return
self.button_3.Disable()
self.text_ctrl_1.Disable()
self.frame_1_statusbar.SetStatusText(u'搜索中...')
def GetResults(self):
return self.list_ctrl_1.GetAllChecked()
def OnCancell(self,evt):
self.Hide()
def OnDownload(self,evt):
rlist=self.list_ctrl_1.GetAllChecked()
for r in rlist:
self.downloadFunc(r['url'])
self.Hide()
def OnReport(self,evt):
if evt.result=="NoContact":
msg=u"没有Peer,无法搜索。"
self.ongoing_kw=0
else:
for r in evt.result:
self.list_ctrl_1.addResult(r)
msg=u'搜索结束'
self.ongoing_kw -= 1
if self.ongoing_kw <=0:
self.frame_1_statusbar.SetStatusText(msg)
self.button_3.Enable()
self.text_ctrl_1.Enable()
def OnClose(self,evt):
self.Hide()
# end of class LTBSearchDiag
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = LTBSearchDiag(None,None,'http://'+sys.argv[1]+':50201')
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,246
|
hujun-open/litebook
|
refs/heads/master
|
/kpub.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: KPUB
# Purpose: publish all books in the specified dir via KADP
#
# Author: Hu Jun
#
# Created: 17/08/2012
# Copyright: (c) Hu Jun 2012
# Licence: GPLv3
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import os
import sys
import re
import xmlrpclib
import zipfile
import hashlib
import traceback
import time
import struct
import cPickle
import threading
import platform
import logging
import longbin
import base64
myos=platform.architecture()
ros = platform.system()
if myos[1]=='ELF' and ros == 'Linux':
if myos[0]=='64bit':
from lxml_linux_64 import etree
elif myos[0]=='32bit':
from lxml_linux import etree
elif ros == 'Darwin':
from lxml_osx import etree
else:
from lxml import etree
def we_are_frozen():
"""Returns whether we are frozen via py2exe.
This will affect how we find out where we are located."""
return hasattr(sys, "frozen")
def module_path():
""" This will get us the program's directory,
even if we are frozen using py2exe"""
if we_are_frozen():
return os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( )))
return os.path.dirname(unicode(__file__, sys.getfilesystemencoding( )))
if we_are_frozen():
print "I am here", module_path()
sys.path.append(module_path())
import jieba
##if ros == 'Windows':
## from pymmseg_win import mmseg
##elif ros == 'Darwin':
## from pymmseg_osx import mmseg
##elif myos[1]=='ELF' and ros == 'Linux' and myos[0]=='64bit':
## from pymmseg_linux_64 import mmseg
##else:
## from pymmseg import mmseg
import urllib
def cur_file_dir():
#获取脚本路径
global ros
if ros == 'Linux':
path = sys.path[0]
elif ros == 'Windows':
x=os.path.dirname(os.path.abspath(sys.argv[0])).decode(sys.getfilesystemencoding())
print x
print type(x)
return x
else:
if sys.argv[0].find('/') != -1:
path = sys.argv[0]
else:
path = sys.path[0]
if isinstance(path,str):
path=path.decode('utf-8')
#判断为脚本文件还是py2exe编译后的文件,如果是脚本文件,则返回的是脚本的目录,如果是编译后的文件,则返回的是编译后的文件路径
if os.path.isdir(path):
return path
elif os.path.isfile(path):
return os.path.dirname(path)
def getEPUBMeta(ifile):
"""
return a dict of epub meta data
ifile is the path to the epub file
"""
try:
zfile = zipfile.ZipFile(ifile,'r')
except:
return False
container_xml = zfile.open('META-INF/container.xml')
context = etree.iterparse(container_xml)
opfpath='OPS/content.opf'
for action, elem in context:
if elem.tag[-8:].lower()=='rootfile':
try:
opfpath=elem.attrib['full-path']
except:
break
break
opf_file = zfile.open(opfpath)
context = etree.iterparse(opf_file)
meta_list={}
for action, elem in context:
if elem.tag.split('}')[0][1:].lower()=='http://purl.org/dc/elements/1.1/':
meta_list[elem.tag.split('}')[-1:][0]]=elem.text
return meta_list
class KPUB(threading.Thread):
def __init__(self,ipath,rloc_base_url=u'http://SELF:8000/',kcurl='http://127.0.0.1:50201/'):
"""
ipath is a unicode, represent the share_root
rloc_base_url is the base URL of resouce location, should be unicode
kcurl is the XMLRPC URL of the KADP
"""
threading.Thread.__init__(self)
# create logger
self.lifetime=60*60*24*3 #3 day lifetime
self.SALT = 'DKUYUPUB'
self.running = True
self.logger = logging.getLogger("KPUB")
self.logger.setLevel(logging.DEBUG)
# create console log handler
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = \
logging.Formatter('%(asctime)s - %(name)s - %(levelname)s : %(message)s'
)
ch.setFormatter(formatter)
# add console handler to logger, multiple handler could be added to same logger
self.logger.addHandler(ch)
self.logger.disabled = True
## self.states={}#this is a dict used to save pub states
if os.path.isdir(ipath) != True:
raise ValueError('Invalid Path:'+ipath)
else:
self.root=os.path.abspath(ipath)
self.rloc_base=unicode(rloc_base_url).encode('utf-8')
self.kserver=xmlrpclib.Server(kcurl)
#load saved states
## rid,
## data,
## rtype=1,
## rloc=None,
## metadata={},
## owner_id='SELF',
## ctime=None
## def saveStates(self):
## fname = self.root+os.sep+'.kpub.states'
## savef = open(fname, 'wb')
## saves = cPickle.dumps(self.states, 2)
## saves = struct.pack('f',time.time()) + saves
## m = hashlib.sha224()
## m.update(saves+self.SALT)
## savef.write(m.digest()+saves) #use sha224 to hash
## savef.close()
## def loadStates(self):
## fname = self.root+os.sep+'.kpub.states'
## if not os.path.exists(fname):
## self.logger.warning('saved states not found')
## return False
## try:
## savef = open(fname, 'rb')
## loads = savef.read()
## m = hashlib.sha224()
## m.update(loads[28:]+self.SALT)
## if m.digest() != loads[:28]:
## return False
## if time.time() - (struct.unpack('f',loads[28:32])[0]) > self.lifetime:
## return False
## self.states = cPickle.loads(loads[32:])
## savef.close()
## except Exception, inst:
## self.logger.error("loadStates failed\n")
## self.logger.error(str(inst))
## return False
## return True
def pubBook(self,bookpath):
"""
Publish a book via KADP
bpath is the full path to the book
"""
global ros
bpath=os.path.abspath(bookpath)
if os.path.isfile(bpath) == False:
return False
meta_list={}
if os.path.splitext(bpath)[1].lower()=='.epub':
meta_list=getEPUBMeta(bpath)
else:
meta_list['size']=os.stat(bpath).st_size
for k,v in meta_list.items():
if v == None:
meta_list[k]=''
inf=open(bpath,'rb')
m = hashlib.sha1()
m.update(inf.read())
rid=m.digest()
#rid = longbin.LongBin(rid)
inf.close()
data=os.path.basename(bpath)
#data=KADP.AnyToUnicode(data)
if isinstance(data,str):
data=data.decode(sys.getfilesystemencoding())
## if ros != 'Windows':
## data=data.decode('utf-8')
## else:
## data=data.decode('utf-16')
try:
rlpath=os.path.relpath(bpath,self.root)
except Exception, inst:
self.logger.error('pubBook:'+traceback.format_exc())
self.logger.error('pubBook: catched exception: '
+ str(inst))
return False
if rlpath[:2]=='..':
return False
if isinstance(rlpath,unicode):
rlpath=rlpath.encode('utf-8')
rlpath=urllib.quote(rlpath)
#check if the resource has been published within last lifetime
## if rid in self.states:
## if self.states[rid]['relpath']==rlpath:
## if time.time()-self.states[rid]['lastpub']<=self.lifetime:
## return False
## else:
## if os.path.exists(self.states[rid]['bookpath']):
## return False
rloc=self.rloc_base+rlpath
rtype=1
#kres = KADP.KADRes(rid,data,rtype,rloc,meta_list)
fname=os.path.splitext(data)[0]
if os.path.splitext(bpath)[1].lower()=='.epub':
if 'title' in meta_list:
fname=meta_list['title']
if not isinstance(fname,unicode):
fname=fname.decode('utf-8')
fname=fname.encode('utf-8')
kw_list = list(jieba.cut(fname,cut_all=False))
klist = []
p = re.compile('^\d+$')
for kw in kw_list:
## kw = tok.text.decode('utf-8')
if len(kw)<2:continue
if p.search(kw) != None:continue
klist.append(kw.encode('utf-8'))
if not fname in klist:
klist.append(fname)
#book_state={'rid':rid,'relpath':rlpath,'lastpub':time.time(),'bookpath':bookpath}
if klist != []:
try:
self.logger.debug(u'pubBook: publishing '+data+u' with keywords: '+(' '.join(klist).decode('utf-8')))
self.kserver.publishRes(klist,base64.b16encode(rid),data,rtype,rloc,meta_list,'SELF')
except Exception, inst:
self.logger.error('pubBook:'+traceback.format_exc())
self.logger.error('pubBook: catched exception: '
+ str(inst))
return False
## self.states[rid]={'relpath':rlpath,'lastpub':time.time(),'bookpath':bookpath}
return True
def getNovelFileList(self):
"""
return a list of file with following suffix:
txt/html/htm/epub/umd/jar/zip/rar
following files will be excluded:
- filesize smaller than 256KB
-
"""
ext_list=['txt','html','htm','epub','umd','jar','zip','rar']
rlist=[]
#p = re.compile('^[0-9_]+$')
for root,dirs,files in os.walk(self.root):
for fname in files:
if os.path.splitext(fname)[1].lower()[1:] in ext_list:
#if p.match(os.path.splitext(fname)[0]) == None:
fpath=os.path.join(root,fname)
if os.stat(fpath).st_size>=256000: # this is to avoid publishing small file
rlist.append(fpath)
return rlist
def run(self):
## mmseg.dict_load_chars(cur_file_dir()+os.sep+'chars.dic')
## mmseg.dict_load_words(cur_file_dir()+os.sep+'booknames.dic')
time.sleep(10)#wait for KADP startup
## self.loadStates()
while self.running == True:
flist=self.getNovelFileList()
for book in flist:
self.pubBook(book)
if self.running == False:
## self.saveStates()
return
time.sleep(3)
time.sleep(60)
## self.saveStates()
return
def stop(self):
self.running=False
if __name__ == '__main__':
## import signal
## def signal_handler(signal, frame):
## global kp
## print 'You pressed Ctrl+C!'
## kp.stop()
## signal.signal(signal.SIGINT, signal_handler)
if len(sys.argv)>=2:
sroot=sys.argv[1]
try:
kcurl=sys.argv[2]
except:
kcurl='http://127.0.0.1:50201/'
kp = KPUB(sroot,kcurl=kcurl)
kp.start()
print "starting..."
while True:
try:
kp.join(1)
except KeyboardInterrupt:
print "stopped"
kp.stop()
break
else:
print "kpub <share_root> <ctrl_url>"
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,247
|
hujun-open/litebook
|
refs/heads/master
|
/KADP.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Name: KADP, a Kademlia based P2P protocol
# Purpose:
#
#
# Author: Hu Jun
#
# Created: 12/09/2011
# Copyright: (c) Hu Jun 2011
# Licence: GPLv3
# for latest version, visit project's website: http://code.google.com/p/ltbnet/
#
# ------------------------------------------------------------------------------
#
# todo: need to fix some exception while kpubing
#
#
#import inspect
import platform
MYOS = platform.system()
import sys
import traceback
import os
import urllib
import os.path
import subprocess
import cPickle
import longbin
from operator import attrgetter
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor, defer, task
from twisted.application.internet import TimerService
from twisted.internet.protocol import Protocol, Factory
import hashlib
import socket
import SocketServer
import threading
import time
import struct
import random
import chardet
import Queue
import urlparse
import ConfigParser
import netifaces
##if MYOS != "Darwin":
## import netifaces
##else:
## from netifaces_osx import netifaces
# import wx.lib.newevent
import xmlrpclib
from twisted.web.xmlrpc import XMLRPC, withRequest
from twisted.web import server as TW_xmlserver
import base64
import logging
from logging.handlers import DatagramHandler
#from logging.handlers import SysLogHandler
##from pymmseg import mmseg
KPORT = 50200 #UDP port for KADP message
KCPORT = 50201 #tcp port for xmlRPC
# (ResouceUpdateEvt,EVT_RU)=wx.lib.newevent.NewEvent()
def AnyToUnicode(input_str, coding=None):
"""Convert any coding str into unicode str. this function should used with function DetectFileCoding"""
if isinstance(input_str, unicode):
return input_str
if coding != None:
if coding != 'utf-8':
if coding.lower() == 'gb2312':
coding = 'GBK'
coding = coding.upper()
output_str = unicode(input_str, coding, errors='replace')
else:
output_str = input_str.decode('utf-8', 'replace')
else:
output_str = unicode(input_str, 'gbk', errors='replace')
return output_str
def getOSXIP():
"""
return the ethernet interface ip that in the OSX
"""
int_list=netifaces.interfaces()
if 'en0' in int_list:
return netifaces.ifaddresses('en0')[2][0]['addr']
for intf in int_list:
int_info=netifaces.ifaddresses(intf)
if 2 in int_info and 18 in int_info:
return int_info[2][0]['addr']
return False
class KQueue(Queue.Queue):
"""
FIFO Q, if maxsize is reached, then oldest item will be removed
"""
def __init__(self,maxsize,logger):
Queue.Queue.__init__(self,maxsize)
self.maxlen=maxsize
self.logger=logger
def put(self,item,block=True,timeout=None):
if self.full() == True:
try:
self.get_nowait()
except Exception, inst:
self.logger.error('KQueue.put:'+traceback.format_exc())
self.logger.error('KQueue.put: catched exception: '
+ str(inst))
try:
Queue.Queue.put(self,item,block=False)
except Exception, inst:
self.logger.error('KQueue.put:'+traceback.format_exc())
self.logger.error('KQueue.put: catched exception: '
+ str(inst))
class KADResList:
"""
This class is used to store all known resources (KADRes)
the structure is:
- {kw:{rid:[res,]}
"""
def __init__(self,proto):
"""proto is the KADProtocol
"""
self.reslist = {}
self.tExpire=86500
self.tReplicate=3600
self.tRepublish=86400
self.proto=proto #This is the KADProtocol
self.SALT = 'DKUYU'#salt for hashing
def __contains__(self,res):
"""
check if the specified res is in
with same rid and rloc
"""
for kw in self.reslist.values():
if res.rid.val in kw:
for r in kw[res.rid.val]:
if r.rloc == res.rloc: return True
return False
def setPubed(self,res,pubed=True):
"""
set the published status of res
"""
for kw in self.reslist.values():
if res.rid.val in kw:
for r in kw[res.rid.val]:
if r.rloc == res.rloc:
r.published=pubed
return True
def isPubed(self,res):
"""
check if the res is in the local list and already published
"""
for kw in self.reslist.values():
if res.rid.val in kw:
for r in kw[res.rid.val]:
if r.rloc == res.rloc and r.published==True:
return True
return False
def clearAll(self):
"""
clear all stored res
"""
self.reslist={}
def add_res(self, kw, res_list, src_nodeid):
"""
kw is a keyword, must be unicode, return False otherwise
res is a list of KADRes
src_nodeid is a 20bytes str of source NodeID
"""
if not isinstance(kw,unicode):
self.proto.logger.warning(u'add_res:kw is not unicode')
return False
if not kw in self.reslist:
self.reslist[kw] = {}
for res in res_list:
if not (res.rid.val in self.reslist[kw].keys()):
self.reslist[kw][res.rid.val] = [res,]
else:
found = False
for r in self.reslist[kw][res.rid.val]:
if r.owner_id == res.owner_id:
if res.owner_id == src_nodeid: #only replace the existing res when owner is publishing
self.reslist[kw][res.rid.val].remove(r)
self.reslist[kw][res.rid.val].append(res)
found = True
break
if found == False: # if the res is from another owner
self.reslist[kw][res.rid.val].append(res)
def get_res_list(self, kw, rtype=0):
"""
return a list of all resources that has kw and rtype
kw is a keyword string
rtype is resource type,a integer,0 means all types match
return False if kw is not found.
"""
rlist=[]
for cur_kw in self.reslist.keys():
if cur_kw.find(kw)!=-1:
#if kw in self.reslist: #no need for search for kw one by one, because
for rl in self.reslist[cur_kw].values():
for r in rl:
if r.type == rtype or rtype == 0:
found=False
for xr in rlist: #if same res and rloc found in rlist, then skip this one.
if xr.rid == r.rid and xr.rloc == r.rloc:
found=True
break
if found == False: rlist.append(r)
if len(rlist) != 0:
return rlist
else:
return False
def del_res(self,rid,owner_id,kw=None):
"""
remove a res from the list
"""
if kw != None: #if kw is known
if not kw in self.reslist: return
for r in self.reslist[kw][rid]:
if r.owner_id == owner_id:
self.reslist[kw][rid].remove(r)
break
else:# if kw is unknow
for rid_list in self.reslist.values():
for rl in rid_list.values():
for r in rl:
if r.owner_id == owner_id and r.rid == rid:
rl.remove(r)
break
def remove_expired_res(self):
"""
remove all expired res
"""
for rid_list in self.reslist.values():
for rl in rid_list.values():
for r in rl:
curtime=time.time()
if curtime - r.creation_time >= self.tExpire:
rl.remove(r)
def get_all_res(self):
"""
yield all non-expired (kw, res)
it will also remove exipred res
"""
for (kw,rid_list) in self.reslist.items():
for rl in rid_list.values():
for r in rl:
curtime = time.time()
delta = curtime - r.creation_time
if delta >= self.tExpire:
rl.remove(r)
else:
yield (kw,r)
def replicate(self):
self.proto.logger.debug('Start replicating RES')
for (kw,rid_list) in self.reslist.items():
for rl in rid_list.values():
for r in rl:
curtime = time.time()
delta = curtime - r.creation_time
if delta >= self.tExpire:
rl.remove(r)
else:
self.proto.logger.debug("KADResList_replicate:"+self.proto.knode.nodeid.val+"'s task_list has "+str(len(self.proto.task_list)))
#self.proto.logger.debug(u"replicate: 中文怎么就不行".encode('utf-8')) #need to convert it to utf-8
#self.print_me()
self.proto.PublishRes([kw,],r)
def republish(self):
self.proto.logger.debug('entering republish')
#self.proto.logger.debug(u'这是一个测试'.encode('utf-8'))
for (kw,rid_list) in self.reslist.items():
for rl in rid_list.values():
for r in rl:
curtime = time.time()
delta = curtime - r.creation_time
if delta >= self.tExpire:
rl.remove(r)
else:
if r.owner_id == self.proto.knode.nodeid.val:
self.proto.logger.debug(u"republish: "+kw+u" "+unicode(r))
#self.print_me()
self.proto.PublishRes([kw,],r)
def print_me(self):
self.proto.logger.debug("kw list has:\n")
for kw in self.reslist.keys():
self.proto.logger.debug(kw.encode('utf-8'))
#print kw
for (kw,rid_list) in self.reslist.items():
for rl in rid_list.values():
for r in rl:
self.proto.logger.debug(kw.encode('utf-8')+'---'+
r.rloc.encode('utf-8')+" "+r.owner_id.encode('hex_codec'))
#print kw+u'---'+unicode(r.rloc)+u" "+unicode(r.owner_id)
def saveRes(self):
fname = self.proto.getConfigDir()+os.sep+'resl.kadp'
savef = open(fname, 'wb')
saves = cPickle.dumps(self.reslist, 2)
t=time.time()
saves = struct.pack('f',time.time()) + saves
m = hashlib.sha224()
m.update(saves+self.SALT)
savef.write(m.digest()+saves) #use sha224 to hash
savef.close()
def loadRes(self):
self.proto.logger.debug("loading Res from "+self.proto.getConfigDir()+os.sep+'resl.kadp')
fname = self.proto.getConfigDir()+os.sep+'resl.kadp'
if not os.path.exists(fname):
return False
try:
savef = open(fname, 'rb')
loads = savef.read()
m = hashlib.sha224()
m.update(loads[28:]+self.SALT)
if m.digest() != loads[:28]:
return False
if time.time() - (struct.unpack('f',loads[28:32])[0]) > self.tExpire:
return False
rl = cPickle.loads(loads[32:])
savef.close()
except Exception, inst:
self.proto.logger.error("loadRes failed\n")
self.proto.logger.error(str(inst))
return False
self.reslist = rl
return True
class KADFile:
def __init__(
self,
ifname=None,
fsize=None,
fid=None,
fpath='',
):
"""
fpath is full path of the file.
KADFile has following propeties:
- id, 20 bytes string
- name, unicode
- size, int
"""
if fpath != '' and fpath != None:
fname = os.path.basename(fpath)
self.name = AnyToUnicode(fname)
self.size = os.path.getsize(fpath)
inf = open(fpath, 'rb')
m = hashlib.sha1()
m.update(inf.read())
self.id = m.digest()
inf.close()
else:
self.name = AnyToUnicode(ifname)
self.size = fsize
self.id = fid
##class KADNovel(KADFile):
## """
## This is class for Novel, with metadata for novels like author, title.
## """
## def __init__(self,fpath):
## """
## fpath is the full path of novel
## title is title of the novel, it might be different from the filename
## author is the author of the novel
## """
## KADFile.__init__(fpath=fpath)
## (fbasename,fext) = os.path.splitext(fpath)
## fext = fext.lower()
## self.title = fbasename
## self.author = ''
## self.meta_list = {}
## if fext == '.epub':
## meta_list = getEPUBMeta(fpath)
## if meta_list != False and meta_list != {}:
## self.title = meta_list['title']
## self.author = meta_list['creator']
## self.meta_list = meta_list
class KADTreeNode:
def __init__(self, nodedata=None, parentnode=None):
self.left = None
self.right = None
self.parent = parentnode
self.bucket = []
self.latime = 0 #last time of looking-up in the bucket, 0 means no looking-up since creation
self.position = None # left or right child of parent
class KADTree:
def __init__(self, proto, max_level=160):
self.root = KADTreeNode(None)
self.bucket_size = 20 # maximum contacts in one bucket
self.proto = proto
self.max_level = max_level
self.count = 0
self.tExpire = 864000 #10 days
self.SALT = 'DKUYU'#salt for hashing
self.found = False #used by get1stIB()
def getRoot(self):
return self.root
def insertBucket(
self,
bucket,
newnode,
iforce=False,
):
"""Insert a contact into a bucket
bucket is a list
newnode ia KADNode
"""
newnode.lastsee = time.time()
for node in bucket:
if node.nodeid == newnode.nodeid:
# if newknode already exist
self.proto.logger.debug('insertBucket---- node already existed in bucket, updated'
)
bucket.remove(node)
node.lastsee = time.time()
bucket.append(node)
bucket.sort(key=attrgetter('lastsee'))
return
if len(bucket) < self.bucket_size: # if bucket is NOT full
self.proto.logger.debug('KADTree.insertBucket:add new contact')
bucket.append(newnode)
self.count += 1
return
if len(bucket) >= self.bucket_size: # bucket is full
self.proto.logger.debug("InsertBucket: bucket full")
if iforce == True:
bucket[self.bucket_size - 1] = newnode
else:
# ping 1st node
self.proto.logger.debug('insertBucket:bucket is full, ping the 1st node'
)
pseq = self.proto.getSeq()
self.proto.task_list[pseq] = {'task': 0,
'object': {'bucket': bucket, 'node': newnode}}
self.proto.Ping(bucket[0], self.proto.PingCallback,
pseq)
def remove(self,nodeid):
"""
remove a contact
nodeid is LongBin
"""
bucket = self.getBucket(nodeid)
for c in bucket:
if c.nodeid == nodeid:
bucket.remove(c)
self.count-=1
break
def insert(self, newnode):
"""insert a KADNode into tree
newnode is a KADNode
"""
if self.proto.knode.nodeid == newnode.nodeid: # return if contact is self
return
self.insertBucket(self.getBucket(newnode.nodeid),newnode)
def getBucket(self, nodeid):
""" return the bucket that nodeid belongs to
nodeid is a LongBin
"""
delta = self.proto.knode.nodeid ^ nodeid
tks = str(delta)
pnd = self.root
level = 1
for c in tks:
if c == '0':
if level <= 3:
if pnd.right == None:
newtnode = KADTreeNode(parentnode=pnd)
pnd.right = newtnode
pnd = pnd.right
elif level <= 159:
if int(tks[:level], 2) in range(5): # keep descending
if pnd.right == None:
newtnode = KADTreeNode(parentnode=pnd)
pnd.right = newtnode
pnd = pnd.right
else:
return pnd.bucket
elif level == self.max_level:
return pnd.bucket
else:
if level <= 3:
if pnd.left == None:
newtnode = KADTreeNode(parentnode=pnd)
pnd.left = newtnode
pnd = pnd.left
elif level <= 159:
if int(tks[:level], 2) in range(5): # keep descending
if pnd.left == None:
newtnode = KADTreeNode(parentnode=pnd)
pnd.left = newtnode
pnd = pnd.left
else:
return pnd.bucket
elif level == self.max_level:
return pnd.bucket
level += 1
def get_list(
self,
rlist,
maxn=None,
rootnode=None,
):
"""
return at least maxn KADNode in rlist
rlist should be []
maxn is an integer
"""
if rootnode == None:
cnode = self.root
else:
cnode = rootnode
rlist += cnode.bucket
if maxn != None and len(rlist) >= maxn:
return
if cnode.left == None and cnode.right == None:
return
else:
if cnode.left != None:
self.get_list(rlist, maxn, cnode.left)
if cnode.right != None:
self.get_list(rlist, maxn, cnode.right)
def get_count(self):
"""
return the total number of contacts
"""
clist = []
self.get_list(clist)
return len(clist)
def get1stIB(self):
"""
get the nid of first idle bucket in the tree.
the found nid will be put in self.found
"""
self.found=None
self.get_idle_bucket(self.root)
return self.found
def get_idle_bucket(self,rootnode,nid=''):
"""
support function for get1stIB()
"""
if self.found != None:
return
#print "latime is ",rootnode.latime, " vaule is ",rootnode.bucket
if time.time() - rootnode.latime>self.proto.tRefresh and \
rootnode.left == None and rootnode.right == None:
#print "found nid is ",nid
self.found=nid
return
if rootnode.left == None and rootnode.right == None:
return
if rootnode.left != None and self.found == None:
r1=self.get_idle_bucket(rootnode.left,nid+'1')
if rootnode.right != None and self.found == None:
r2=self.get_idle_bucket(rootnode.right,nid+'0')
def print_me(self,rootnode,nid=''):
"""
print the tree
"""
#print "i am in level ",level
if rootnode.bucket != []:
self.proto.logger.debug('current nid is ---- ' + nid)
for c in rootnode.bucket:
self.proto.logger.debug(c.nodeid.hexstr())
self.proto.logger.debug(c.strME())
self.proto.logger.debug("_____________")
if rootnode.left==None and rootnode.right==None:
return
if rootnode.left !=None:
self.print_me(rootnode.left,nid+'1')
if rootnode.right !=None:
self.print_me(rootnode.right,nid+'0')
def get_closest_node(self, target_id):
"""
return the tree node that target_id belongs to
target_id is LongBin
"""
## if self.proto.knode.nodeid==target_id: #return if contact is self
## return None
delta = self.proto.knode.nodeid ^ target_id
tks = str(delta)
pnd = self.root
level = 1
for c in tks:
if c == '0':
if level <= 3:
if pnd.right == None:
newtnode = KADTreeNode(parentnode=pnd)
pnd.right = newtnode
pnd = pnd.right
elif level <= 159:
if int(tks[:level], 2) in range(5): # keep descending
if pnd.right == None:
newtnode = KADTreeNode(parentnode=pnd)
pnd.right = newtnode
pnd = pnd.right
else:
# go into bucket
pnd.latime=time.time()
return pnd
elif level == self.max_level:
pnd.latime=time.time()
return pnd
else:
if level <= 3:
if pnd.left == None:
newtnode = KADTreeNode(parentnode=pnd)
pnd.left = newtnode
pnd = pnd.left
elif level <= 159:
if int(tks[:level], 2) in range(5): # keep descending
if pnd.left == None:
newtnode = KADTreeNode(parentnode=pnd)
pnd.left = newtnode
pnd = pnd.left
else:
# go into bucket
pnd.latime=time.time()
return pnd
elif level == self.max_level:
pnd.latime=time.time()
return pnd
level += 1
def get_closest_list(self, target_id, maxn=None):
"""
return a sorted list with no more than maxin closest contacs to target_id
target_id is a LongBin
"""
rlist = []
if maxn == None:
maxn = self.proto.k
pnd = self.get_closest_node(target_id)
while len(rlist) < maxn:
clist = []
if pnd.parent == None:
break
else:
pnd = pnd.parent
self.get_list(rlist, rootnode=pnd)
rlist += clist
rlist = sorted(rlist, key=lambda c: c.nodeid ^ target_id)
return rlist[:maxn]
def saveContact(self):
fname = self.proto.getConfigDir()+os.sep+'kcl.kadp'
savef = open(fname, 'wb')
clist = []
self.get_list(clist)
saves = cPickle.dumps(clist, 2)
saves = struct.pack('f',time.time()) + saves
m = hashlib.sha224()
m.update(saves+self.SALT)
savef.write(m.digest()+saves) #use sha224 to hash
savef.close()
def loadContact(self):
self.proto.logger.debug("loading contact from "+self.proto.getConfigDir()+os.sep+'kcl.kadp')
fname = self.proto.getConfigDir()+os.sep+'kcl.kadp'
if not os.path.exists(fname):
self.proto.logger.error("can not open "+fname)
return False
try:
savef = open(fname, 'rb')
loads = savef.read()
m = hashlib.sha224()
m.update(loads[28:]+self.SALT)
if m.digest() != loads[:28]:
return False
if time.time() - (struct.unpack('f',loads[28:32])[0]) > self.tExpire:
self.proto.logger.warning('loadContact: saved contacts expired')
return False
bl = cPickle.loads(loads[32:])
savef.close()
except Exception, inst:
self.proto.logger.error('loadContact:'+traceback.format_exc())
self.proto.logger.error('loadContact: catched exception: '
+ str(inst))
return False
if len(bl)>0:
for c in bl:
self.insert(c)
if self.get_count >0:
return True
else:
return False
else:
self.proto.logger.error("No contact in the saved file")
return False
class KADNode:
def __init__(
self,
nodeid=None,
ip=None,
port=None,
nodes=None,
):
"""nodeid is LongBin
ip is string
port is int
nodes if a string=4bytes_IP+2bytes_port+20bytes_nodeid,when present,
other parameter will be ignored.
"""
if nodes == None:
self.nodeid = nodeid
self.v4addr = ip
self.port = port
else:
if len(nodes) != 26:
raise ValueError('KADNode__init__:nodes must be 26 bytes long,got '
+ str(len(nodes)) + ' bytes instead')
return
ips = nodes[:4]
self.v4addr = ''
ipl = struct.unpack('cccc', ips)
for i in ipl:
self.v4addr += str(ord(i)) + '.'
self.v4addr = self.v4addr[:-1]
self.port = struct.unpack('H', nodes[4:6])
self.nodeid = longbin.LongBin(nodes[6:26])
self.lastsee = time.time()
self.status = 'init' # status is one of 'init'/'firewalled'/'clear'/'unreachable'
self.distance = None
def __str__(self):
"""Generate a binary str=4bytes_IP+2bytes_port+20bytes_nodeid"""
ips = ''
ipl = self.v4addr.split('.')
for i in ipl:
ips += struct.pack('c', chr(int(i)))
ports = struct.pack('H', self.port)
return ips + ports + self.nodeid.val
def strME(self):
"""
Generate a printable string for the KADNode
"""
rs=''
rs+="NodeId:"+self.nodeid.hexstr()+"-----"
rs+="Addr:"+self.v4addr+":"+str(self.port)
return rs
class KADRes:
"""
Resrouce
"""
def __init__(
self,
rid,
data,
rtype=1,
rloc=None,
metadata={},
owner_id='SELF',
ctime=None
):
"""
rid is a LongBin, represent the resource id
data is resource data, could be any thing
rtype is the type of resouce, a integer
rloc is the location of the resource,like HTTP URL
metadata is a dict include meta data for the resources, e.g filesize
ctime is the creation time(int sec)
owner_id is a str
"""
self.rid = rid
self.data = data
self.type = rtype
if ctime == None:
self.creation_time = time.time()
self.rloc = rloc
self.meta_list = metadata
self.owner_id=owner_id
self.published=False #if this res has been successfully published
##class KAD_Req:
##
## def __init__(
## self,
## dst_node,
## code,
## seq,
## attr_list=None,
## send_time=0,
## ):
## self.dst_node = dst_node
## self.code = code
## self.seq = seq
## self.attr_list = attr_list
## self.create_time = time.time()
## self.send_time = send_time
##raising Exception should not be used in network protocol.
##class ParseError(Exception):
## def __init__(self,msg,packet):
## self.msg=msg
## self.wrong_packet=packet
## def __str__(self):
## return self.msg
##
##class EncapError(Exception):
## def __init__(self,msg):
## self.msg=msg
## def __str__(self):
## return self.msg
##
##class ProtoError(Exception):
## """
## id is the ErrorID, following is a table of all defined ID:
## - 1: no contact in contact list
## """
## def __init__(self,id):
## self.id=id
##
## def __str__(self):
## return str(self.id)
class KADProtocol(DatagramProtocol):
def __init__(
self,
win=None,
lport=KPORT,
nodeid=None,
addrf=None, #geoip address file, used for bootscan
#dstnode=None,
bip=None,#the ipaddr that protocol listen on,'' means any interface
conf_dir=None,#the directory of configuration files
force_scan=False,#force ip address scan
cserver_url=None, #control server URL, a XMLRPC server URL that search result sent to
nodebug=False, #if enabling display log at start
):
global MYOS
## mmseg.dict_load_defaults()
# following are test code, should be removed
## self.dstnode = dstnode
# end of test code
# current index for bootscan
self.current_ii = 0
self.current_ai = 0
self.bip = bip
self.conf_dir = conf_dir
try:
self.cserver = xmlrpclib.Server(cserver_url)
except:
self.cserver = None
self.rptlist = None
self.packet_seq = 0
self.msg_code_list = range(11)
self.win = win
self.numofcontact = 0
#self.default_lport = KPORT
self.bstrap_url = 'http://boot-ltbnet.rhcloud.com/?'
self.chkport_url = 'http://boot-ltbnet.rhcloud.com/check?'
self.port_open_status = 'INIT' #'INIT' means unknow, 1 means open,-1 means closed, 0 means waiting
self.port_open_nonce = None
self.force_scan = force_scan
# the following two dic apply to all RPCs
self.req_list = {} # seq of reqest packet as the key, used for re-tran
self.task_list = {} # seq of reqest packet as the key, used to do real job
# task == 0 replace contact
#
#
#
self.send_interval = 8 # re-transmission interval, in seconds
self.max_resend = 2 # max number of times for re-tran
#some protocol timers
self.tClearResInterval=600 #interval of clear expired res
self.tExpire=86500 #expire time for res, will be reset by owner publish
self.tRefresh=3600 #refersh time for bucket
self.tReplicate=3600 #republish time for all res in res list
self.tRepublish=86400 #republish time for owning res
#test code
## self.tReplicate=600 #republish time for all res in res list
## self.tRepublish=1200 #republish time for owning res
#end of test code
# parameter for bootscan
self.run_bootscan = False # enable/disable bootscan
self.run_bootscan_interval = 1 # number of seconds
self.max_bootscan_answers = 20 # change interval or stop bootscan when got this number of contacts
self.buck_list = KADTree(self)
self.rlist = KADResList(self) # resource list
self.k = 20
self.buck_size = self.k
self.alpha = 3
self.buck_list_len = 160
#some scale limit
self.MAX_NUM_CONTACT = 5000
self.MAX_NUM_RES = 50000
# create logger
self.logger = logging.getLogger("KADP")
self.logger.setLevel(logging.DEBUG)
# create console log handler
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = \
logging.Formatter('%(asctime)s - %(name)s - %(levelname)s : %(message)s'
)
ch.setFormatter(formatter)
# add console handler to logger, multiple handler could be added to same logger
self.logger.addHandler(ch)
self.logger.disabled = nodebug
#create Qs
self.updateContactQ = KQueue(512,self.logger)
self.FindNodeReplyQ = Queue.Queue()
self.BootReplyQ = Queue.Queue()
self.StoreReplyQ = Queue.Queue()
self.FindValueReplyQ = Queue.Queue()
#try to load the configuration file
## if nodeid != None:
## testc = True
## else:
## self.logger.debug("loading KADP config...")
## testc = not self.loadConfig()
##
## if testc == True:
## self.listening_port = lport
## if nodeid != None:
## self.knode = KADNode(nodeid,
## socket.gethostbyname(socket.gethostname()),
## lport)
## else:
## self.knode = KADNode(self.genNodeID(),
## socket.gethostbyname(socket.gethostname()),
## lport)
self.listening_port = lport
if MYOS=='Darwin':
myhostip=getOSXIP()
else:
myhostip=socket.gethostbyname(socket.gethostname())
if nodeid != None:
self.knode = KADNode(nodeid,
myhostip,
lport)
else:
self.knode = KADNode(self.genNodeID(),
myhostip,
lport)
self.rlist.loadRes()
# bootstrapping code by scan IP space of CT/CU/CM
# load addr list into self.addrlist as list of [start_addr,count,network]
self.addrlist = LoadAddr(addrf)
#
self.bookext_list = ['txt', 'umd', 'jar']
def getInfo(self):
"""
return lport and self nodeid as string
"""
return [self.listening_port,str(self.knode.nodeid)]
def printme(self):
return [self.listening_port,self.knode.nodeid.hexstr()]
def setTaskList(self, rptlist):
self.rptlist = rptlist
def getDBcastAddr(self, addr, netmask):
"""return a subnet broadcast address
"""
alist = addr.split('.')
nmlist = netmask.split('.')
if len(alist) != 4 or len(nmlist) != 4:
return None
## try:
a1 = int(alist[0])
if a1 == 127 or a1 >= 224 or a1 == 0:
return None
tlist = []
for x in alist:
if int(x) <= 0 or int(x) > 255:
return None
tlist.append(chr(int(x)))
fms = 'cccc'
rs = struct.pack(fms, tlist[0], tlist[1], tlist[2], tlist[3])
fms = 'I'
ai = struct.unpack(fms, rs)
tlist = []
for x in nmlist:
if int(x) < 0 or int(x) > 255:
return None
tlist.append(chr(int(x)))
fms = 'cccc'
rs = struct.pack(fms, tlist[0], tlist[1], tlist[2], tlist[3])
fms = 'I'
ni = struct.unpack(fms, rs)
## except:
## return None
fms = 'cccc'
rs = struct.pack(fms, chr(255), chr(255), chr(255), chr(255))
fms = 'I'
allone = struct.unpack(fms, rs)
tmpi = allone[0] ^ ni[0]
dbi = ai[0] | tmpi
fms = 'I'
rs = struct.pack(fms, dbi)
fms = 'cccc'
(s1, s2, s3, s4) = struct.unpack(fms, rs)
rlist = (s1, s2, s3, s4)
dbcast = ''
for r in rlist:
dbcast += str(ord(r)) + '.'
return dbcast[:-1]
def genNodeID(self):
"""
Generate NodeID for self
"""
global MYOS
if MYOS == 'Darwin':
hostip=getOSXIP()
else:
hostip = socket.gethostbyname(socket.gethostname())
hostname = socket.gethostname()
times = str(time.time())
fid = '00000000000000000000'
while fid == '00000000000000000000':
rrr = str(random.randint(1, 10000))
m = hashlib.sha1()
m.update(rrr + ':' + times + ':' + hostip + ':' + hostname)
for x in range(5):#repeat random seeding for 5 times
rrr = str(random.randint(1, 10000))
m.update(rrr)
fid = m.digest()
return longbin.LongBin(fid)
def ErrCallback(self, fail):
self.logger.error('ErrBack:' + fail.getErrorMessage())
def FindNodeCallback(self, r):
try: # otherwise the exception won't get print out
if r['result'] != 'NoContact':
self.logger.debug('Entering FindNodeCallback')
taskseq = self.req_list[r['seq']]['taskseq']
#self.logger.debug('taskseq is ' + str(taskseq))
#self.logger.debug('the task is ' + str(self.task_list[taskseq]))
if not taskseq in self.task_list:
self.logger.warning('FindNodeCallback: no such task')
return
thetask = self.task_list[taskseq]
#print taskseq,'--->',thetask['shortlist']
for c in thetask['shortlist']:
if c['contact'].nodeid.val == r['src_id']:
c['status'] = 'answered'
if r['result'] != False:
self.logger.debug('FindNodeCallback: found '
+ str(c['contact'].nodeid.hexstr()))
thec = c
break
if r['result'] == True: # if got the reply to FindNode
self.logger.debug('FindNodeCallback:Got the answer')
host_alist = r['attr_list'][4]
# following code is used to add all contacts from FindNodeReply into buck_list
# you may want to change this behavior
for h in host_alist:
newnode = KADNode(h['nodeid'], h['ipv4'], h['port'])
newnode.distance = newnode.nodeid ^ thetask['target'
]
found = False
for s in thetask['shortlist']:
if s['contact'].nodeid == newnode.nodeid:
s['contact'] = newnode
found = True
break
if found == False:
thetask['shortlist'
].append({'contact': newnode,
'status': 'init'})
self.updateContactQ.put(newnode)
thetask['shortlist'].sort(key=lambda c: c['contact'
].distance)
thetask['shortlist'] = (thetask['shortlist'])[:self.k]
thetask['onthefly'] -= 1
if thetask['onthefly'] < 0:
thetask['onthefly'] = 0
found = False
self.logger.debug('onthefly is ' + str(thetask['onthefly']))
#print 'short list is', thetask['shortlist']
for c in thetask['shortlist']:
if c['status'] == 'init':
found = True
if thetask['onthefly'] < self.alpha:
c['status'] = 'sent'
self.logger.debug('FindNodeCallback:send another FindNode'
)
self.FindNode(c['contact'], thetask['target'
], self.FindNodeCallback,
taskseq=taskseq)
thetask['onthefly'] += 1
break # twisted doesn't have any sending buffer, you need release the control to reactor to do the sending, if reactor doesn't have chance to gain the control, then then packet may NOT have chance to get sent
elif c['status'] != 'answered':
found = True
if found == False: # lookup stops
self.logger.debug('FindNodeCallback: Stopped')
self.logger.debug('FindNodeCallback: '+self.knode.nodeid.hexstr()+' found '+str(len(thetask['shortlist']))+' contacts')
del self.task_list[taskseq]
thetask['defer'
].callback({'context': thetask['callback_context'
], 'shortlist': thetask['shortlist'],
'result': True})
# following are test code
## for c in thetask['shortlist']:
## print c['contact'].nodeid.val
elif r['result'] == 'NoContact':
# if there is no contact in local buck_list
# send signal to wx app
self.logger.debug('FindNodeCallback:No Contact')
return
else:
# if there is no answer
self.logger.warning("FindNodeCallback: "+str(r['seq'])+" NO ANSWER FROM "+r['src_id'].encode('hex_codec'))
thetask['shortlist'].remove(thec)
self.buck_list.remove(thec['contact'].nodeid)
thetask['onthefly'] -= 1
if thetask['onthefly'] < 0:
thetask['onthefly'] = 0
found = False
for c in thetask['shortlist']:
if c['status'] == 'init':
found = True
if thetask['onthefly'] < self.alpha:
c['status'] = 'sent'
self.FindNode(c['contact'], thetask['target'
], self.FindNodeCallback,
taskseq=taskseq)
thetask['onthefly'] += 1
elif c['status'] != 'answered':
found = True
if found == False: # lookup stops
self.logger.debug('FindNodeCallback:'+self.knode.nodeid.hexstr()+' found '+str(len(thetask['shortlist'])))
self.logger.debug('FindNodeCallback: Stopped')
del self.task_list[taskseq]
thetask['defer'
].callback({'context': thetask['callback_context'
], 'shortlist': thetask['shortlist'],
'result': False})
del self.req_list[r['seq']]
except Exception, inst:
# otherwise the exception won't get print out
self.logger.error('FindNodeCallback:'+traceback.format_exc())
self.logger.error('FindNodeCallback: catched exception: '
+ str(inst))
def FindNodeReply(self):
"""Scan FindNodeReplyQ periodically and send FindNode-Reply
return up to k closet contacts.
"""
# print "FindNodeReply ---- running"
## try:
## (t_nodeid, src_node, rseq) = self.FindNodeReplyQ.get(False)
## except Queue.Empty:
## return
newreqlist=[]
for i in range(50):
try:
(t_nodeid, src_node, rseq,ctime) = self.FindNodeReplyQ.get(False)
newreqlist.append((t_nodeid, src_node, rseq, ctime))
except Queue.Empty:
break
if len(newreqlist) == 0: return
for (t_nodeid, src_node, rseq, ctime) in newreqlist:
if time.time()-ctime>self.send_interval*self.max_resend:
with self.FindNodeReplyQ.mutex:
self.FindNodeReplyQ.queue.clear()
self.logger.debug( "FindNodeReply: FindNodeReplyQ Cleared")
return #clear the queue and return
c_list = self.buck_list.get_closest_list(t_nodeid)
attrs = ''
for c in c_list:
attrs += self.gen_attr(4, str(c))
# r_attr=self.gen_attr(0,True) #result attr is needed for FindNode?
# attrs+=r_attr
(header, seq) = self.gen_header(5, self.knode.nodeid.val,
src_node.nodeid.val, rseq)
packet = self.gen_packet(header, attrs)
self.sendDatagram(src_node.v4addr, src_node.port, packet)
self.logger.debug(str(rseq)+" Send FindNodeReply to "+src_node.nodeid.hexstr())
def FindNode(
self,
dst_node,
fnode_id,
findnodecallback,
iseq=None,
taskseq=None,
):
"""FindNode RPC, this is primitive operation, not an iterative one.
dst_node is knode that being contacted
fnode_id is the key value is being looked for
"""
(header, seq) = self.gen_header(4, self.knode.nodeid.val,
dst_node.nodeid.val, iseq)
attr = self.gen_attr(3, fnode_id.val)
packet = self.gen_packet(header, attr)
if not seq in self.req_list: # if this is a new request
self.logger.debug('Initiate a new FindNode...')
d = defer.Deferred()
d.addErrback(self.ErrCallback)
d.addCallback(findnodecallback) # you might want to change this
self.sendDatagram(dst_node.v4addr, dst_node.port, packet)
callid = reactor.callLater(
self.send_interval,
self.FindNode,
dst_node,
fnode_id,
findnodecallback,
seq,
)
self.req_list[seq] = {
'code': 4,
'callid': callid,
'defer': d,
'send_time': 1,
'dst_node': dst_node,
'fnode': fnode_id,
'taskseq': taskseq,
}
#self.req_list[seq]['send_time'] += 1
return
else:
if self.req_list[seq]['send_time'] > self.max_resend:
# no respond, and max resend time reached
self.logger.debug('stop sending FindNode,no answer from '
+ dst_node.v4addr + ', calling callback')
self.req_list[seq]['defer'].callback({'seq': seq,
'result': False, 'src_id': dst_node.nodeid.val})
else:
self.logger.debug('re-tran FindNode')
self.sendDatagram(dst_node.v4addr, dst_node.port,
packet)
self.req_list[seq]['send_time'] += 1
callid = reactor.callLater(
self.send_interval,
self.FindNode,
dst_node,
fnode_id,
findnodecallback,
seq,
)
self.req_list[seq]['callid'] = callid
def NodeLookup(self, target_key, callback_context=None):
"""
the purpose of NodeLook is to find k closest contact to target_key(longbin)
This is iterative operation, NOT primitive(like FindNode)
target_key is a LongBin
"""
self.logger.debug('init a new NodeLookup')
cshortlist = self.buck_list.get_closest_list(target_key,
self.alpha)
if len(cshortlist) == 0:
self.logger.debug("NodeLookup:cshosrtlist is empty")
# this is how you handle error in protocol, always use callback
# to clean-up, do NOT use raise exception.
return self.FindNodeCallback({'result': 'NoContact'})
for c in cshortlist: # cal the distance to the target
c.distance = c.nodeid ^ target_key
shortlist = []
for c in cshortlist:
shortlist.append({'contact': c, 'status': 'init'})
# use first seq number as the key for this task?
d = defer.Deferred()
thetask = {
'shortest': shortlist[0],
'onthefly': self.alpha,
'shortlist': shortlist,
'defer': d,
'target': target_key,
'callback_context': callback_context,
}
task_seq = self.getSeq()
self.task_list[task_seq] = thetask
for c in shortlist:
c['status'] = 'sent'
self.FindNode(c['contact'], target_key,
self.FindNodeCallback, taskseq=task_seq)
return d # return deferred, use addCallback() to add functions, this defered used to add different function for different purposes like publish,search ..etc.
def FindValueCallback(self, r):
try: # otherwise the exception won't get print out
self.logger.debug('Entering FindValueCallback')
if r['result'] == 'NoContact':
# if there is no contact in local buck_list
# send signal to wx app
self.logger.warning('FindValueCallback:No Contact')
return
taskseq = self.req_list[r['seq']]['taskseq']
## self.logger.debug('taskseq is ' + str(taskseq))
## self.logger.debug('the task is ' + str(self.task_list[taskseq]))
if not taskseq in self.task_list:
self.logger.warning('FindValueCallback: no such task')
return
thetask = self.task_list[taskseq]
## print thetask['defer'].callbacks
## print thetask['defer']._debugInfo
for c in thetask['shortlist']:
if c['contact'].nodeid.val == r['src_id']:
if 'attr_list' in r:
if 6 in r['attr_list']:
c['status'] = 'answered-file'
else:
c['status'] = 'answered'
self.logger.debug('FindValueCallback: found '
+ str(c['contact'].nodeid.hexstr()))
thec = c
break
if r['result'] == True: # if got the reply to FindNode
self.logger.debug('FindValueCallback:Got the answer')
if thec['status'] == 'answered-file': # got the search result
self.logger.debug('FindValueCallback: got result from '
+ r['src_id'].encode('hex_codec'))
for xr in r['attr_list'][6]:
if not xr in thetask['rlist']:
thetask['rlist'].append(xr)
# else:#got some contacts
# process the contacts
if 4 in r['attr_list']:
host_alist = r['attr_list'][4]
# following code is used to add all contacts from FindNodeReply into buck_list
# you may want to change this behavior
for h in host_alist:
newnode = KADNode(h['nodeid'], h['ipv4'],
h['port'])
newnode.distance = newnode.nodeid \
^ thetask['target']
found = False
for s in thetask['shortlist']:
if s['contact'].nodeid == newnode.nodeid:
s['contact'] = newnode
found = True
break
if found == False:
thetask['shortlist'
].append({'contact': newnode,
'status': 'init'})
self.updateContactQ.put(newnode)
thetask['shortlist'].sort(key=lambda c: c['contact'
].distance)
thetask['shortlist'] = (thetask['shortlist'
])[:self.k]
thetask['onthefly'] -= 1
if thetask['onthefly'] < 0:
thetask['onthefly'] = 0
found = False
self.logger.debug('onthefly is ' + str(thetask['onthefly']))
#print 'short list is', thetask['shortlist']
for c in thetask['shortlist']:
if c['status'] == 'init':
found = True
if thetask['onthefly'] < self.alpha:
c['status'] = 'sent'
self.logger.debug('FindValueCallback:send another FindValue'
)
self.FindValue(c['contact'], thetask['kw'],
thetask['rtype'],
self.FindValueCallback,
taskseq=taskseq)
thetask['onthefly'] += 1
break # twisted doesn't have any sending buffer, you need release the control to reactor to do the sending, if reactor doesn't have chance to gain the control, then then packet may NOT have chance to get sent
elif c['status'] != 'answered' and c['status'] \
!= 'answered-file':
found = True
if found == False: # lookup stops
self.logger.debug('FindValueCallback: Stopped')
# following are test code
self.logger.debug('i found '+str(len(thetask['shortlist'])))
## for c in thetask['shortlist']:
## print c['contact'].nodeid.val
## print thetask['rlist']
# end of test code
del self.task_list[taskseq]
thetask['defer'].callback({
'context': thetask['callback_context'],
'rlist': thetask['rlist'],
'shortlist': thetask['shortlist'],
'result': True,
'kw': thetask['kw'],
})
## elif r['result'] == 'NoContact':
##
## # if there is no contact in local buck_list
## # send signal to wx app
##
## self.logger.warning('FindValueCallback:No Contact')
## return
else:
# if there is no answer
self.logger.warning('FindValueCallback:No Answer')
thetask['shortlist'].remove(thec)
self.buck_list.remove(thec['contact'].nodeid)
thetask['onthefly'] -= 1
if thetask['onthefly'] < 0:
thetask['onthefly'] = 0
found = False
for c in thetask['shortlist']:
if c['status'] == 'init':
found = True
if thetask['onthefly'] < self.alpha:
c['status'] = 'sent'
self.FindValue(c['contact'], thetask['kw'],
thetask['rtype'],
self.FindValueCallback,
taskseq=taskseq)
thetask['onthefly'] += 1
elif c['status'] != 'answered' and c['status'] \
!= 'answered-file':
found = True
if found == False: # lookup stops
del self.task_list[taskseq]
thetask['defer'].callback({
'context': thetask['callback_context'],
'rlist': thetask['rlist'],
'shortlist': thetask['shortlist'],
'result': False,
'kw': thetask['kw'],
})
del self.req_list[r['seq']]
except Exception, inst:
# otherwise the exception won't get print out
self.logger.error('FindValueCallback:'+traceback.format_exc())
self.logger.error('FindValueCallback: catched exception: '
+ str(inst))
def FindValueReply(self):
"""Scan FindValueReplyQ periodically and send FindValue-Reply
return up to k closet contacts or resource info.
"""
newreqlist=[]
for i in range(50):
try:
(kw, rtype, src_node, rseq,ctime) = self.FindValueReplyQ.get(False)
newreqlist.append((kw, rtype, src_node, rseq,ctime))
except Queue.Empty:
break
if len(newreqlist) == 0: return
for (kw, rtype, src_node, rseq,ctime) in newreqlist:
if time.time()-ctime>self.send_interval*self.max_resend:
with self.FindValueReplyQ.mutex:
self.FindValueReplyQ.queue.clear()
self.logger.debug("FindValueReply: FindValueReplyQ cleared")
return #clear the queue and return
attrs = ''
rrlist = self.rlist.get_res_list(kw, rtype)
if rrlist != False: # if kw is found locally, return resource list
for res in rrlist:
if res.type == rtype or rtype == 0:
self.logger.debug("FindValueReply: The owner is "+res.owner_id)
attrs += self.gen_res_attr(res.rid, res.owner_id, res.type,
res.data, res.rloc, res.meta_list)
# always return k cloest contacks
kw = kw.encode('utf-8')
m = hashlib.sha1()
m.update(kw)
t_nodeid = longbin.LongBin(m.digest())
c_list = self.buck_list.get_closest_list(t_nodeid)
for c in c_list:
attrs += self.gen_attr(4, str(c))
(header, seq) = self.gen_header(7, self.knode.nodeid.val,
src_node.nodeid.val, rseq)
packet = self.gen_packet(header, attrs)
self.sendDatagram(src_node.v4addr, src_node.port, packet)
def FindValue(
self,
dst_node,
fkw,
res_type,
findvaluecallback,
iseq=None,
taskseq=None,
):
"""FindValue RPC, this is primitive operation, not an iterative one.
dst_node is knode that being contacted
fkw is a key word is being looked for
rtype is the resource type
res_type is resource type, int
"""
(header, seq) = self.gen_header(6, self.knode.nodeid.val,
dst_node.nodeid.val, iseq)
attrs = ''
## kw = AnyToUnicode(fkw)
## kw = kw.encode('utf-8')
kw = fkw
attrs += self.gen_attr(1, kw)
attrs += self.gen_attr(7, res_type)
packet = self.gen_packet(header, attrs)
if not seq in self.req_list: # if this is a new request
self.logger.debug('Initiate a new FindValue...')
d = defer.Deferred()
d.addErrback(self.ErrCallback)
d.addCallback(findvaluecallback) # you might want to change this
self.sendDatagram(dst_node.v4addr, dst_node.port, packet)
callid = reactor.callLater(
self.send_interval,
self.FindValue,
dst_node,
fkw,
res_type,
findvaluecallback,
seq,
)
self.req_list[seq] = {
'code': 6,
'callid': callid,
'defer': d,
'send_time': 0,
'dst_node': dst_node,
'fkw': fkw,
'taskseq': taskseq,
}
self.req_list[seq]['send_time'] += 1
return
else:
if self.req_list[seq]['send_time'] > self.max_resend:
# no respond, and max resend time reached
self.logger.debug('stop sending FindValue,no answer from '+dst_node.v4addr+', calling callback'
)
self.req_list[seq]['defer'].callback({'seq': seq,
'result': False, 'src_id': dst_node.nodeid.val})
else:
self.logger.debug('re-tran FindValue')
self.sendDatagram(dst_node.v4addr, dst_node.port,
packet)
self.req_list[seq]['send_time'] += 1
callid = reactor.callLater(
self.send_interval,
self.FindValue,
dst_node,
fkw,
res_type,
findvaluecallback,
seq,
)
self.req_list[seq]['callid'] = callid
def ValueLookup(
self,
fkw,
rtype,
callback_context=None,
):
"""
the purpose of ValueLook is to find resource related to keyword
This is iterative operation, NOT primitive(like FindValue)
fkw is a keyword to search
rtype is resource type
"""
self.logger.debug('init a new ValueLookup')
kw = AnyToUnicode(fkw)
kw = kw.encode('utf-8')
m = hashlib.sha1()
m.update(kw)
target_key = longbin.LongBin(m.digest())
cshortlist = self.buck_list.get_closest_list(target_key,
self.alpha)
if len(cshortlist) == 0:
# this is how you handle error in protocol, always use callback
# to clean-up, do NOT use raise exception.
#return self.FindValueCallback({'result': 'NoContact'})
self.logger.warning('ValueLookup:No Contact')
return None
for c in cshortlist: # cal the distance to the target
c.distance = c.nodeid ^ target_key
shortlist = []
for c in cshortlist:
shortlist.append({'contact': c, 'status': 'init'})
# use first seq number as the key for this task?
d = defer.Deferred()
thetask = {
'shortest': shortlist[0],
'onthefly': self.alpha,
'shortlist': shortlist,
'defer': d,
'target': target_key,
'callback_context': callback_context,
'rlist': [],
'kw': fkw,
'rtype': rtype,
}
task_seq = self.getSeq()
self.task_list[task_seq] = thetask
#print "valuelookup,len:",len(shortlist)
for c in shortlist:
c['status'] = 'sent'
self.logger.debug("ValueLookup: Send FindValue to "+c['contact'].v4addr)
## print "DDDD valuelookup ", type(fkw)
self.FindValue(c['contact'], fkw, rtype,
self.FindValueCallback, taskseq=task_seq)
return d # return deferred, use addCallback() to add functions, this defered used to add different function for different purposes like publish,search ..etc.
def Store(
self,
kw_list,
res_list,
dst_node,
storecallback,
iseq=None,
):
"""
store keywork list on dst_node
kw_list is a list of keyword,should be utf-8 encoded str
res_list is a list of KADRes
dst_node is KAD
"""
self.logger.debug('Sending a Store request to ' + dst_node.v4addr)
(header, seq) = self.gen_header(2, self.knode.nodeid.val,
dst_node.nodeid.val, iseq)
attrs = ''
for kw in kw_list:
attrs += self.gen_attr(1, kw)
for res in res_list:
if res.owner_id == 'SELF':
owner_id = self.knode.nodeid.val
else:
owner_id = res.owner_id
attrs += self.gen_res_attr(res.rid,owner_id, res.type,
res.data, res.rloc, res.meta_list)
packet = self.gen_packet(header, attrs)
if not seq in self.req_list: # if this is a new request
d = defer.Deferred()
d.addCallback(storecallback) # you might want to change this
self.sendDatagram(dst_node.v4addr, dst_node.port, packet)
callid = reactor.callLater(
self.send_interval,
self.Store,
kw_list,
res_list,
dst_node,
storecallback,
seq,
)
self.req_list[seq] = {
'code': 2,
'callid': callid,
'defer': d,
'send_time': 0,
'dst_node': dst_node,
}
self.req_list[seq]['send_time'] += 1
return
else:
if self.req_list[seq]['send_time'] > self.max_resend:
# no respond, and max resend time reached
self.logger.debug('stop resending Store, calling callback...'
)
self.req_list[seq]['defer'].callback({'seq': seq,
'result': False}) # change this,
else:
self.sendDatagram(dst_node.v4addr, dst_node.port,
packet)
self.logger.debug('re-tran Store...')
self.req_list[seq]['send_time'] += 1
callid = reactor.callLater(
self.send_interval,
self.Store,
kw_list,
res_list,
dst_node,
storecallback,
seq,
)
self.req_list[seq]['callid'] = callid
def StoreReply(self):
"""Scan StoreReplyQ periodically and send Store-Reply
"""
newreqlist=[]
for i in range(50):
try:
(kw_list, res_list, src_node, rseq) = self.StoreReplyQ.get(False)
newreqlist.append((kw_list, res_list, src_node, rseq))
except Queue.Empty:
break
if len(newreqlist) == 0: return
# {'rid':20byte str,'rtype':int,'rdata':unicode,'rloc':unicode,'meta_list':dict of unicode}
for (kw_list, res_list, src_node, rseq) in newreqlist:
newlist = []
for res in res_list:
if u'//SELF/' in res['rloc'] or u'//SELF:' in res['rloc']:
rloc = res['rloc'].replace('SELF', src_node.v4addr, 1)
else:
rloc = res['rloc']
kres = KADRes(longbin.LongBin(res['rid']), res['rdata'], res['rtype'], rloc,
res['meta_list'],res['owner_id'])
newlist.append(kres)
for k in kw_list:
self.rlist.add_res(k, newlist, src_node.nodeid.val)
attrs = self.gen_attr(0, None)
(header, seq) = self.gen_header(3, self.knode.nodeid.val,
src_node.nodeid.val, rseq)
packet = self.gen_packet(header, attrs)
self.sendDatagram(src_node.v4addr, src_node.port, packet)
self.logger.debug('StoreReply: stored one')
def StoreCallback(self, r):
self.logger.debug('Entering storecallback')
if r['seq'] in self.req_list:
if r['result'] == False: # if timeout
self.logger.warning('store failed, dst_node no answer')
elif r['result'] == True:
self.logger.debug('store succeed')
del self.req_list[r['seq']]
def Publishcallback(self, r):
self.logger.debug('Entering Publishcallback')
shortlist = r['shortlist']
context = r['context']
if len(shortlist) == 0: # no contacts has been found
# send a signal to wx application here
self.logger.warning('publishcallback: no contact in shortlist!')
return False
else:
# res_list is a list of dict: {res_id: res_type,res_data,meta_list}
# {'rid':20byte str,'rtype':int,'rdata':unicode,'rloc':unicode,'meta_list':dict of unicode}
kres = context['res']
for cc in shortlist:
self.logger.debug('publishcallback: store ' + context['kw']
+ ' to ' + cc['contact'].nodeid.val)
self.Store([context['kw']], [kres], cc['contact'],
self.StoreCallback)
self.rlist.setPubed(kres)
def PublishRes(self,kw_list,res,check_pubed=False):
"""
pulish function for all type of resource
res is KADRes
kw is a unicode
check_pubed is a boolean to control if system should check the res is already published
"""
if self.rlist.isPubed(res)==True and check_pubed==True:
self.logger.debug('PublishRes:res already in local list')
return
self.logger.debug('PublishRes:start a new publish')
## self.logger.debug('PublishRes:kw_list is '+str(kw_list))
## print "kw_list is ",kw_list
for kw in kw_list:
self.logger.debug('PublishRes: Got- ' + kw.encode('utf-8'))
self.rlist.add_res(kw,[res,],self.knode.nodeid.val)#add it into local rlist
m = hashlib.sha1()
kw = kw.encode('utf-8')
m.update(kw)
target = m.digest()
target = longbin.LongBin(target)
callback_context = {'res': res, 'kw': kw, 'rtype': 1} # both are utf-8 encoded
d = self.NodeLookup(target, callback_context)
if d != None:
d.addCallback(self.Publishcallback)
## def Publish_kfile(self, kfile):
## #
## # don't use this method, it is outdated, use PublishRes instead
## #
## """
## publish a new filename
## kfile is KADFile
## """
##
##
## fname = os.path.splitext(kfile.name)[0]
## fname = fname.encode('utf-8')
## kw_list = mmseg.Algorithm(fname)
## klist = []
## for tok in kw_list:
## klist.append(tok.text)
## klist.append(fname)
## url = u'http://SELF:' + unicode(self.listening_port) \
## + u'/' + kfile.name # this could be other type of transportation like ftp
##
## kres = KADRes(kfile.id,kfile.name,1,url,{'size':kfile.size},self.knode.nodeid.val)
## newklist = []
## for tok in klist:
## kw = tok.decode('utf-8')
## newklist.append(kw)
## #self.rlist.add_res(kw,[kres,],self.knode.nodeid.val)#add it into local rlist
##
## self.PublishRes(newklist,kres)
def Searchcallback(self, r):
"""
Searchcallback func
"""
try:
self.logger.debug('Entering Searchcallback')
kw = r['kw']
shortlist = r['shortlist']
kw = AnyToUnicode(kw)
rlist = r['rlist']
context = r['context']
if not context['search_task_seq'] in self.task_list:
return
thetask = self.task_list[context['search_task_seq']]
for r in rlist:
if not r in thetask['rlist']:
thetask['rlist'].append(r)
# if the closest node did NOT return file, then we store kw on it.
if len(shortlist)>0:
if shortlist[0]['status'] != 'answered-file' and rlist != []:
krlist=[]
for r in thetask['rlist']:
krlist.append(KADRes(longbin.LongBin(r['rid']),r['rdata'],r['rtype'],r['rloc'],r['meta_list'],r['owner_id']))
self.Store([kw], krlist, shortlist[0]['contact'],
self.StoreCallback)
thetask['todo_list'].remove(kw)
if thetask['todo_list'] == []: # search stops
self.logger.debug('Searchcallback:Search Stops')
# following is test code
self.logger.debug("Searchcallback: following are the results:")
for r in thetask['rlist']:
self.logger.debug(str(r))
# end of test code
## if thetask['cserver'] != None:
try:
rrs=base64.b16encode(cPickle.dumps(thetask['rlist']))
#thetask['cserver'].report(thetask['rlist'])
thetask['cserver'].report(rrs)
except Exception, inst:
self.logger.error('SearchCallback:'+traceback.format_exc())
self.logger.error('SearchCallback: catched exception: '
+ str(inst))
del self.task_list[context['search_task_seq']]
except Exception, inst:
# otherwise the exception won't get print out
self.logger.error('searchCallback:'+traceback.format_exc())
self.logger.error('SearchCallback: catched exception: '
+ str(inst))
## print Exception.message
if len(rlist) == 0: # no contacts has been found
# send a signal to wx application here
self.logger.warning('Searchcallback: no resource found')
try:
thetask['cserver'].report(base64.b16encode(cPickle.dumps([])))
except Exception, inst:
self.logger.error('SearchCallback:'+traceback.format_exc())
self.logger.error('SearchCallback: catched exception: '
+ str(inst))
return False
def MaintainContactList(self):
"""
go through all buckets, for 1st buckets that have NOT been lookup
tRefresh time, do a NodeLookup with a random key in the bucket range.
"""
nid_prefix = self.buck_list.get1stIB()
if nid_prefix == None:
self.logger.debug("MaintainContactList: No Idle bucket found")
return
self.logger.debug("MaintainContactList: nid_prefix is "+nid_prefix)
nlen = len(nid_prefix)
while nlen < 160:
nid_prefix+=random.choice(['0','1'])
nlen+=1
target_key = self.knode.nodeid ^ longbin.LongBin(binstr=nid_prefix)
self.logger.debug("MaintainContactList:looking for "+str(target_key))
self.NodeLookup(target_key)
def MaintainRes(self):
"""
Maintain resource list:
- remove expired res
"""
self.logger.debug('MaintainRes: cleaning expired res')
self.rlist.remove_expired_res()
def Search(self, kw_list, rtype, cserver=None):
"""search a list of keywords with a resource type
kw_list is list of keyword to be searched, must be unicode
rtype is the resource type to be searched
cserver is the url of xmlrpc callbacksvr to report search results ,a
non-None value will override self.cserver
"""
if kw_list == None or len(kw_list)==0: return
for k in kw_list:
if not isinstance(k,unicode):
## print "Search:"+k+" is not unicode"
self.logger.warning("Search:"+k+" is not unicode")
return
#fkw_list.append(AnyToUnicode(k))
cxmlsvr = None
if cserver != None:
try:
cxmlsvr = xmlrpclib.Server(cserver)
except:
cxmlsvr = None
else:
cxmlsvr = self.cserver
thetask = {'kw_list': kw_list, 'todo_list': kw_list,
'rlist': [],'cserver':cxmlsvr}
task_seq = self.getSeq()
self.task_list[task_seq] = thetask
callback_context = {'search_task_seq': task_seq}
for kw in kw_list:
d = self.ValueLookup(kw, rtype, callback_context)
if d != None:
d.addCallback(self.Searchcallback)
else:
cxmlsvr.report(base64.b16encode(cPickle.dumps('NoContact')))
def PingCallback(self, r):
self.logger.debug('Entering pingcallback')
if r['seq'] in self.task_list:
if self.task_list[r['seq']]['task'] == 0:
if r['result'] == False: # if timeout
self.logger.debug('adding new contact')
obj = self.task_list[r['seq']]['object']
obj['bucket'].__delitem__(0)
obj['bucket'].append(obj['node'])
obj['bucket'].sort(key=attrgetter('distance'))
self.numofcontact += 1
elif r['result'] == True:
self.logger.debug('New Contact Ignored')
pass # ignore the new contact
del self.task_list[r['seq']]
del self.req_list[r['seq']]
def PingReply(self, dst_node, iseq):
self.logger.debug('sending ping-reply')
(header, seq) = self.gen_header(1, self.knode.nodeid.val,
dst_node.nodeid.val, iseq)
packet = self.gen_packet(header)
self.sendDatagram(dst_node.v4addr, dst_node.port, packet)
def Ping(
self,
dst_node,
pingcallback,
iseq=None,
):
self.logger.debug('Entering Ping')
(header, seq) = self.gen_header(0, self.knode.nodeid.val,
dst_node.nodeid.val, iseq)
packet = self.gen_packet(header)
if not seq in self.req_list: # if this is a new request
d = defer.Deferred()
d.addCallback(pingcallback) # you might want to change this
self.sendDatagram(dst_node.v4addr, dst_node.port, packet)
callid = reactor.callLater(self.send_interval, self.Ping,
dst_node, pingcallback, seq)
self.req_list[seq] = {
'code': 0,
'callid': callid,
'defer': d,
'send_time': 0,
'dst_node': dst_node,
}
self.req_list[seq]['send_time'] += 1
return
else:
if self.req_list[seq]['send_time'] > self.max_resend:
# no respond, and max resend time reached
self.logger.debug('stop resending ping, calling callback...'
)
self.req_list[seq]['defer'].callback({'seq': seq,
'result': False}) # change this,
else:
self.sendDatagram(dst_node.v4addr, dst_node.port,
packet)
self.logger.debug('re-tran ping...')
self.req_list[seq]['send_time'] += 1
callid = reactor.callLater(self.send_interval,
self.Ping, dst_node, pingcallback, seq)
self.req_list[seq]['callid'] = callid
def Boot(
self,
dst_ip,
bootcallback,
iseq=None,
dst_port=KPORT,
):
"""Bootstrapping request, used to request 20 contacts from dst_ip
"""
self.logger.debug('Bootstrapping...')
(header, seq) = self.gen_header(9, self.knode.nodeid.val,
'00000000000000000000', iseq)
packet = self.gen_packet(header)
if not seq in self.req_list: # if this is a new request
d = defer.Deferred()
d.addCallback(bootcallback) # you might want to change this
self.sendDatagram(dst_ip, dst_port, packet)
callid = reactor.callLater(
self.send_interval,
self.Boot,
dst_ip,
bootcallback,
seq,
dst_port,
)
self.req_list[seq] = {
'code': 9,
'callid': callid,
'defer': d,
'send_time': 0,
'dst_ip': dst_ip,
}
self.req_list[seq]['send_time'] += 1
return
else:
if self.req_list[seq]['send_time'] > self.max_resend:
# no respond, and max resend time reached
self.logger.debug('stop resending boot, calling callback...'
)
self.req_list[seq]['defer'].callback({'seq': seq,
'result': False}) # change this,
else:
self.sendDatagram(dst_ip, dst_port, packet)
self.logger.debug('re-tran boot...')
self.req_list[seq]['send_time'] += 1
callid = reactor.callLater(
self.send_interval,
self.Boot,
dst_ip,
bootcallback,
seq,
dst_port,
)
self.req_list[seq]['callid'] = callid
def BootReply(self):
"""Bootstrapping reply, return 20 contacts
"""
newreqlist=[]
for i in range(50):
try:
(src_node, rseq, ctime) = self.BootReplyQ.get(False)
newreqlist.append((src_node, rseq, ctime))
except Queue.Empty:
break
if len(newreqlist) == 0: return
for (src_node, rseq, ctime) in newreqlist:
if time.time()-ctime>self.send_interval*self.max_resend:
with self.BootReplyQ.mutex:
self.BootReplyQ.queue.clear()
self.logger.debug("BootRely: BootReplyQ cleared ")
return #clear the queue and return
c_list = []
self.buck_list.get_list(c_list, self.k)
c_list = c_list[:self.k]
attrs = ''
for c in c_list:
attrs += self.gen_attr(4, str(c))
(header, seq) = self.gen_header(10, self.knode.nodeid.val,
src_node.nodeid.val, rseq)
packet = self.gen_packet(header, attrs)
self.sendDatagram(src_node.v4addr, src_node.port, packet)
def BootCallback(self, r):
del self.req_list[r['seq']]
if self.buck_list.count >= self.max_bootscan_answers:
try:
self.logger.debug('bootscan stopped')
self.rptlist['BootScan'].stop() # stop the bootscan task
except:
pass
else:
if r['result'] == True: # if got the reply to Boot
self.logger.debug('BootCallback:Got the answer')
if not 4 in r['attr_list']:
return
host_alist = r['attr_list'][4]
for h in host_alist:
newnode = KADNode(h['nodeid'], h['ipv4'], h['port'])
self.updateContactQ.put(newnode)
else:
# if there is no answer
self.logger.warning('BootCallback:No Answer')
def getSeq(self):
if self.packet_seq == 4294967295:
self.packet_seq = 0
else:
self.packet_seq += 1
return self.packet_seq
def getConfigDir(self):
"""
return the directory of configuration files resides in.
"""
global MYOS
if self.conf_dir == None:
if MYOS == 'Windows':
return os.environ['APPDATA']
elif MYOS == 'Linux' or MYOS == 'Darwin':
cdir = os.environ['HOME']+'/.kadp/'
else:
return False
else:
cdir = self.conf_dir
if not os.path.isdir(cdir):
os.mkdir(cdir,0755)
self.conf_dir = cdir
return cdir
## def saveConfig(self):
## """
## Save configuration
## """
## config = MyConfig()
## config.add_section('settings')
## config.set('settings','nodeid',str(self.knode.nodeid))
## config.set('settings','lport',str(self.listening_port))
## try:
## config_file = open(self.getConfigDir()+os.sep+"kadp.ini","w")
## config.write(config_file)
## config_file.close()
## return True
## except:
## return False
##
## def loadConfig(self):
## """
## Load configuration
## """
## config = MyConfig()
## try:
## fp = open(self.getConfigDir()+os.sep+"kadp.ini","r")
## config.readfp(fp)
## nodeid = longbin.LongBin(binstr=config.get('settings','nodeid'))
## self.listening_port = config.getint('settings','lport')
## self.knode = KADNode(nodeid,
## socket.gethostbyname(socket.gethostname()),
## self.listening_port)
## return True
## except:
## return False
def updateContactList(self, newc=None):
"""
if newc==None then get newknode from Q
"""
newclist=[]
if newc == None:
for i in range(50):
try:
newknode = self.updateContactQ.get(False)
newclist.append(newknode)
except Queue.Empty:
break
else:
newclist.append(newc)
if len(newclist) == 0: return
for c in newclist:
self.buck_list.insert(c)
def prefix2mask(self, prefix):
i = 2 ** prefix - 1
rs = struct.pack('I', i)
(c1, c2, c3, c4) = struct.unpack('cccc', rs)
rs = ''
for c in (c1, c2, c3, c4):
rs += str(ord(c)) + '.'
return rs[:-1]
def testcode(self): # this is test function, should be removed
"""This is used to test Nodelookup function"""
kw = u'上海'
kw = kw.encode('utf-8')
m = hashlib.sha1()
m.update(kw)
target = longbin.LongBin(m.digest())
self.NodeLookup(target)
def test4(self): # this is a test function, should be removed
"""This is used to test valueLookup"""
self.Search([u'上海'], 1)
## def test_pub(self): # this is test function, should be removed
## """This is used to test publish function"""
##
## testf = KADFile(u'上海五角场风云录.txt', 15000, '99999999999999999999')
## self.Publish_kfile(testf)
def test2(self): # this is a test function, should be removed
"""This is used to test store function"""
finfo = KADFile(u'中国北京.txt', 1500)
ff = False
for b in self.buck_list:
for node in b:
dstn = node
ff = True
break
if ff == True:
break
kw_list = []
kw_list.append(u'中国'.encode('utf-8'))
kw_list.append(u'北京'.encode('utf-8'))
self.Store(kw_list, finfo, dstn, self.StoreCallback)
def setLPort(self,lport):
"""
Set the IListeningPort, used to stop listening
"""
self.ilport=lport
def startProtocol(self):
self.transport.socket.setsockopt(socket.SOL_SOCKET,
socket.SO_REUSEADDR, 1)
self.transport.socket.setsockopt(socket.SOL_SOCKET,
socket.SO_BROADCAST, 1)
# don't use while loop, use task.LoopingCall, otherwise ctrl+c won't work
rpt_list = {}
rpt1 = task.LoopingCall(self.updateContactList)
rpt1.start(1.0)
rpt_list['updateContactList'] = rpt1
rpt2 = task.LoopingCall(self.FindNodeReply)
rpt2.start(1.0)
rpt_list['FindNodeReply'] = rpt2
rpt3 = task.LoopingCall(self.BootReply)
rpt3.start(0.8)
rpt_list['BootReply'] = rpt3
if self.force_scan == True:
rpt4 = task.LoopingCall(self.BootScan)
rpt4.start(0.02)
rpt_list['BootScan'] = rpt4
rpt5 = task.LoopingCall(self.StoreReply)
rpt5.start(1.0)
rpt_list['StoreReply'] = rpt5
rpt6 = task.LoopingCall(self.FindValueReply)
rpt6.start(1.0)
rpt_list['FindValueReply'] = rpt6
rpt7 = task.LoopingCall(self.MaintainRes)
rpt7.start(self.tClearResInterval)
rpt_list['MaintainRes'] = rpt7
rpt8 = task.LoopingCall(self.rlist.replicate)
rpt8.start(self.tReplicate)
rpt_list['ReplicateRes'] = rpt8
rpt9 = task.LoopingCall(self.rlist.republish)
rpt9.start(self.tRepublish)
rpt_list['RepublishRes'] = rpt9
rpt10 = task.LoopingCall(self.MaintainContactList)
rpt10.start(300)
rpt_list['MaintainContactList'] = rpt10
if self.force_scan == False:
if self.buck_list.loadContact() == True:
self.logger.debug('startProtocol: contact loaded sucessfully, \
No bootscan')
#self.rptlist['BootScan'].stop()
self.NodeLookup(self.knode.nodeid) #broadcast self, should enable this in production code
else:
self.logger.warning('startProtocol: load contact failed.')
if self.BootStrap() == False:
self.logger.warning("startProtocol: can not bootstrap, will\
try agin later")
rpt11 = task.LoopingCall(self.BootStrap)
rpt11.start(300)
rpt_list['BootStrap'] = rpt11
self.setTaskList(rpt_list)
#self.checkPort()
# starting test code, should be removed in production
## if self.dstnode != None:
## self.Boot(self.dstnode.v4addr, self.BootCallback)
# end of test code
def prepareStop(self):
self.logger.debug("preparing stop")
## self.saveConfig()
self.buck_list.saveContact()
self.rlist.saveRes()
self.ilport.stopListening()
def stopAll(self):
#self.prepareStop()
reactor.stop()
def stopProtocol(self):
self.prepareStop()
self.logger.debug("KADP STOPPED.")
def answerPortOpen(self,nonce=99):
"""
this function is called while receving code=11 packet
"""
if self.port_open_status==0:
if self.port_open_nonce==nonce:
self.port_open_status=1
self.logger.debug("answerPortOpen:Port is open!")
self.checkportopen_call.cancel()
else:
self.port_open_status=-1
self.logger.error("answerPortOpen:Port is NOT open!")
def checkPort(self):
"""
check if the listening port is open
"""
self.logger.debug("checkPort: i am in")
if self.port_open_status == 0:
return
self.port_open_status = 'INIT'
reactor.callLater(10,self.checkPortOpen)
self.checkportopen_call = reactor.callLater(
20,
self.answerPortOpen,
99
)
def checkPortOpen(self):
"""
supporting function for checkPort, checkPort() should be used
"""
if self.port_open_status == 0:
return
self.logger.debug("checkPortOpen:start checking port")
nonce=os.urandom(8)
cnode = {'nid':self.knode.nodeid.val,'port':self.listening_port,
'nonce':nonce
}
encodes = urllib.urlencode(cnode)
full_url = self.chkport_url + encodes
try:
clistf = urllib.urlopen(full_url)
except Exception, inst:
self.logger.error("checkPortOpen: Error opening check URL!")
return False
self.port_open_nonce=nonce
self.port_open_status=0
self.logger.debug("checkPortOpen:port check request submited")
def BootStrap(self):
"""
Get some contact from bootstrap server
"""
cnode = {'nid':self.knode.nodeid.val,'port':self.listening_port}
encodes = urllib.urlencode(cnode)
full_url = self.bstrap_url + encodes
try:
clistf = urllib.urlopen(full_url)
except Exception, inst:
self.logger.error("BootStrap: Error opening bootstrap URL!")
return False
found = False
if clistf.getcode() != 200:
self.logger.error("BootStrap: not a 200 answer")
return False
self.logger.debug("BootStrap: got following from bootstrap server:\n")
for cls in clistf:
self.logger.debug(cls)
cdict = urlparse.parse_qs(cls,strict_parsing=True)
knode = KADNode(longbin.LongBin(cdict['nid'][0]),cdict['addr'][0].strip(),int(cdict['port'][0].strip()))
self.buck_list.insert(knode)
#print "adding ", cdict['nid'][0].strip()
found = True
if found==True and self.rptlist != None and 'BootStrap' in self.rptlist:
self.rptlist['BootStrap'].stop()
return found
def BootScan(self):
if self.addrlist != []:
if self.current_ai >= len(self.addrlist):
return
caddr = self.addrlist[self.current_ai]
if self.current_ii > int(caddr[1]):
self.current_ii = 0
self.current_ai += 1
sipi = struct.unpack('>L', socket.inet_aton(caddr[0]))[0]
tipi = sipi + self.current_ii
ips = socket.inet_ntoa(struct.pack('>L', tipi))
lastn = ips.split('.')[3]
# if self.current_ii % 10000==0: print self.current_ii
if lastn != '0' and lastn != '255':
if ips != self.bip:
self.Boot(ips, self.BootCallback)
self.current_ii += 1
def sendDatagram(
self,
v4addr,
udpport,
packet,
):
"""
send a packet directly
"""
self.logger.debug('sending a packet.')
try:
self.transport.write(packet, (v4addr, udpport))
except Exception, inst:
self.logger.error('sendDatagram:'+traceback.format_exc())
self.logger.error('sendDatagram: send failed. ' + str(inst))
return
def datagramReceived(self, datagram, host):
""" Executed when a UDP packet is received:
- datagram: received udp payload; str
- host: remote host is a tuple of (addr,port); tupple
"""
self.logger.debug('Received a packet.')
## if host[0] in self.IPList.keys(): #drop packet sent from self
## return
rr = self.parse_packet(datagram)
if rr == False:
return
else:
(pheader, alist) = rr
src_node = KADNode(longbin.LongBin(pheader['src_id']), host[0],
host[1])#the src-port in the IP header is used iso listening port in the KADP header
if pheader['code'] != 11:
self.updateContactQ.put(src_node) # put dst_node into queue
if pheader['code'] == 0: # if it is ping-request
self.PingReply(src_node, pheader['seq'])
return
if pheader['code'] == 1: # if it is ping-reply
rseq = pheader['seq']
if rseq in self.req_list:
self.req_list[rseq]['callid'].cancel()
self.req_list[rseq]['defer'].callback({'seq': rseq,
'result': True})
else:
self.logger.error('unknown seq, dropped')
return
if pheader['code'] == 6: # if it is FindValue-Request
if 1 in alist and 7 in alist:
self.FindValueReplyQ.put([alist[1][0], alist[7],
src_node, pheader['seq'], time.time()]) # only use 1st keyword attr
return
if pheader['code'] == 7: # if it is FindValue-Reply
rseq = pheader['seq']
if rseq in self.req_list:
try:
self.req_list[rseq]['callid'].cancel()
if 6 in alist:
for r in alist[6]:
if u'//SELF/' in r['rloc'] or u'//SELF:' in r['rloc']:
r['rloc'] = r['rloc'].replace('SELF', src_node.v4addr, 1)
self.req_list[rseq]['defer'].callback({
'seq': rseq,
'result': True,
'attr_list': alist,
'src_id': pheader['src_id'],
})
except Exception, inst:
self.logger.error('datagramReceived:'+traceback.format_exc())
self.logger.error(str(inst))
return
if pheader['code'] == 4: # if it is FindNode-Request
#print "get FindNodeRequest from ",src_node.nodeid.val," seq ",pheader['seq']
if 3 in alist:
t_node = longbin.LongBin(alist[3][0])
self.FindNodeReplyQ.put([t_node, src_node, pheader['seq'
],time.time()])
return
if pheader['code'] == 5: # if it is FindNode-Reply
rseq = pheader['seq']
if rseq in self.req_list:
try:
self.req_list[rseq]['callid'].cancel()
self.req_list[rseq]['defer'].callback({
'seq': rseq,
'result': True,
'attr_list': alist,
'src_id': pheader['src_id'],
})
except Exception, inst:
self.logger.error('datagramReceived:'+traceback.format_exc())
self.logger.error(str(inst))
return
if pheader['code'] == 2: # if it is store
if 1 in alist and 6 in alist:
self.StoreReplyQ.put([alist[1], alist[6], src_node,
pheader['seq']])
return
if pheader['code'] == 3: # if it is Store-Reply
rseq = pheader['seq']
if rseq in self.req_list:
try:
self.req_list[rseq]['callid'].cancel()
self.req_list[rseq]['defer'].callback({
'seq': rseq,
'result': True,
'attr_list': alist,
'src_id': pheader['src_id'],
})
except Exception, inst:
self.logger.error('datagramReceived:'+traceback.format_exc())
self.logger.error(str(inst))
return
if pheader['code'] == 9: # if it is Boot
self.BootReplyQ.put([src_node, pheader['seq'], time.time()])
return
if pheader['code'] == 11: # if it is check_port_open
self.answerPortOpen(alist[8][0])
return
if pheader['code'] == 10: # if it is Boot-reply
rseq = pheader['seq']
if rseq in self.req_list:
try:
self.req_list[rseq]['callid'].cancel()
self.req_list[rseq]['defer'].callback({'seq': rseq,
'result': True, 'attr_list': alist})
except Exception, inst:
self.logger.error('datagramReceived:'+traceback.format_exc())
self.logger.error(str(inst))
else:
self.logger.error('datagramReceived:'+traceback.format_exc())
self.logger.info('unknown seq, dropped')
def gen_header(
self,
code,
src_id,
dst_id,
seq_num=None,
):
""" Generate KAD protocol header:
- code: message type; unsigned int
- src_id/dst_id: Node_ID(str) of src and dest
- payload_len: length of payload, unsigned int
return (header,seq)
"""
ver = chr(1) # protocol version is 1
if not code in self.msg_code_list:
self.logger.warning('gen_header:Invalid Code')
return False
mcode = chr(code) # msg type
flag = chr(0) # request
resvr = chr(0)
if seq_num == None:
if self.packet_seq == 4294967295:
self.packet_seq = 0
else:
self.packet_seq += 1
fseq = int(self.packet_seq)
else:
fseq = int(seq_num)
fseqs = struct.pack('I', fseq)
# print type(ver),type(mcode),type(flag),type(src_id),type(dst_id),type(fseqs)
lps = struct.pack('H', self.listening_port)
rheader = ver + mcode + flag + src_id + dst_id + lps + fseqs
return (rheader, fseq)
def gen_attr(self, atype, aval):
""" Generate a KADP attribute:
- atype: attribute type; int
- aval: attribute value; str or unicode
note: aval will be encoded as UTF-8 when atype==0
note2: struct.pack/unpack can NOT be used to pack/unpack complex combo,otherwise, unexpected '\x00' will be padded
"""
if aval != None:
if atype == 1: # if attr is keyword
## print "aval is", aval
if isinstance(aval, str):
encoding = chardet.detect(aval)['encoding']
try:
aval = aval.decode(encoding)
except:
aval = aval.decode('utf-8')
if isinstance(aval, unicode):
aval = aval.encode('utf-8')
if atype == 7:
fmts = 'HHH'
return struct.pack(fmts, atype, 2, aval)
alen = len(aval)
if atype == 0: # if attr is result
fmt_str = 'HHc'
alen = 1
aval = int(aval)
rattr = struct.pack(fmt_str, atype, alen, aval)
else:
fmt_str = 'HH' + str(alen) + 's'
rattr = struct.pack(fmt_str, atype, alen, aval)
else:
fms = 'HH'
rattr = struct.pack(fms, atype, 0)
return rattr
def gen_res_attr(
self,
res_id,
owner_id,
res_type,
res_data,
res_loc,
meta_list,
):
"""
Generate a KAD general resource attr
res_id is a 20 bytes string
owner_id is the owner's NodeID,20bytes string
res_type is a int, 1 means file_url is currently supported
res_data is a unicode or a utf-8 string
res_local is a unicode or a utf-8 string
meta_list is a dict, all string in this dict must be unicode
"""
if owner_id == 'SELF':
oid = self.knode.nodeid.val
else:
oid = owner_id
supported_types = [1]
if len(oid) != 20:
raise ValueError('owner_id must be 20 bytes str.')
if not res_type in supported_types:
raise ValueError('unsupported res_type')
attr_val = ''
types = struct.pack('H', res_type)
attr_val += res_id.val + oid + types
if isinstance(res_data, unicode):
res_data = res_data.encode('utf-8')
datalen = len(res_data)
datalens = struct.pack('H', datalen)
attr_val += datalens + res_data
if isinstance(res_loc, unicode):
res_loc = res_loc.encode('utf-8')
loclen = len(res_loc)
loclens = struct.pack('H', loclen)
attr_val += loclens + res_loc
newmlist = {}
for (k, v) in meta_list.items(): # encode all unicode into utf-8
newk=k
newv=v
if isinstance(k, unicode):
newk = urllib.quote_plus(k.encode('utf-8'))
if isinstance(v, unicode):
newv = urllib.quote_plus(v.encode('utf-8'))
newmlist[newk] = newv
## if len(newmlist.keys())>1:
## print newmlist
metas = urllib.urlencode(newmlist)
attr_val += metas
return self.gen_attr(6, attr_val)
def gen_packet(self, header, payload=''):
m = hashlib.sha1()
m.update(header + payload)
checksum = m.digest()
return header + payload + checksum[:10]
def parse_packet(self, ipacket):
""" Parse input packet, return:
- a dict store header info
- a dict store attributes
"""
plen = len(ipacket)
if plen < 59:
self.logger.warning('Invalid packet size,packet dropped')
return False
if ord(ipacket[0]) != 1:
self.logger.warning('Unsupported version,packet dropped')
return False
m = hashlib.sha1()
m.update(ipacket[:-10])
if m.digest()[:10] != ipacket[-10:]:
self.logger.warning('Invalid checksum,packet dropped')
return False
header = {}
header['ver'] = ord(ipacket[0])
header['code'] = ord(ipacket[1])
header['flag'] = ord(ipacket[2])
header['src_id'] = ipacket[3:23]
header['dst_id'] = ipacket[23:43]
header['listen_port'] = struct.unpack('H', ipacket[43:45])[0]#this could be used to detect the NAT within src node
if header['dst_id'] != self.knode.nodeid.val and header['dst_id'
] != '00000000000000000000': # if dst_id <> self.id
self.logger.warning('Invalid dst_id, packet dropped')
return False
header['seq'] = struct.unpack('I', ipacket[45:49])[0]
attr_list = {}
ats = ipacket[49:-10]
if ats != '':
attr_list = self.parse_attrs(ats)
return (header, attr_list)
def parse_attrs(self, attrs):
""" Parse recived attributes, return a dict,
- key is attribute type
- The value depends on attr type like following:
- 0: a bool
- 1 or 2: a list of unicode(by using utf-8 decode)
- 3: a binary str
- 4: a list of {'ipv4':str,'port':int,'nodeid':longbin}
- 5: a dict of {'fname':unicode,'size':int}
- 6: depends on res_type, for type 1, a list of dict of
{'rid':20byte str,'owner_id':20bytes str,
'rtype':int,'rdata':unicode,'rloc':unicode,
'meta_list':dict of unicode}
- 7: int
"""
attr_list = {}
try:
while attrs != '':
fmts = 'HH'
(atype, alen) = struct.unpack(fmts, attrs[:4])
fmts = 'HH' + str(alen) + 's'
(atype, alen, aval) = struct.unpack(fmts, attrs[:4
+ alen])
etc = True
if atype == 1 or atype == 2: # if attr is keyword or url
aval = aval.decode('utf-8')
if not atype in attr_list:
# attr_list[atype]=[[atype,alen,aval[:alen]]]
attr_list[atype] = [aval]
else:
attr_list[atype].append(aval)
etc = False
if atype == 0: # if attr is result
# attr_list[atype]=[[atype,alen,bool(aval[:alen])]]
attr_list[atype] = bool(aval)
etc = False
if atype == 4: # if attr is v4host_info
fmts = '4sH20s'
(ipbs, udpport, nodeidval) = struct.unpack(fmts,
aval)
ipv4addr = ''
for c in ipbs:
ipv4addr += str(ord(c)) + '.'
ipv4addr = ipv4addr[:-1]
contact = {'ipv4': ipv4addr, 'port': udpport,
'nodeid': longbin.LongBin(nodeidval)}
if not atype in attr_list:
# attr_list[atype]=[[atype,alen,aval[:alen]]]
attr_list[atype] = [contact]
else:
attr_list[atype].append(contact)
etc = False
if atype == 5: # if attr is fileinfo
aval = aval.decode('utf-8')
aalist = aval.split('>')
attr_list[atype] = {'fname': aalist[0],
'size': int(aalist[1])}
etc = False
if atype == 6: # if attr is general resource
rid = aval[:20]
owner_id = aval[20:40]
rtype = struct.unpack('H', aval[40:42])[0]
# varstr=aval[22:]
rdatalen = struct.unpack('H', aval[42:44])[0]
rdata = aval[44:44 + rdatalen]
rloclen = struct.unpack('H', aval[44 + rdatalen:46
+ rdatalen])[0]
rloc = aval[46 + rdatalen:46 + rdatalen + rloclen]
rmetas = aval[46 + rdatalen + rloclen:]
if rtype == 1:
rdata = rdata.decode('utf-8')
rloc = rloc.decode('utf-8')
metas_list = rmetas.split('&')
mlist = {}
for meta in metas_list:
(k, v) = meta.split('=')
k = urllib.unquote_plus(k).decode('utf-8')
v = urllib.unquote_plus(v).decode('utf-8')
mlist[k] = v
if not atype in attr_list:
attr_list[atype] = [{
'rid': rid,
'owner_id' : owner_id,
'rtype': rtype,
'rdata': rdata,
'rloc': rloc,
'meta_list': mlist,
}]
else:
attr_list[atype].append({
'rid': rid,
'owner_id' : owner_id,
'rtype': rtype,
'rdata': rdata,
'rloc': rloc,
'meta_list': mlist,
})
etc = False
if atype == 7: # if attr is resource type
attr_list[atype] = struct.unpack('H', aval)[0]
etc = False
if etc == True:
if not atype in attr_list:
# attr_list[atype]=[[atype,alen,aval[:alen]]]
attr_list[atype] = [aval[:alen]]
else:
attr_list[atype].append(aval[:alen])
attrs = attrs[4 + alen:]
except Exception, inst:
# otherwise the exception won't get print out
self.logger.error('parse_attrs:'+traceback.format_exc())
self.logger.error('parse_attrs: catched exception: '
+ str(inst))
return attr_list
class MyUDPHandler(SocketServer.BaseRequestHandler):
"""
print recved data
"""
def handle(self):
data = self.request[0]
rec = logging.makeLogRecord(cPickle.loads(data[4:]))
#socket = self.request[1]
#print "{} wrote:".format(self.client_address[0])
print "\n"+rec.asctime+" - "+rec.name+" - "+rec.levelname+" : "+rec.getMessage()
class ThreadingUDPServer(SocketServer.ThreadingMixIn, SocketServer.UDPServer):
pass
class tXMLSvr(XMLRPC):
def __init__(self, proto):
XMLRPC.__init__(self)
self.proto = proto
self.log_list = []
def addlog(self, cip):
if not cip in self.log_list:
lh = DatagramHandler(cip, 9999)
lh.setLevel(logging.DEBUG)
formatter = \
logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
lh.setFormatter(formatter)
self.proto.logger.addHandler(lh)
self.log_list.append(cip)
## rid,
## data,
## rtype=1,
## rloc=None,
## metadata={},
## owner_id='SELF',
## ctime=None
def xmlrpc_publishRes(self,kw_list,rid_val,res_data,res_rtype,res_rloc,res_metadata,res_owner):
#{'rloc': 'http://1.1.1.1/', 'meta_list': {'size': 9999}, 'type': 1, 'creation_time': 1343344275.1678779, 'rid': {'val': '10101011010000000000', 'nlen': 20}, 'data': u'\u8fd9\u662f\u4e00\u4e2a\u6d4b\u8bd5\u95ee\u955c', 'owner_id': '10101011019999999999'}
ridv=base64.b16decode(rid_val)
rid = longbin.LongBin(ridv)
newklist=[]
for k in kw_list:
k = k.strip()
if k !='':
if not isinstance(k,unicode):
newklist.append(k.decode('utf-8'))
else:
newklist.append(k)
## print "newklist is",newklist
if newklist != []:
kkres = KADRes(rid,res_data,res_rtype,res_rloc,res_metadata,res_owner)
self.proto.PublishRes(newklist,kkres,True)
return 'ok'
@withRequest
def xmlrpc_report(self, request, attrs):
"""attrs is a string represent attr name, could be a func"""
# following code is test code, use to add syslog handler to XML_RPC client
# should be removed from production.
cip = request.getClientIP()
self.addlog(cip)
# end of test code
try:
return base64.b16encode(cPickle.dumps(getattr(self.proto,
attrs), 2))
except Exception, inst:
print attrs
print inst
return base64.b16encode(cPickle.dumps('ErrOOR', 2))
@withRequest
def xmlrpc_EnableLogging(self, request):
self.proto.logger.disabled = False
cip = request.getClientIP()
self.addlog(cip)
return 'Logging enabled'
def xmlrpc_DisableLogging(self):
self.proto.logger.disabled = True
return 'Logging disabled'
def xmlrpc_testcode(self, dump):
self.proto.testcode()
return 'ok'
def xmlrpc_test2(self, dump):
self.proto.test2()
return 'ok'
## def xmlrpc_test_pub(self, dump):
## self.proto.test_pub()
## return 'ok'
def xmlrpc_test4(self, dump):
self.proto.test4()
return 'ok'
#Search(self, kw_list, rtype, cserver=None):
def xmlrpc_search(self, kw_list,cserver):
"""
kw_list is a list of utf-8 encoded keywords
"""
uklist=[]
## print "I got ",kw_list
for k in kw_list: #convert utf-8 to unicode
if isinstance(k,unicode):
uklist.append(k)
else:
uklist.append(k.decode('utf-8'))
self.proto.Search(uklist,0,cserver)
return 'ok'
def xmlrpc_savecontact(self, dump):
self.proto.saveContact()
return 'ok'
def xmlrpc_displaycontact(self, dump):
self.proto.displayContactList()
return 'ok'
def xmlrpc_stopall(self, dump):
self.proto.stopAll()
#return 'ok'
def xmlrpc_checkPort(self, dump):
## print "xml is checking port"
self.proto.checkPort()
return 'ok'
def xmlrpc_PortStatus(self, dump):
return self.proto.port_open_status
def xmlrpc_preparestop(self, dump):
self.proto.prepareStop()
def xmlrpc_publish(self, fname):
self.proto.Publish(fname)
return 'ok'
def xmlrpc_numofcontact(self, dump):
return str(self.proto.buck_list.count)
def xmlrpc_printbucklist(self, dump):
self.proto.buck_list.print_me(self.proto.buck_list.root)
return 'ok'
def xmlrpc_printreslist(self, dump):
self.proto.rlist.print_me()
return 'ok'
def xmlrpc_getbucket(self, dump):
return self.proto.buck_list.get_idle_bucket()
def xmlrpc_getinfo(self, dump):
return self.proto.getInfo()
def xmlrpc_printme(self, dump):
return self.proto.printme()
def PingCallback(self, r):
if r['result'] == False: # if timeout
print "timeout"
elif r['result'] == True:
print "Alive!"
del self.proto.req_list[r['seq']]
def xmlrpc_Ping(self,hexids,addr,port):
ID=longbin.LongBin(binstr=hexids.decode('hex_codec'))
dstnode=KADNode(ID,ip=addr,port=int(port))
self.proto.Ping(dstnode,self.PingCallback)
return "ok"
def KShell(proc_list):
"""
A debug CLI
"""
if platform.system() == 'Windows':
import pyreadline
else:
import readline
cmd = ''
print 'ctrl+c to quit'
log_list = []
while True:
cmd = raw_input('KADP_Ctrl@>')
cmd = cmd.lower()
cmd = cmd.strip()
clist = cmd.split(' ')
try:
i = int(clist[1])
except:
i = None
if i < 0 or i >= len(proc_list):
i = None
if clist[0] == 'end':
break
if clist[0] == 'd': # display log of instance x
if i != None:
proc_list[i]['debug'].EnableLogging()
log_list.append(i)
continue
if clist[0] == 'nd': # disable log of instance x
if i != None:
proc_list[i]['debug'].DisableLogging()
try:
log_list.remove(i)
except Exception, inst:
print traceback.format_exc()
print str(inst)
continue
if clist[0] == 'xd': # disable all current logging and enable log for instance x
if i != None:
for n in log_list:
proc_list[n]['debug'].DisableLogging()
proc_list[i]['debug'].EnableLogging()
log_list = [i]
continue
if clist[0] == 'lookup': # excute testcode, lookup a target
if i != None:
proc_list[i]['debug'].testcode(False)
continue
if clist[0] == 'store': # excute testcode, store some key words
if i != None:
proc_list[i]['debug'].test2(False)
continue
if clist[0] == 'pub': # excute testcode, publish a filename
if i != None:
proc_list[i]['debug'].test_pub(False)
continue
if clist[0] == 'ss': # search for '上海'
if i != None:
proc_list[i]['debug'].test4(False)
continue
if clist[0] == 'search': # excute testcode, search a kw
if len(clist) >= 3:
kw = clist[2].decode('utf-8')
else:
print 'search <id> <kw>'
continue
if i != None:
proc_list[i]['debug'].search(kw)
continue
if clist[0] == 'save': # save contacts
for p in proc_list:
p['debug'].savecontact(False)
continue
if clist[0] == 'stop': # stop all process
for p in proc_list:
try:
p['debug'].stopall(False)
except:
pass
continue
if clist[0] == 'nc': # display number of contacts
if i != None:
print proc_list[i]['debug'].numofcontact(False)
continue
if clist[0] == 'pc': # print bucket tree
if i != None:
proc_list[i]['debug'].printbucklist(False)
continue
if clist[0] == 'printme': # print bucket tree
if i != None:
print proc_list[i]['debug'].printme(False)
continue
if clist[0] == 'pr': # print res list
if i != None:
proc_list[i]['debug'].printreslist(False)
continue
if clist[0] == 'p': # publish a keyword
if i != None:
print 'clist is', clist[2]
proc_list[i]['debug'].publish(clist[2])
continue
if clist[0] == 'ping': # publish a keyword
if i != None:
proc_list[i]['debug'].Ping(clist[2],clist[3],clist[4])
continue
if clist[0] == 'gb': # get 1st idle bucket
if i != None:
print proc_list[i]['debug'].getbucket(False)
continue
if clist[0] == 'savef': # save test setup into file
try:
fname = clist[1]
except:
print 'usage:savef filename'
continue
print 'save setup in ' + fname
newf = open(fname, 'wb')
for p in proc_list:
newf.write(p['ip'] + '\n')
newf.close()
continue
if clist[0] == 'e': # excute debug command on instance x
if i != None:
robj = \
cPickle.loads(base64.b16decode(proc_list[i]['debug'
].report(clist[2])))
if len(clist) > 3:
ac = clist[3].replace(clist[2], 'robj')
try:
print eval(ac)
except Exception, inst:
print inst
else:
print robj
else:
print ' iam false'
continue
if len(proc_list)>1 or proc_list[0]['process'] != None:
print 'killing instances...'
for p in proc_list:
os.kill(p['process'].pid, signal.SIGKILL)
def LoadAddr(addrf):
addrlist = []
if addrf != None:
inf = open(addrf, 'r')
for a in inf:
a = a.strip()
addrlist.append(a.split())
inf.close()
return addrlist
##
##def debugCLI(xmlSvrList):
## """
## This provides a debug CLI
## xmlSvrList is a list of XML RPC server
## """
## pass
if __name__ == '__main__':
if len(sys.argv) >= 2:
if sys.argv[1].lower() == '-server' or sys.argv[1].lower() == '-product':
## print 'starting KADP...'
lport = KPORT
nodeid = None
bip = ''
if sys.argv[1].lower() == '-product':
bip = ''
mynodeid = None
#lport = KPORT
conf_dir = None
cserver = None
try:
lport = int(sys.argv[2])
except:
lport=KPORT
if sys.argv[3] == 'NONE':
mynodeid = None
else:
mynodeid = longbin.LongBin(binstr=sys.argv[3])
try:
fscan = bool(int(sys.argv[4]))
except:
fscan = False
try:
nodebug = bool(int(sys.argv[5]))
except:
nodebug = False
try:
cserver = sys.argv[6]
except:
cserver = None
# following are test code
else:
if sys.argv[2]=='NONE':
bip = ''
else:
bip = sys.argv[2]
if sys.argv[4]=='NONE':
myid=None
else:
myid = sys.argv[4]
lport = int(sys.argv[3])
if sys.argv[5]=='NONE':
conf_dir=None
else:
conf_dir = sys.argv[5]
mynodeid = longbin.LongBin(myid)
try:
fscan = bool(int(sys.argv[6]))
except:
fscan = False
try:
cserver = sys.argv[7]
except:
cserver = None
nodebug = True
# end of test code
protocol = KADProtocol(None, lport, mynodeid, 'mainlist.txt'
, bip=bip,conf_dir=conf_dir,force_scan=fscan,
cserver_url=cserver,nodebug=nodebug)
# bind protocol to reactor
t = reactor.listenUDP(protocol.listening_port, protocol,
interface=bip)
protocol.setLPort(t)
# reactor.callInThread(protocol.updateContactList)
# reactor.callInThread(protocol.BootScan)
# create XML interface for debug
# Have to use twisted.web.xmlrpc module, otherwise ctrl+c won't work
txmlsvr = tXMLSvr(protocol)
if bip == '':
reactor.listenTCP(KCPORT, TW_xmlserver.Site(txmlsvr),
interface="127.0.0.1")
else: #listen on loopback int
reactor.listenTCP(KCPORT, TW_xmlserver.Site(txmlsvr),
interface=bip)
reactor.run()
#print 'stopped'
sys.exit(0)
elif sys.argv[1].lower() == '-debug':
# this is a debug shell via XML-RPC
# shell command format is 'attr-name(of KADProtocol) expression'
# for example, "buck_list len(buck_list)" to return len of buck_list
# command "end" to quit
#start UDP server @ port 9999
HOST, PORT = "localhost", 9999
server = ThreadingUDPServer((HOST, PORT), MyUDPHandler)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()
print "log listener started."
if len(sys.argv) <= 2:
dst_host = '127.0.0.1'
dst_port = KCPORT
else:
# use argv[2] as the XML-RPC server's domain name(or IP)
dst_host = sys.argv[2]
dst_port = int(sys.argv[3])
s = xmlrpclib.Server('http://' + dst_host + ':'
+ str(dst_port))
proc_list = []
instance = {'process': None, 'debug': s, 'ip': dst_host}
print instance
proc_list.append(instance)
KShell(proc_list)
server.shutdown()
print 'Quit from ' + dst_host + '.'
elif sys.argv[1].lower() == '-test':#this is for testing&debug purpose
if MYOS != 'Linux' or (MYOS=='Linux' and os.geteuid() != 0):
print "Testing function only works under Linux as root"
sys.exit(1)
print "Testing start at ",time.asctime()
# start mulitple instances
import signal
import sys
def signal_handler(signal, frame):
global protocol
print 'You pressed Ctrl+C!'
protocol.run_bootscan = False
signal.signal(signal.SIGINT, signal_handler)
start_port = KPORT
lport = start_port
start_id = 11110111100000000000
proc_list = []
if len(sys.argv) >= 3:
try:
inumber = int(sys.argv[2])
fscan = sys.argv[3]
except:
fname = sys.argv[2]
#instance_count = int(sys.argv[3])
inumber = False
fscan = '0'
else:
inumber = 10
fscan = '0'
if inumber != False:
addrlist = LoadAddr('mainlist.txt')
addr = addrlist[0] # only use first block to speeds up bootstrapping
blocksize = int(addr[1])
start_addr = addr[0]
sipi = struct.unpack('>L',
socket.inet_aton(start_addr))[0]
stepsize = blocksize / inumber
for i in range(inumber):
tip = '0.0.0.0'
while tip.split('.')[3] == '0' or tip.split('.')[3] \
== '255':
delta = random.randint(stepsize * i + 1,
stepsize * (i + 1))
# delta=random.randint(1,100)
tipi = sipi + delta
tip = socket.inet_ntoa(struct.pack('>L', tipi))
cmd = ['ifconfig', 'eth0:' + str(i), tip + '/30']
# cmd="ifconfig eth0:"+str(i)+" "+tip+"/32"
print cmd
subprocess.call(cmd)
# lport=start_port+i
myid = '{0:020d}'.format(i * 100 + start_id)
cmd = [
'/usr/bin/python',
'KADP.py',
'-server',
tip,
str(lport),
myid,
os.environ['HOME']+"/kconf-"+str(i),
fscan,
]
# cmd="/usr/bin/python KADP.py -server "+tip+" "+str(lport)+" "+myid
print cmd
# p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT)
s = xmlrpclib.Server('http://' + tip + ':'
+ str(KCPORT))
instance = {'process': p, 'debug': s, 'ip': tip}
proc_list.append(instance)
print 'forked ' + str(inumber) + ' KADP instances.'
else:# load a config file
newf = open(fname, 'r')
i = 0
for tip in newf:
#if i > instance_count: break
tip = tip[:-1]
cmd = ['ifconfig', 'eth0:' + str(i), tip + '/30']
# cmd="ifconfig eth0:"+str(i)+" "+tip+"/32"
print cmd
subprocess.call(cmd)
# lport=start_port+i
myid = '{0:020d}'.format(i * 100 + start_id)
cmd = [
'/usr/bin/xterm',
'-xrm',
"'XTerm*VT100.translations: #override <Btn1Up>: select-end(PRIMARY, CLIPBOARD, CUT_BUFFER0)'",
'-hold',
'-T',
myid,
'-e',
'/usr/bin/python',
'KADP.py',
'-server',
tip,
str(lport),
myid,
os.environ['HOME']+"/kconf-"+str(i),
'0',
]
# cmd="/usr/bin/python KADP.py -server "+tip+" "+str(lport)+" "+myid
print cmd
# p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT)
s = xmlrpclib.Server('http://' + tip + ':'
+ str(KCPORT))
instance = {'process': p, 'debug': s, 'ip': tip}
proc_list.append(instance)
i += 1
print 'forked ' + str(i) + ' instances from ' + fname
KShell(proc_list)
print 'Done.'
else:
print 'KADP, a Kademlia based P2P protcol in python.'
print 'Usage:'
print ' -server [bip lport nodeid(20byte str) conf_dir] [force_scan] [cserver_url]'
print ' -product [lport nodeid(160byte str) force_scan [nodebug] [cserver_url]]'
print ' -debug [SVR-hostname port]'
print ' -test [{numberofinstances [forcescan]|conf_file_name}]'
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,248
|
hujun-open/litebook
|
refs/heads/master
|
/plugin/www.ranwen.net.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#-------------------------------------------------------------------------------
# Name: litebook plugin for www.ranwen.net
# Purpose:
#
# Author:
#
# Created: 02/01/2013
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import platform
import sys
MYOS = platform.system()
osarch=platform.architecture()
if osarch[1]=='ELF' and MYOS == 'Linux':
sys.path.append('..')
if osarch[0]=='64bit':
from lxml_linux_64 import html
elif osarch[0]=='32bit':
# from lxml_linux import etree
from lxml_linux import html
elif MYOS == 'Darwin':
from lxml_osx import html
else:
from lxml import html
#import lxml.html
import urlparse
import urllib2
import time
import re
import wx
import thread
import threading
import htmlentitydefs
import urllib
import Queue
from datetime import datetime
Description=u"""支持的网站: http://www.ranwen.net/
插件版本:2.1
发布时间: 2013-08-4
简介:
- 支持多线程下载
- 关键字不能为空
- 支持HTTP代理
- 支持流看
作者:litebook.author@gmail.com
"""
SearchURL='http://www.ranwen.net/modules/article/search.php'
def myopen(url,post_data=None,useproxy=False,proxyserver='',proxyport=0,proxyuser='',proxypass=''):
interval=10 #number of seconds to wait after fail download attampt
max_retries=3 #max number of retry
retry=0
finished=False
if useproxy:
proxy_info = {
'user' : proxyuser,
'pass' : proxypass,
'host' : proxyserver,
'port' : proxyport
}
proxy_support = urllib2.ProxyHandler({"http" : \
"http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info})
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
if post_data<>None:
myrequest=urllib2.Request(url,post_data)
else:
myrequest=urllib2.Request(url)
#spoof user-agent as IE8 on win7
myrequest.add_header("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)")
while retry<max_retries and finished==False:
try:
fp=urllib2.urlopen(myrequest)
finished=True
except:
retry+=1
time.sleep(interval)
if finished==False:
return None
else:
try:
return fp.read()
except:
return None
def htmname2uni(htm):
if htm[1]=='#':
try:
uc=unichr(int(htm[2:-1]))
return uc
except:
return htm
else:
try:
uc=unichr(htmlentitydefs.name2codepoint[htm[1:-1]])
return uc
except:
return htm
def htm2txt(inf):
""" extract the text context"""
doc=html.document_fromstring(inf)
#content=doc.xpath('//*[@id="bgdiv"]/table[2]/tbody/tr[1]/td/table/tbody/tr')
content=doc.xpath('//*[@id="content"]')
htmls=html.tostring(content[0],False)
htmls=htmls.replace('<br>','\n')
htmls=htmls.replace('<p>','\n')
htmls=htmls.replace(' ',' ')
p=re.compile('\n{2,}') #replace more than 2 newlines in a row into one newline
htmls=p.sub('\n',htmls)
newdoc=html.document_fromstring(htmls)
return newdoc.text_content()
class NewDThread:
def __init__(self,Q,useproxy=False,proxyserver='',proxyport=0,proxyuser='',proxypass='',tr=[],cv=None):
self.Q=Q
self.proxyserver=proxyserver
self.proxyport=proxyport
self.proxyuser=proxyuser
self.proxypass=proxypass
self.useproxy=useproxy
self.tr=tr
self.cv=cv
thread.start_new_thread(self.run, ())
def run(self):
while True:
try:
task=self.Q.get(False)
except:
return
self.cv.acquire()
self.tr[task['index']]=htm2txt(myopen(task['url'],post_data=None,
useproxy=self.useproxy,
proxyserver=self.proxyserver,proxyport=self.proxyport,
proxyuser=self.proxyuser,proxypass=self.proxypass))
self.cv.release()
self.Q.task_done()
def get_search_result(url,key,useproxy=False,proxyserver='',proxyport=0,proxyuser='',proxypass=''):
#get search result web from url by using key as the keyword
#this only apply for POST
#return None when fetch fails
if useproxy:
proxy_info = {
'user' : proxyuser,
'pass' : proxypass,
'host' : proxyserver,
'port' : proxyport # or 8080 or whatever
}
proxy_support = urllib2.ProxyHandler({"http" : \
"http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info})
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)
# install it
urllib2.install_opener(opener)
if isinstance(key,unicode):
key=key.encode("GBK")
post_data=urllib.urlencode({u"searchkey":key,u'searchType':'articlename'})
myrequest=urllib2.Request(url,post_data)
#spoof user-agent as IE8 on win7
myrequest.add_header("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)")
try:
rr=urllib2.urlopen(myrequest,timeout=10)
return rr.read()
except Exception as inst:
return None
def GetSearchResults(key,useproxy=False,proxyserver='',proxyport=0,proxyuser='',proxypass=''):
global SearchURL
if key.strip()=='':return []
rlist=[]
page=get_search_result(SearchURL,key,useproxy,proxyserver,proxyport,proxyuser,proxypass)
if page==None:
return None
doc=html.document_fromstring(page)
rtable=doc.xpath('//*[@id="searchhight"]/table') #get the main table, you could use chrome inspect element to get the xpath
if len(rtable)!=0:
row_list=rtable[0].findall('tr') #get the row list
row_list=row_list[1:] #remove first row of caption
for row in row_list:
r={}
col_list = row.getchildren() #get col list in each row
r['bookname']=col_list[0].xpath('a')[0].text
r['book_index_url']=col_list[1].xpath('a')[0].get('href')
r['authorname']=col_list[2].xpath('a')[0].text
r['booksize']=col_list[3].text
r['lastupdatetime']=col_list[4].text
r['bookstatus']=col_list[5].xpath('font')[0].text
for k in r.keys():
if r[k]==None:r[k]=''
rlist.append(r)
return rlist
else:#means the search result is a direct hit, the result page is the book portal page
#rtable=doc.xpath('//*[@id="content"]/div[2]/div[2]/table')
r={}
try:
r['bookname']=doc.xpath('//*[@id="content"]/div[2]/div[2]/table/tr/td/table/tbody/tr[1]/td/table/tr[1]/td/h1')[0].text
r['bookstatus']=doc.xpath('//*[@id="content"]/div[2]/div[2]/table/tr/td/table/tbody/tr[1]/td/table/tr[2]/td[2]/table/tr[1]/td[4]')[0].text
r['lastupdatetime']=doc.xpath('//*[@id="content"]/div[2]/div[2]/table/tr/td/table/tbody/tr[1]/td/table/tr[2]/td[2]/table/tr[1]/td[6]')[0].text
r['authorname']=doc.xpath('//*[@id="content"]/div[2]/div[2]/table/tr/td/table/tbody/tr[1]/td/table/tr[2]/td[2]/table/tr[2]/td[6]/a/b')[0].text
r['book_index_url']=doc.xpath('//*[@id="content"]/div[2]/div[2]/table/tr/td/table/tbody/tr[1]/td/table/tr[2]/td[2]/table/tr[4]/td/div/b/a[1]')[0].get('href')
r['booksize']=''
except:
return []
## for k,v in r.items():
## print k,v
for k in r.keys():
if r[k]==None:r[k]=''
return [r]
return []
def GetBook(url,bkname='',win=None,evt=None,useproxy=False,proxyserver='',
proxyport=0,proxyuser='',proxypass='',concurrent=10,
mode='new',last_chapter_count=0,dmode='down',sevt=None,control=[]):
"""
mode is either 'new' or 'update', default is 'new', update is used to
retrie the updated part
dmode is either 'down' or 'stream'
sevt is the event for stream
if control != [] then download will stop (because list is mutable type, boolean is not)
"""
bb=''
cv=threading.Lock()
if useproxy:
proxy_info = {
'user' : proxyuser,
'pass' : proxypass,
'host' : proxyserver,
'port' : proxyport
}
proxy_support = urllib2.ProxyHandler({"http" : \
"http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info})
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
try:
up=urllib2.urlopen(url)
except:
return None,{'index_url':url}
fs=up.read()
up.close()
doc=html.document_fromstring(fs)
r=doc.xpath('//*[@id="defaulthtml4"]/table') #get the main table, you could use chrome inspect element to get the xpath
row_list=r[0].findall('tr') #get the row list
clist=[]
for r in row_list:
for col in r.getchildren(): #get col list in each row
for a in col.xpath('div/a'): #use relative xpath to locate <a>
chapt_name=a.text,
chapt_url=urlparse.urljoin(url,a.get('href'))
clist.append({'cname':chapt_name,'curl':chapt_url})
ccount=len(clist)
if mode=='update':
if ccount<=last_chapter_count:
return '',{'index_url':url}
else:
clist=clist[last_chapter_count:]
ccount=len(clist)
i=0
Q=Queue.Queue()
tr=[]
for c in clist:
Q.put({'url':c['curl'],'index':i})
tr.append(-1)
i+=1
tlist=[]
for x in range(concurrent):
tlist.append(NewDThread(Q,useproxy,proxyserver,proxyport,proxyuser,
proxypass,tr,cv))
i=0
while True:
if control!=[]:
return None, {'index_url':url}
qlen=Q.qsize()
if Q.empty():
Q.join()
break
percent=int((float(ccount-qlen)/float(ccount))*100)
evt.Value=str(percent)+'%'
wx.PostEvent(win,evt)
if dmode=='stream':
if tr[i] != -1:
sevt.value=clist[i]['cname'][0]+tr[i]
wx.PostEvent(win,sevt)
i+=1
time.sleep(1)
i=0
bb=u''
for c in clist:
bb+=c['cname'][0]
bb+=tr[i]
i+=1
if not isinstance(bb,unicode):
bb=bb.decode('GBK','ignore')
evt.Value=u'下载完毕!'
evt.status='ok'
bookstate={}
bookstate['bookname']=bkname
bookstate['index_url']=url
bookstate['last_chapter_name']=clist[-1:][0]['cname'][0]
bookstate['last_update']=datetime.today().strftime('%y-%m-%d %H:%M')
bookstate['chapter_count']=ccount
wx.PostEvent(win,evt)
return bb,bookstate
if __name__ == '__main__':
GetBook('http://www.ranwen.net/files/article/17/17543/index.html')
#GetSearchResults(u'修真世界')
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,249
|
hujun-open/litebook
|
refs/heads/master
|
/gcepub.py
|
#-------------------------------------------------------------------------------
# Name: gcepub
# Purpose: extract the catalog from epub string
#
# Author: Hu Jun
#
# Created: 29/01/2011
# Copyright: (c) Hu Jun 2011
# Licence: Apache2
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import xml.parsers.expat
import re
import HTMLParser
class GCEPUB:
def __init__(self,instr):
self.ecount=0
self.start_e=False
self.rlist={}
self.start_txt=False
self.cur_txt=''
self.cur_url=''
self.instr=instr
self.Parser = xml.parsers.expat.ParserCreate()
self.Parser.CharacterDataHandler = self.getdata
self.Parser.StartElementHandler = self.start_ef
self.Parser.EndElementHandler = self.end_ef
## self.Parser.SetParamEntityParsing(xml.parsers.expat.XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
self.h=HTMLParser.HTMLParser()
self.instr=self.instr.replace('<','')
self.instr=self.instr.replace('>','')
def start_ef(self,name,attrs):
if name.lower()=='navpoint':
self.start_e=True
if name.lower()=='text' and self.start_e:
self.start_txt=True
if name.lower()=='content' and self.start_e:
self.cur_url=attrs['src']
def getdata(self,data):
if self.start_txt:
self.cur_txt=data
def end_ef(self,name):
if name.lower()=='navpoint':
self.start_e=False
self.start_txt=False
self.rlist[self.cur_url]=self.h.unescape(self.cur_txt)
self.ecount+=1
if name.lower()=='text':
self.start_txt=False
def parser(self):
self.Parser.Parse(self.instr,1)
def GetRList(self):
return self.rlist
if __name__ == '__main__':
f=open('toc.ncx','r')
m=GetCatalogFromEPUB(f.read())
for x in m:
print x[0],":::::",x[1]
f.close()
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,250
|
hujun-open/litebook
|
refs/heads/master
|
/jieba/posseg/viterbi.py
|
import operator
def get_top_states(t_state_v,K=4):
items = t_state_v.items()
topK= sorted(items,key=operator.itemgetter(1),reverse=True)[:K]
return [x[0] for x in topK]
def viterbi(obs, states, start_p, trans_p, emit_p):
V = [{}] #tabular
mem_path = [{}]
all_states = trans_p.keys()
for y in states.get(obs[0],all_states): #init
V[0][y] = start_p[y] * emit_p[y].get(obs[0],0)
mem_path[0][y] = ''
for t in range(1,len(obs)):
V.append({})
mem_path.append({})
prev_states = get_top_states(V[t-1])
prev_states =[ x for x in mem_path[t-1].keys() if len(trans_p[x])>0 ]
prev_states_expect_next = set( (y for x in prev_states for y in trans_p[x].keys() ) )
obs_states = states.get(obs[t],all_states)
obs_states = set(obs_states) & set(prev_states_expect_next)
if len(obs_states)==0: obs_states = all_states
for y in obs_states:
(prob,state ) = max([(V[t-1][y0] * trans_p[y0].get(y,0) * emit_p[y].get(obs[t],0) ,y0) for y0 in prev_states])
V[t][y] =prob
mem_path[t][y] = state
last = [(V[-1][y], y) for y in mem_path[-1].keys() ]
#if len(last)==0:
#print obs
(prob, state) = max(last)
route = [None] * len(obs)
i = len(obs)-1
while i>=0:
route[i] = state
state = mem_path[i][state]
i-=1
return (prob, route)
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,251
|
hujun-open/litebook
|
refs/heads/master
|
/myup.py
|
#-------------------------------------------------------------------------------
# Name: A UPNP Client to add port forward mapping on 1st respond router
# Purpose:
#
# Author: Hu Jun
#
# Created: 23/12/2012
# Copyright: (c) Hu Jun 2012
# Licence: GPLv2
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import socket
import struct
import time
import urllib2
from StringIO import StringIO
from httplib import HTTPResponse
from xml.dom import minidom
from urlparse import urlparse
import re
import traceback
import netifaces
def insubnet(ip1,mask1,ip2):
"""
return True if ip2 is in ip1's subnet
"""
bs1 = socket.inet_aton(ip1)
bs2 = socket.inet_aton(ip2)
mask = socket.inet_aton(mask1)
subnet1=''
for n in range(4):
subnet1+=chr(ord(bs1[n]) & ord(mask[n]))
subnet2=''
for n in range(4):
subnet2+=chr(ord(bs2[n]) & ord(mask[n]))
if subnet1 == subnet2:
return True
else:
return False
def getDRIntIP(gwip):
"""
return the 1st interface ip that in the the same subnet of gwip
"""
for ifname in netifaces.interfaces(): #return addr of 1st network interface
#print netifaces.ifaddresses(ifname)
if 2 in netifaces.ifaddresses(ifname) and 'netmask' in netifaces.ifaddresses(ifname)[2][0] :
if_addr = netifaces.ifaddresses(ifname)[2][0]['addr']
if if_addr != '127.0.0.1' and if_addr != None and if_addr != '':
#print netifaces.ifaddresses(ifname)[2][0]
if_mask = netifaces.ifaddresses(ifname)[2][0]['netmask']
if insubnet(if_addr,if_mask,gwip) == True:
return if_addr
return False
def checkLocalIP(cip):
"""
check if the cip is within the same subnet of any local address
"""
if cip == '127.0.0.1':return True
for ifname in netifaces.interfaces():
if 2 in netifaces.ifaddresses(ifname):
if_addr = netifaces.ifaddresses(ifname)[2][0]['addr']
if if_addr != '127.0.0.1' and if_addr != None and if_addr != '':
if_mask = netifaces.ifaddresses(ifname)[2][0]['netmask']
if insubnet(if_addr,if_mask,cip) == True:
return True
return False
class FakeSocket(StringIO):
def makefile(self, *args, **kw):
return self
def httpparse(fp):
socket = FakeSocket(fp.read())
response = HTTPResponse(socket)
response.begin()
return response
#sendSOAP is based on part of source code from miranda-upnp.
def sendSOAP(hostName,serviceType,controlURL,actionName,actionArguments):
argList = ''
soapResponse = ''
if '://' in controlURL:
urlArray = controlURL.split('/',3)
if len(urlArray) < 4:
controlURL = '/'
else:
controlURL = '/' + urlArray[3]
soapRequest = 'POST %s HTTP/1.1\r\n' % controlURL
#Check if a port number was specified in the host name; default is port 80
if ':' in hostName:
hostNameArray = hostName.split(':')
host = hostNameArray[0]
try:
port = int(hostNameArray[1])
except:
print 'Invalid port specified for host connection:',hostName[1]
return False
else:
host = hostName
port = 80
#Create a string containing all of the SOAP action's arguments and values
for arg,(val,dt) in actionArguments.iteritems():
argList += '<%s>%s</%s>' % (arg,val,arg)
#Create the SOAP request
soapBody = '<?xml version="1.0"?>\n'\
'<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\n'\
'<SOAP-ENV:Body>\n'\
'\t<m:%s xmlns:m="%s">\n'\
'%s\n'\
'\t</m:%s>\n'\
'</SOAP-ENV:Body>\n'\
'</SOAP-ENV:Envelope>' % (actionName,serviceType,argList,actionName)
#Specify the headers to send with the request
headers = {
'Host':hostName,
'Content-Length':len(soapBody),
'Content-Type':'text/xml',
'SOAPAction':'"%s#%s"' % (serviceType,actionName)
}
#Generate the final payload
for head,value in headers.iteritems():
soapRequest += '%s: %s\r\n' % (head,value)
soapRequest += '\r\n%s' % soapBody
#Send data and go into recieve loop
try:
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((host,port))
## if self.DEBUG:
## print self.STARS
## print soapRequest
## print self.STARS
## print ''
sock.send(soapRequest)
while True:
data = sock.recv(8192)
if not data:
break
else:
soapResponse += data
if re.compile('<\/.*:envelope>').search(soapResponse.lower()) != None:
break
sock.close()
(header,body) = soapResponse.split('\r\n\r\n',1)
if not header.upper().startswith('HTTP/1.') or not ' 200 ' in header.split('\r\n')[0]:
raise RuntimeError('SOAP request failed with error code:',header.split('\r\n')[0].split(' ',1)[1])
## errorMsg = self.extractSingleTag(body,'errorDescription')
## if errorMsg:
## print 'SOAP error message:',errorMsg
## return False
else:
return body
except Exception, e:
print 'Caught socket exception:',e
print traceback.format_exc()
sock.close()
return False
except KeyboardInterrupt:
print ""
sock.close()
return False
#def changePortMapping(PM_proto,internal_port,external_port,PM_desc="",method='add'):
def changePortMapping(mapping_list,method='add'):
"""
add or remove PortMapping on 1st respond router via UPNP
mapping_list is a list of dict:
{'desc':str,'port':int,'proto':str}
method: 'add' or 'remove'
note: the internal ip is auto-detected via:
- find the 1st interface address that are in the same subnet of
upnp-server's addr
"""
up_disc='M-SEARCH * HTTP/1.1\r\nHOST:239.255.255.250:1900\r\nST:upnp:rootdevice\r\nMX:2\r\nMAN:"ssdp:discover"\r\n\r\n'
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
sock.bind(('',19110))
sock.sendto(up_disc, ("239.255.255.250", 1900))
sock.settimeout(10.0)
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
sock.close()
internal_ip = getDRIntIP(addr[0])
## print "internal_ip is ",internal_ip
## print "received message:", data
descURL=httpparse(StringIO(data)).getheader('location')
## print "descURL is ",descURL
descXMLs=urllib2.urlopen(descURL).read()
pr=urlparse(descURL)
baseURL=pr.scheme+"://"+pr.netloc
## print descXMLs
dom=minidom.parseString(descXMLs)
ctrlURL=None
for e in dom.getElementsByTagName('service'):
stn=e.getElementsByTagName('serviceType')
if stn != []:
if stn[0].firstChild.nodeValue == 'urn:schemas-upnp-org:service:WANIPConnection:1':
cun=e.getElementsByTagName('controlURL')
ctrlURL=baseURL+cun[0].firstChild.nodeValue
break
## print "ctrlURL is ",ctrlURL
if ctrlURL != None:
for mapping in mapping_list:
if method=='add':
upnp_method='AddPortMapping'
sendArgs = {'NewPortMappingDescription': (mapping['desc'], 'string'),
'NewLeaseDuration': ('0', 'ui4'),
'NewInternalClient': (internal_ip, 'string'),
'NewEnabled': ('1', 'boolean'),
'NewExternalPort': (mapping['port'], 'ui2'),
'NewRemoteHost': ('', 'string'),
'NewProtocol': (mapping['proto'], 'string'),
'NewInternalPort': (mapping['port'], 'ui2')}
else:
upnp_method='DeletePortMapping'
sendArgs = {
'NewExternalPort': (mapping['port'], 'ui2'),
'NewRemoteHost': ('', 'string'),
'NewProtocol': (mapping['proto'], 'string'),}
sendSOAP(pr.netloc,'urn:schemas-upnp-org:service:WANIPConnection:1',
ctrlURL,upnp_method,sendArgs)
if __name__ == '__main__':
changePortMapping([{'port':50210,'proto':'UDP','desc':"testFromScript"}],'add')
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,252
|
hujun-open/litebook
|
refs/heads/master
|
/longbin.py
|
#-------------------------------------------------------------------------------
# Name: LongBin
# Purpose: For long binary number manipulation
#
# Author: Hu Jun
#
# Created: 16/09/2011
# Copyright: (c) Hu Jun 2011
# Licence: GPLv3
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import hashlib
import struct
class LongBin:
"""This class represent a long number, bigger than long type number
self.val: str that store the value
self.nlen: self.val length in bytes
"""
def __init__(self,copyval=None,nlen=20,binstr=None):
"""
binstr's format is "01010101000..."
copyval is actuall binary str
if binstr is not spcified, then use copyval;
otherwise covert binstr(1010101..)
"""
if binstr == None:
if isinstance(copyval,str) and copyval<>None:
if len(copyval)<>nlen:
raise ValueError('the length of copyval doesnt equal to '
+str(nlen))
else:
raise TypeError('copyval must be a str')
self.val = copyval
self.nlen=nlen
else:
blen=len(binstr)
if blen % 8 != 0:
raise ValueError("the len of binstr must be times of 8")
self.nlen=blen/8
self.val=''
for i in range(self.nlen):
self.val+=chr(int(binstr[i*8:i*8+8],2))
def __xor__(self,b):
i=0
rstr=''
if self.nlen<>b.nlen:
raise ValueError("these two LongBin have different length")
while i<self.nlen:
x=ord(self.val[i])
y=ord(b.val[i])
z=x^y
rstr+=chr(z)
i+=1
return LongBin(rstr,self.nlen)
def __eq__(self,b):
if self.nlen<>b.nlen:
return False
if self.val<>b.val:
return False
return True
def __ne__(self,b):
if type(self)<>type(b):
return True
if self.nlen<>b.nlen:
return True
if self.val<>b.val:
return True
return False
def __gt__(self,b):
i=0
while i<self.nlen:
if ord(self.val[i])>ord(b.val[i]):
return True
elif ord(self.val[i])<ord(b.val[i]):
return False
i+=1
return False
def __ge__(self,b):
i=0
while i<self.nlen:
if ord(self.val[i])>ord(b.val[i]):
return True
elif ord(self.val[i])<ord(b.val[i]):
return False
i+=1
return True
def __lt__(self,b):
i=0
while i<self.nlen:
if ord(self.val[i])>ord(b.val[i]):
return False
elif ord(self.val[i])<ord(b.val[i]):
return True
i+=1
return False
def __le__(self,b):
i=0
while i<self.nlen:
if ord(self.val[i])>ord(b.val[i]):
return False
elif ord(self.val[i])<ord(b.val[i]):
return True
i+=1
return True
def __str__(self):
""" convert val to string of 1010101..."""
i=0
rstr=''
while i<self.nlen:
rstr+='{0:08b}'.format(ord(self.val[i]))
i+=1
return rstr
def hexstr(self):
return "0x"+self.val.encode('hex_codec')
if __name__ == '__main__':
h1=hashlib.sha1()
h2=hashlib.sha1()
h1.update('1')
h2.update('2')
x=LongBin(h1.digest())
y=LongBin(h2.digest())
print x
print y
print x^y
print x>=y
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,253
|
hujun-open/litebook
|
refs/heads/master
|
/litebook.py
|
#!/usr/bin/env py32
# -*- coding: utf-8 -*-
#This is the source file of LiteBook (for all Windows/Linux/OSX)
#see Readme.txt for module dependcy
#
#
#
import locale
SYSENC=locale.getdefaultlocale()[1]
import sys
FullVersion=False
if len(sys.argv)>1:
if sys.argv[1]=='-full':
FullVersion=True
if FullVersion:
import download_manager
import ltbsearchdiag
import xmlrpclib
import myup
import kpub
import Zeroconf
import socket
import SocketServer
import posixpath
import BaseHTTPServer
import urllib
import web_download_manager
import jf
import traceback
import platform
HOSTNAME = platform.node()
MYOS = platform.system()
osarch=platform.architecture()
if osarch[1]=='ELF' and MYOS == 'Linux':
if osarch[0]=='64bit':
from lxml_linux_64 import etree
elif osarch[0]=='32bit':
from lxml_linux import etree
elif MYOS == 'Darwin':
from lxml_osx import etree
else:
from lxml import etree
if MYOS != 'Linux' and MYOS != 'Darwin' and MYOS != 'Windows':
print "This version of litebook only support Linux and MAC OSX"
sys.exit(1)
if MYOS == 'Linux':
import dbus
elif MYOS == 'Darwin':
import netifaces
elif MYOS == 'Windows':
import wmi
import win32api
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import ez_epub
import gcepub
import ComboDialog
import liteview
import webbrowser
import keygrid
import imp
import urllib2
import glob
import math
import htmlentitydefs
#add the codepoints are not in the standard lib
htmlentitydefs.name2codepoint['ldqo']=ord(u'“')
htmlentitydefs.name2codepoint['rdqo']=ord(u'”')
htmlentitydefs.name2codepoint['lsqo']=ord(u'‘')
htmlentitydefs.name2codepoint['rsqo']=ord(u'’')
htmlentitydefs.name2codepoint['dash']=ord(u'-')
htmlentitydefs.name2codepoint['hllp']=8230
import wx
import wx.lib.mixins.listctrl
import wx.lib.newevent
import sqlite3
import struct
import zlib
import os
import glob
import sys
import ConfigParser
import time
from datetime import datetime
import re
import zipfile
import rarfile
import codecs
import shutil
import encodings.gbk
import encodings.utf_8
import encodings.big5
import encodings.utf_16
from chardet.universaldetector import UniversalDetector
import chardet
if MYOS == 'Windows':
import win32process
import UnRAR2
import subprocess
import thread
import hashlib
import threading
try:
from agw import hyperlink as hl
except ImportError: # if it's not there locally, try the wxPython lib.
import wx.lib.agw.hyperlink as hl
try:
from agw import genericmessagedialog as GMD
except ImportError: # if it's not there locally, try the wxPython lib.
import wx.lib.agw.genericmessagedialog as GMD
# begin wxGlade: extracode
# end wxGlade
(UpdateStatusBarEvent, EVT_UPDATE_STATUSBAR) = wx.lib.newevent.NewEvent()
(ReadTimeAlert,EVT_ReadTimeAlert)=wx.lib.newevent.NewEvent()
(ScrollDownPage,EVT_ScrollDownPage)=wx.lib.newevent.NewEvent()
##(GetPosEvent,EVT_GetPos)=wx.lib.newevent.NewEvent()
(VerCheckEvent,EVT_VerCheck)=wx.lib.newevent.NewEvent()
(DownloadFinishedAlert,EVT_DFA)=wx.lib.newevent.NewEvent()
(DownloadUpdateAlert,EVT_DUA)=wx.lib.newevent.NewEvent()
(AlertMsgEvt,EVT_AME)=wx.lib.newevent.NewEvent()
(UpdateEvt,EVT_UPD)=wx.lib.newevent.NewEvent()
(UpdateValueEvt,EVT_UPDV)=wx.lib.newevent.NewEvent()
def GetMDNSIP_OSX():
"""
return v4 addr of 1st wlan interface in OSX, if there is no wlan interface,
then the v4 addr of 1st network interface will be returned
"""
try:
r = subprocess.check_output(['/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport','prefs'])
except:
r = False
if r != False:
wif = r.splitlines()[0].split()[-1:][0][:-1]
try:
return netifaces.ifaddresses(wif)[2][0]['addr']
except:
pass
for ifname in netifaces.interfaces(): #return addr of 1st network interface
if 2 in netifaces.ifaddresses(ifname):
if_addr = netifaces.ifaddresses(wif)[2][0]['addr']
if if_addr != '127.0.0.1' and if_addr != None and if_addr != '':
return if_addr
def GetMDNSIP_Win():#windows version
global GlobalConfig
"""This function return IPv4 addr of 1st WLAN interface. if there is no WLAN interface, then it will return the v4 address of the main interface """
if sys.platform=='win32':
if GlobalConfig['mDNS_interface']=='AUTO':
wlan_int_id=None
for nic in wmi.WMI().Win32_NetworkAdapter():
if nic.NetConnectionID == "Wireless Network Connection":
wlan_int_id=nic.Index
break
if wlan_int_id<>None:
for nic in wmi.WMI ().Win32_NetworkAdapterConfiguration (IPEnabled=1):
if nic.Index==wlan_int_id:
wlan_ip=nic.IPAddress[0]
break
else:
wlan_ip=None
else:
wlan_ip=None
for nic in wmi.WMI ().Win32_NetworkAdapterConfiguration (IPEnabled=1):
if nic.Caption==GlobalConfig['mDNS_interface']:
wlan_ip=nic.IPAddress[0]
break
if wlan_ip<>None:
try:
socket.inet_aton(wlan_ip)
except:
wlan_ip=None
if wlan_ip<>None:
if wlan_ip=='0.0.0.0':wlan_ip=None
else:
if wlan_ip[:7]=='169.254':wlan_ip=None
if wlan_ip==None:
ar=socket.getaddrinfo(socket.gethostname(), 80, 0, 0, socket.SOL_TCP)
if socket.has_ipv6:
if len(ar)>1:
wlan_ip=ar[1][4][0]
else:
wlan_ip=ar[0][4][0]
else:
wlan_ip=ar[0][4][0]
if wlan_ip == '0.0.0.0' or wlan_ip=='127.0.0.1':
return False
else:
return wlan_ip
def GetMDNSIP():
global GlobalConfig
"""This function return IPv4 addr of 1st WLAN interface. if there is no WLAN interface, then it will return the v4 address of the main interface """
bus = dbus.SystemBus()
proxy = bus.get_object("org.freedesktop.NetworkManager",
"/org/freedesktop/NetworkManager")
manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager")
# Get device-specific state
devices = manager.GetDevices()
for d in devices:
dev_proxy = bus.get_object("org.freedesktop.NetworkManager", d)
prop_iface = dbus.Interface(dev_proxy, "org.freedesktop.DBus.Properties")
# Get the device's current state and interface name
state = prop_iface.Get("org.freedesktop.NetworkManager.Device", "State")
name = prop_iface.Get("org.freedesktop.NetworkManager.Device", "Interface")
ifa = "org.freedesktop.NetworkManager.Device"
type = prop_iface.Get(ifa, "DeviceType")
addr = prop_iface.Get(ifa, "Ip4Address")
wlan_ip=None
candidate_ip=None
if state == 8: # activated
addr_dotted = socket.inet_ntoa(struct.pack('<L', addr))
str_addr=str(addr_dotted)
if type==2: #if it is a wifi interface
wlan_ip=str_addr
break
else:
if type==1:
candidate_ip=str_addr
if wlan_ip == '0.0.0.0' or wlan_ip=='127.0.0.1':
return False
elif wlan_ip==None:
if candidate_ip<>None:
return candidate_ip
else:
return False
else:
return wlan_ip
def cmp_filename(x,y):
p=re.compile('\d+')
if p.search(x)==None:
m=0
else:
m=int(p.search(x).group())
if p.search(y)==None:
n=0
else:
n=int(p.search(y).group())
return m-n
def parseBook(instr,divide_method=0,zishu=10000):
"""
preparation for epub file generation
"""
if not isinstance(instr,unicode):
instr=instr.decode('GBK','ignore')
## rlist,c_list=GenCatalog(instr,divide_method,zishu)
rlist=GenCatalog(instr,divide_method,zishu)
sections = []
istr=instr
last_pos=0
i=0
for c in rlist:
section = ez_epub.Section()
#section.css = """.em { font-style: italic; }"""
section.title = c[0]
x=c[1]
if i<len(rlist)-1:
sec_str=istr[x:rlist[i+1][1]]
else:
sec_str=istr[x:]
## line_list = sec_str.splitlines()
## sec_str=''
## for line in line_list:
## sec_str+=u'<p>'+line+u'</p>\n'
section.text.append(sec_str)
last_pos=x
sections.append(section)
i+=1
return sections
def txt2epub(instr,outfile,title='',authors=[],divide_method=0,zishu=10000):
"""
infile: path of input text file
outfile: path of output text file.(don't add .epub)
title: book title
authors: list of author names
"""
book = ez_epub.Book()
if title=='':
book.title=outfile
else:
book.title = title
book.authors = authors
book.sections = parseBook(instr,divide_method,zishu)
book.make(outfile)
try:
shutil.rmtree(outfile)
except:
pass
OnDirectSeenPage=False
GlobalConfig={}
KeyConfigList=[]
KeyMenuList={}
PluginList={}
OpenedFileList=[]
current_file=''
load_zip=False
current_file_list=[]
current_zip_file=''
OnScreenFileList=[]
CurOnScreenFileIndex=0
BookMarkList=[]
ThemeList=[]
BookDB=[]
Ticking=True
Version='3.21 '+MYOS
I_Version=3.21 # this is used to check updated version
lb_hash='3de03ac38cc1c2dc0547ee09f866ee7b'
def cur_file_dir():
#获取脚本路径
global MYOS
if MYOS == 'Linux':
path = sys.path[0]
elif MYOS == 'Windows':
return os.path.dirname(AnyToUnicode(os.path.abspath(sys.argv[0])))
else:
if sys.argv[0].find('/') != -1:
path = sys.argv[0]
else:
path = sys.path[0]
if isinstance(path,str):
path=path.decode('utf-8')
#判断为脚本文件还是py2exe编译后的文件,如果是脚本文件,则返回的是脚本的目录,如果是编译后的文件,则返回的是编译后的文件路径
if os.path.isdir(path):
return path
elif os.path.isfile(path):
return os.path.dirname(path)
def str2list(istr):
rlist=[]
if istr[0]<>'[' and istr[0]<>'(':
return istr
mlist=istr[1:-1].split(',')
for m in mlist:
rlist.append(int(m))
return rlist
def DetectFileCoding(filepath,type='txt',zipfilepath=''):
"""Return a file's encoding, need import chardet """
global MYOS
if type=='txt':
try:
input_file=open(filepath,'r')
except:
dlg = wx.MessageDialog(None, filepath+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return "error"
else:
if type=='zip':
try:
zfile=zipfile.ZipFile(zipfilepath)
if isinstance(filepath, unicode):
filepath=filepath.encode('gbk')
input_file=zfile.read(filepath)
except:
dlg = wx.MessageDialog(None, zipfilepath+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return "error"
lines=input_file.splitlines()
detector = UniversalDetector()
line_count=0
for line in lines:
detector.feed(line)
if detector.done or line_count==50: break# decrease this number to improve speed
line_count+=1
detector.close()
if detector.result['encoding']<>None:
return detector.result['encoding'].lower()
else:
return None
if type=='rar':
if MYOS == 'Windows':
try:
rfile=UnRAR2.RarFile(zipfilepath)
buff=rfile.read_files(filepath)
except Exception as inst:
dlg = wx.MessageDialog(None, zipfilepath+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return "error"
lines=buff[0][1].splitlines()
else:
buff=unrar(zipfilepath,filepath)
if buff==False:
dlg = wx.MessageDialog(None, zipfilepath+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return "error"
lines=buff.splitlines()
detector = UniversalDetector()
line_count=0
for line in lines:
line=line[:800] # decrease this number to improve speed
detector.feed(line)
if detector.done or line_count==1000: break# decrease this number to improve speed
line_count+=1
detector.close()
if detector.result['encoding']<>None:
return detector.result['encoding'].lower()
else:
return None
detector = UniversalDetector()
line_count=0
while line_count<50: # decrease this number to improve speed
if type=='txt':line=input_file.readline(100) # decrease this number to improve speed
detector.feed(line)
if detector.done: break
line_count+=1
detector.close()
input_file.close()
if detector.result['encoding']<>None:
return detector.result['encoding'].lower()
else:
return None
def GetPint():
p=platform.architecture()
if p[0]=='32bit': return 'L'
else:
return 'I'
def isfull(l):
xx=0
n=len(l)
count=0
while xx<n:
if l[xx]==-1: count+=1
xx+=1
if count==0: return True
else:
return int((float(n-count)/float(n))*100)
def JtoF(data):
#简体到繁体
return jf.jtof(data)
def FtoJ(data):
#繁体到简体
return jf.ftoj(data)
def GenCatalog(instr,divide_method=0,zishu=10000):
"""
Return a list of : [cname,pos]
"""
if not isinstance(instr,unicode):
instr=instr.decode("gbk")
rlist=[]
#c_list=[]
if divide_method==0:
#自动划分章节
max_chapter_len=50 #the chapter len>50 will be skipped,this is used to detect redundant chapter lines
cur_pos=0
n=len(instr)
hash_len=len(lb_hash)
cpos=instr.find(lb_hash)
if cpos<>-1:
while cur_pos<n:
cur_pos=instr.find(lb_hash,cur_pos)
if cur_pos==-1: break
tstr=instr[cur_pos:cur_pos+100]
llist=tstr.splitlines()
chapter=llist[0][hash_len:]
rlist.append([chapter,cur_pos])
## rlist[chapter]=cur_pos
## c_list.append(chapter)
cur_pos+=1
else:
#if there is NO lb_hash string found, try to automatic guess the catalog
chnum_str=u'(零|一|壹|二|俩|两|贰|三|叁|四|肆|五|伍|六|陆|七|柒|八|捌|九|玖|十|拾|百|佰|千|仟|万|0|1|2|3|4|5|6|7|8|9)'
ch_ten_str=u'(十|百|千|万)'
ch_ten_dict={u'十':u'0',u'百':u'00',u'千':u'000',u'万':u'0000',}
ch_dict={u'零':u'0',u'一':u'1',u'二':u'2',u'三':u'3',u'四':u'4',u'五':u'5',u'六':u'6',u'七':u'7',u'八':u'8',u'九':u'9',}
p=re.compile(u'第'+chnum_str+u'+(章|节|部|卷|回)',re.L|re.U)
nlist=p.findall(instr)
m_list=p.finditer(instr)
if len(nlist)<5:
p=re.compile(u'(章|节|部|卷|回)'+chnum_str+u'+\s',re.L|re.U)
m_list=p.finditer(instr)
#last_chapter=None
## c_list.append(u'本书首页>>>>')
## rlist[u'本书首页>>>>']=0
rlist.append([u'本书首页>>>>',0])
last_end=0
## last_chapter=None
for m in m_list:
if instr[last_end:m.start()].find('\n')==-1:
continue
re_start_pos=m.start()
re_end_pos=m.end()
last_end=re_end_pos
## if last_chapter==instr[re_start_pos:re_end_pos]:
## continue
## else:
## last_chapter=instr[re_start_pos:re_end_pos]
start_pos=re_start_pos
ch=instr[start_pos]
pos1=start_pos
while ch<>'\n':
pos1-=1
ch=instr[pos1]
pos1+=1
pos2=start_pos
ch=instr[start_pos]
while ch<>'\n':
pos2+=1
ch=instr[pos2]
#pos2-=1
if pos2-pos1>50:
continue
chapter=instr[pos1:pos2].strip()
## if chapter == last_chapter:
## continue
if len(rlist)>0:
if pos1-rlist[-1:][0][1]>80: #to remove dup title lines
rlist.append([chapter,pos1])
else:
rlist.append([chapter,pos1])
## rlist[chapter]=pos1
## c_list.append(chapter)
## last_chapter = chapter
elif divide_method==1:
#按字数划分
c_list=[]
len_str=len(instr)
num_ch,left=divmod(len_str,zishu)
cur_pos=0
i=1
while i<=num_ch:
cur_pos=(i-1)*zishu
chapter=u'第'+unicode(i)+u'章(字数划分)'
c_list.append(chapter)
rlist.append([chapter,cur_pos])
#rlist[chapter]=cur_pos
i+=1
chapter=u'第'+unicode(i)+u'章(字数划分)'
rlist.append([chapter,num_ch*zishu])
## c_list.append(chapter)
## rlist[chapter]=num_ch*zishu
#for c in c_list:print c
##
## print "the final rlist is ", rlist
## print "the final clist is ",c_list
## return (rlist,c_list)
return rlist
def AnyToUnicode(input_str,coding=None):
"""Convert any coding str into unicode str. this function should used with function DetectFileCoding"""
if isinstance(input_str,unicode): return input_str
if coding<>None:
if coding <> 'utf-8':
if coding.lower()=='gb2312':
coding='GBK'
output_str=unicode(input_str,coding,errors='replace')
else:
output_str=input_str.decode('utf-8',"replace")
else:
output_str=unicode(input_str,'gbk',errors='replace')
return output_str
def readPlugin():
global PluginList, MYOS
PluginList={}
if MYOS != 'Windows':
flist=glob.glob(cur_file_dir()+"/plugin/*.py")
else:
flist=glob.glob(os.path.dirname(AnyToUnicode(os.path.abspath(sys.argv[0])))+u"\\plugin\\*.py")
i=0
for f in flist:
if MYOS != 'Windows':
bname=os.path.basename(f)
fpath=cur_file_dir()+"/plugin/"+bname
fpath=fpath.encode('utf-8')
else:
bname=os.path.basename(AnyToUnicode(f))
fpath=os.path.dirname(AnyToUnicode(os.path.abspath(sys.argv[0])))+u'\\plugin\\'+bname
fpath=fpath.encode('gbk')
try:
PluginList[bname]=imp.load_source(str(i),fpath)
except Exception as inst:
## print traceback.format_exc()
## print inst
return False
i+=1
## for k in PluginList.keys():
## print k
def InstallDefaultConfig():
global ThemeList,KeyConfigList
fname=cur_file_dir()+u"/defaultconfig.ini"
config=MyConfig()
try:
ffp=codecs.open(fname,encoding='utf-8',mode='r')
config.readfp(ffp)
except:
return
#install appearance
if config.has_section('Appearance'):
ft_list=config.items('Appearance')
for ft in ft_list:
tname=ft[0]
f=ft[1].split('|')
if len(f)<>21: continue
try:
l={}
l['font']=wx.Font(int(f[0]),int(f[1]),int(f[2]),int(f[3]),eval(f[4]),f[5],int(f[6]))
l['fcolor']=eval(f[7])
l['bcolor']=eval(f[8])
if f[9]<>'None':
l['backgroundimg']=f[9]
else:
l['backgroundimg']=None
l['showmode']=f[10]
l['backgroundimglayout']=f[11]
l['underline']=eval(f[12])
l['underlinestyle']=int(f[13])
l['underlinecolor']=f[14]
l['pagemargin']=int(f[15])
l['bookmargin']=int(f[16])
l['vbookmargin']=int(f[17])
l['centralmargin']=int(f[18])
l['linespace']=int(f[19])
l['vlinespace']=int(f[20])
l['name']=tname
l['config']=ft[1]
except:
continue
ThemeList.append(l)
#install key config
secs=config.sections()
secs.remove('Appearance')
for sec in secs:
tname=sec
kconfig=[]
kconfig.append(tname)
for f,v in keygrid.LB2_func_list.items():
try:
cstr=config.get(sec,f)
cstr_list=cstr.split('&&')
for cs in cstr_list:
kconfig.append((f,cs))
except:
kconfig.append((f,v))
KeyConfigList.append(kconfig)
GlobalConfig['InstallDefaultConfig']=False
def readKeyConfig():
global KeyConfigList,KeyMenuList,MYOS
config=MyConfig()
conffile=GlobalConfig['path_list']['key_conf']
try:
ffp=codecs.open(conffile,encoding='utf-8',mode='r')
config.readfp(ffp)
except:
kconfig=[]
kconfig.append(('last'))
for func,keyval in keygrid.LB2_func_list.items():
kconfig.append((func,keyval))
## kconfig.append((u'向上翻行',"----+WXK_UP"))
## kconfig.append((u'向下翻行',"----+WXK_DOWN"))
## kconfig.append((u'向上翻页',"----+WXK_PAGEUP"))
## kconfig.append((u'向上翻页',"----+WXK_LEFT"))
## kconfig.append((u'向下翻页',"----+WXK_PAGEDOWN"))
## kconfig.append((u'向下翻页',"----+WXK_RIGHT"))
## kconfig.append((u'向下翻页',"----+WXK_SPACE"))
## kconfig.append((u'向上翻半页','----+","'))
## kconfig.append((u'向下翻半页','----+"."'))
## kconfig.append((u'后退10%','----+"["'))
## kconfig.append((u'前进10%','----+"]"'))
## kconfig.append((u'后退1%','----+"9"'))
## kconfig.append((u'前进1%','----+"0"'))
##
## kconfig.append((u'跳到首页',"----+WXK_HOME"))
## kconfig.append((u'跳到结尾',"----+WXK_END"))
## kconfig.append((u'文件列表','C---+"O"'))
## kconfig.append((u'打开文件','C---+"P"'))
## kconfig.append((u'另存为','C---+"S"'))
## kconfig.append((u'关闭','C---+"Z"'))
## kconfig.append((u'上一个文件','C---+"["'))
## kconfig.append((u'下一个文件','C---+"]"'))
## kconfig.append((u'搜索小说网站','-A--+"C"'))
## kconfig.append((u'搜索LTBNET','-A--+"S"'))
## kconfig.append((u'重新载入插件','C---+"R"'))
## kconfig.append((u'选项','-A--+"O"'))
## kconfig.append((u'退出','-A--+"X"'))
## kconfig.append((u'拷贝','C---+"C"'))
## kconfig.append((u'查找','C---+"F"'))
## kconfig.append((u'查找下一个','----+WXK_F3'))
## kconfig.append((u'查找上一个','----+WXK_F4'))
## kconfig.append((u'替换','C---+"H"'))
## kconfig.append((u'纸张显示模式','-A--+"M"'))
## kconfig.append((u'书本显示模式','-A--+"B"'))
## kconfig.append((u'竖排书本显示模式','-A--+"N"'))
## kconfig.append((u'显示目录','C---+"U"'))
## kconfig.append((u'显示工具栏','C---+"T"'))
## kconfig.append((u'缩小工具栏','C---+"-"'))
## kconfig.append((u'放大工具栏','C---+"="'))
## kconfig.append((u'全屏显示','C---+"I"'))
## kconfig.append((u'显示文件侧边栏','-A--+"D"'))
## kconfig.append((u'自动翻页','-A--+"T"'))
## kconfig.append((u'智能分段','-A--+"P"'))
## kconfig.append((u'添加到收藏夹','C---+"D"'))
## kconfig.append((u'整理收藏夹','C---+"M"'))
## kconfig.append((u'简明帮助','----+WXK_F1'))
## kconfig.append((u'版本更新内容','----+WXK_F2'))
## kconfig.append((u'检查更新','----+WXK_F5'))
## kconfig.append((u'关于','----+WXK_F6'))
## kconfig.append((u'过滤HTML标记','----+WXK_F9'))
## kconfig.append((u'切换为简体字','----+WXK_F7'))
## kconfig.append((u'切换为繁体字','----+WXK_F8'))
## kconfig.append((u'显示进度条','----+"Z"'))
## kconfig.append((u'增大字体','----+"="'))
## kconfig.append((u'减小字体','----+"-"'))
## kconfig.append((u'清空缓存','CA--+"Q"'))
## kconfig.append((u'最小化','----+WXK_ESCAPE'))
## kconfig.append((u'生成EPUB文件','C---+"E"'))
## kconfig.append((u'启用WEB服务器','-A--+"W"'))
## kconfig.append((u'显示章节侧边栏','-A--+"J"'))
KeyConfigList.append(kconfig)
i=1
tl=len(kconfig)
while i<tl:
KeyMenuList[kconfig[i][0]]=keygrid.str2menu(kconfig[i][1])
i+=1
return
if not config.has_section('last'):
kconfig=[]
kconfig.append(('last'))
for func,keyval in keygrid.LB2_func_list.items():
kconfig.append((func,keyval))
## kconfig.append((u'向上翻行',"----+WXK_UP"))
## kconfig.append((u'向下翻行',"----+WXK_DOWN"))
## kconfig.append((u'向上翻页',"----+WXK_PAGEUP"))
## kconfig.append((u'向上翻页',"----+WXK_LEFT"))
## kconfig.append((u'向下翻页',"----+WXK_PAGEDOWN"))
## kconfig.append((u'向下翻页',"----+WXK_RIGHT"))
## kconfig.append((u'向下翻页',"----+WXK_SPACE"))
## kconfig.append((u'向上翻半页','----+","'))
## kconfig.append((u'向下翻半页','----+"."'))
## kconfig.append((u'后退10%','----+"["'))
## kconfig.append((u'前进10%','----+"]"'))
## kconfig.append((u'后退1%','----+"9"'))
## kconfig.append((u'前进1%','----+"0"'))
##
## kconfig.append((u'跳到首页',"----+WXK_HOME"))
## kconfig.append((u'跳到结尾',"----+WXK_END"))
## kconfig.append((u'文件列表','C---+"O"'))
## kconfig.append((u'打开文件','C---+"P"'))
## kconfig.append((u'另存为','C---+"S"'))
## kconfig.append((u'关闭','C---+"Z"'))
## kconfig.append((u'上一个文件','C---+"["'))
## kconfig.append((u'下一个文件','C---+"]"'))
## kconfig.append((u'搜索小说网站','-A--+"C"'))
## kconfig.append((u'搜索LTBNET','-A--+"S"'))
## kconfig.append((u'重新载入插件','C---+"R"'))
## kconfig.append((u'选项','-A--+"O"'))
## kconfig.append((u'退出','-A--+"X"'))
## kconfig.append((u'拷贝','C---+"C"'))
## kconfig.append((u'查找','C---+"F"'))
## kconfig.append((u'替换','C---+"H"'))
## kconfig.append((u'查找下一个','----+WXK_F3'))
## kconfig.append((u'查找上一个','----+WXK_F4'))
## kconfig.append((u'纸张显示模式','-A--+"M"'))
## kconfig.append((u'书本显示模式','-A--+"B"'))
## kconfig.append((u'竖排书本显示模式','-A--+"N"'))
## kconfig.append((u'显示工具栏','C---+"T"'))
## kconfig.append((u'缩小工具栏','C---+"-"'))
## kconfig.append((u'放大工具栏','C---+"="'))
## kconfig.append((u'显示目录','C---+"U"'))
## kconfig.append((u'全屏显示','C---+"I"'))
## kconfig.append((u'显示文件侧边栏','-A--+"D"'))
## kconfig.append((u'自动翻页','-A--+"T"'))
## kconfig.append((u'智能分段','-A--+"P"'))
## kconfig.append((u'添加到收藏夹','C---+"D"'))
## kconfig.append((u'整理收藏夹','C---+"M"'))
## kconfig.append((u'简明帮助','----+WXK_F1'))
## kconfig.append((u'版本更新内容','----+WXK_F2'))
## kconfig.append((u'检查更新','----+WXK_F5'))
## kconfig.append((u'关于','----+WXK_F6'))
## kconfig.append((u'过滤HTML标记','----+WXK_F9'))
## kconfig.append((u'切换为简体字','----+WXK_F7'))
## kconfig.append((u'切换为繁体字','----+WXK_F8'))
## kconfig.append((u'显示进度条','----+"Z"'))
## kconfig.append((u'增大字体','----+"="'))
## kconfig.append((u'减小字体','----+"-"'))
## kconfig.append((u'清空缓存','CA--+"Q"'))
## kconfig.append((u'最小化','----+WXK_ESCAPE'))
## kconfig.append((u'生成EPUB文件','C---+"E"'))
## kconfig.append((u'启用WEB服务器','-A--+"W"'))
## kconfig.append((u'显示章节侧边栏','-A--+"J"'))
KeyConfigList.append(kconfig)
else:
kconfig=[]
kconfig.append(('last'))
for f,v in keygrid.LB2_func_list.items():
try:
cstr=config.get('last',f)
cstr_list=cstr.split('&&')
for cs in cstr_list:
kconfig.append((f,cs))
except:
kconfig.append((f,v))
KeyConfigList.append(kconfig)
secs=config.sections()
secs.remove('last')
for sec in secs:
kconfig=[]
kconfig.append((sec))
opts=config.options(sec)
for opt in opts:
cstr=config.get(sec,opt)
cstr_list=cstr.split('&&')
for cs in cstr_list:
kconfig.append((opt,cs))
KeyConfigList.append(kconfig)
for kconfig in KeyConfigList:
if kconfig[0]=='last':
break
i=1
tl=len(kconfig)
while i<tl:
KeyMenuList[kconfig[i][0]]=keygrid.str2menu(kconfig[i][1])
i+=1
def writeKeyConfig():
global KeyConfigList,MYOS
config=MyConfig()
for kconfig in KeyConfigList:
config.add_section(kconfig[0])
i=1
kl=len(kconfig)
cstr={}
while i<kl:
if kconfig[i][0] not in cstr:
cstr[kconfig[i][0]]=kconfig[i][1]
else:
cstr[kconfig[i][0]]+="&&"+kconfig[i][1]
i+=1
for key,val in cstr.items():
config.set(kconfig[0],unicode(key),val)
conffile=GlobalConfig['path_list']['key_conf']
try:
ConfigFile=codecs.open(conffile,encoding='utf-8',mode='w')
config.write(ConfigFile)
ConfigFile.close()
except:
dlg = wx.MessageDialog(None, u'写入按键配置文件错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return False
def readConfigFile():
"""This function will read config from litebook.ini to a global dict var: GlobalConfig"""
global GlobalConfig,OpenedFileList,BookMarkList,ThemeList,BookDB,MYOS,HOSTNAME
config = MyConfig()
conffile=GlobalConfig['path_list']['conf']
conffile=conffile
try:
ffp=codecs.open(conffile,encoding='utf-8',mode='r')
config.readfp(ffp)
except:
if MYOS == 'Windows':
GlobalConfig['LastDir']=os.path.dirname(AnyToUnicode(os.path.abspath(sys.argv[0])))
GlobalConfig['ConfigDir']=os.environ['APPDATA'].decode('gbk')
GlobalConfig['IconDir']=os.path.dirname(AnyToUnicode(os.path.abspath(sys.argv[0])))+u"\\icon"
GlobalConfig['ShareRoot']=os.environ['USERPROFILE'].decode('gbk')+u"\\litebook\\shared"
else:
GlobalConfig['LastDir']=os.environ['HOME'].decode('utf-8')
GlobalConfig['IconDir']=cur_file_dir()+u"/icon"
GlobalConfig['ConfigDir']=unicode(os.environ['HOME'],'utf-8')+u'/litebook/'
GlobalConfig['ShareRoot']=unicode(os.environ['HOME'],'utf-8')+u"/litebook/shared"
GlobalConfig['LTBNETRoot']=GlobalConfig['ShareRoot']
GlobalConfig['LTBNETPort']=50200
GlobalConfig['LTBNETID']='NONE'
OpenedFileList=[]
GlobalConfig['LastFile']=''
GlobalConfig['LastZipFile']=''
GlobalConfig['LastPos']=0
BookMarkList=[]
GlobalConfig['CurFont']=wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "")
GlobalConfig['CurFColor']=(0,0,0,0)
GlobalConfig['CurBColor']='LIGHT BLUE'
GlobalConfig['LoadLastFile']=True
GlobalConfig['AutoScrollInterval']=12000
GlobalConfig['MaxBookDB']=50
GlobalConfig['MaxOpenedFiles']=5
GlobalConfig['RemindInterval']=60
GlobalConfig['EnableSidebarPreview']=True
GlobalConfig['VerCheckOnStartup']=True
GlobalConfig['HashTitle']=False
GlobalConfig['ShowAllFileInSidebar']=True
GlobalConfig['HideToolbar']=False
GlobalConfig['EnableESC']=False
GlobalConfig['useproxy']=False
GlobalConfig['proxyserver']=''
GlobalConfig['proxyport']=0
GlobalConfig['proxyuser']=''
GlobalConfig['proxypass']=''
GlobalConfig['DAUDF']=0
GlobalConfig['lastwebsearchkeyword']=''
GlobalConfig['defaultsavedir']=GlobalConfig['LastDir']
GlobalConfig['numberofthreads']=10
GlobalConfig['lastweb']=''
GlobalConfig['backgroundimg']="default.jpg"
GlobalConfig['backgroundimglayout']='tile'
GlobalConfig['showmode']='paper'
GlobalConfig['underline']=True
GlobalConfig['underlinecolor']='GREY'
GlobalConfig['underlinestyle']=wx.DOT
GlobalConfig['pagemargin']=50
GlobalConfig['bookmargin']=50
GlobalConfig['vbookmargin']=50
GlobalConfig['vbookpunc']=True
GlobalConfig['centralmargin']=20
GlobalConfig['linespace']=5
GlobalConfig['vlinespace']=15
GlobalConfig['InstallDefaultConfig']=True
GlobalConfig['RunWebserverAtStartup']=False
GlobalConfig['ServerPort']=8000
GlobalConfig['mDNS_interface']='AUTO'
GlobalConfig['ToolSize']=32
GlobalConfig['RunUPNPAtStartup']=False
GlobalConfig['EnableLTBNET']=False
GlobalConfig['BookDirPrefix']=""
return
try:
GlobalConfig['BookDirPrefix']=config.get('settings','BookDirPrefix').strip()
GlobalConfig['BookDirPrefix']=os.path.abspath(GlobalConfig['BookDirPrefix'])
if os.path.isdir(GlobalConfig['BookDirPrefix']) == False:
raise ValueError("")
except:
GlobalConfig['BookDirPrefix']=''
try:
GlobalConfig['mDNS_interface']=config.get('settings','mDNS_interface')
except:
GlobalConfig['mDNS_interface']='AUTO'
try:
GlobalConfig['RunUPNPAtStartup']=config.getboolean('settings','RunUPNPAtStartup')
except:
GlobalConfig['RunUPNPAtStartup']=False
try:
GlobalConfig['EnableLTBNET']=config.getboolean('settings','EnableLTBNET')
except:
GlobalConfig['EnableLTBNET']=False
try:
GlobalConfig['RunWebserverAtStartup']=config.getboolean('settings','RunWebserverAtStartup')
except:
GlobalConfig['RunWebserverAtStartup']=False
try:
GlobalConfig['ServerPort']=config.getint('settings','ServerPort')
except:
GlobalConfig['ServerPort']=8000
try:
GlobalConfig['ToolSize']=config.getint('settings','toolsize')
except:
GlobalConfig['ToolSize']=32
try:
GlobalConfig['ShareRoot']=os.path.abspath(config.get('settings','ShareRoot'))
except:
if MYOS == 'Windows':
GlobalConfig['ShareRoot']=os.environ['USERPROFILE'].decode('gbk')+u"\\litebook\\shared"
else:
GlobalConfig['ShareRoot']=unicode(os.environ['HOME'],'utf-8')+u"/litebook/shared"
#if the path is not writeable, restore to default value
if not os.access(GlobalConfig['ShareRoot'],os.W_OK | os.R_OK):
if MYOS == 'Windows':
GlobalConfig['ShareRoot']=os.environ['USERPROFILE'].decode('gbk')+u"\\litebook\\shared"
else:
GlobalConfig['ShareRoot']=unicode(os.environ['HOME'],'utf-8')+u"/litebook/shared"
try:
GlobalConfig['LTBNETRoot']=config.getboolean('settings','LTBNETRoot')
except:
GlobalConfig['LTBNETRoot']=GlobalConfig['ShareRoot']
try:
GlobalConfig['LTBNETPort']=config.getint('settings','LTBNETPort')
except:
GlobalConfig['LTBNETPort']=50200
try:
GlobalConfig['LTBNETID']=(config.get('settings','LTBNETID')).strip()
except:
GlobalConfig['LTBNETID']='NONE'
try:
GlobalConfig['InstallDefaultConfig']=config.getboolean('settings','installdefaultconfig')
except:
GlobalConfig['InstallDefaultConfig']=True
try:
GlobalConfig['lastweb']=config.get('settings','lastweb')
except:
GlobalConfig['lastweb']=''
try:
GlobalConfig['lastwebsearchkeyword']=config.get('settings','LastWebSearchKeyword')
except:
GlobalConfig['lastwebsearchkeyword']=''
try:
GlobalConfig['DAUDF']=config.getint('settings','DefaultActionUponDownloadFinished')
except:
GlobalConfig['DAUDF']=0
try:
GlobalConfig['EnableESC']=config.getboolean('settings','EnableESC')
except:
GlobalConfig['EnableESC']=False
try:
GlobalConfig['useproxy']=config.getboolean('settings','UseProxy')
except:
GlobalConfig['useproxy']=False
try:
GlobalConfig['proxyserver']=config.get('settings','ProxyServer')
except:
GlobalConfig['proxyserver']=''
try:
GlobalConfig['proxyport']=config.getint('settings','ProxyPort')
except:
GlobalConfig['proxyport']=0
try:
GlobalConfig['proxyuser']=config.get('settings','ProxyUser')
except:
GlobalConfig['proxyuser']=''
try:
GlobalConfig['proxypass']=config.get('settings','ProxyPass')
except:
GlobalConfig['proxypass']=''
if MYOS != 'Windows':
GlobalConfig['ConfigDir']=unicode(os.environ['HOME'],'utf-8')+u'/litebook/'
else:
GlobalConfig['ConfigDir']=os.environ['APPDATA'].decode('gbk')
try:
GlobalConfig['LastDir']=config.get('settings','LastDir')
except:
if MYOS == 'Windows':
GlobalConfig['LastDir']=os.path.dirname(AnyToUnicode(os.path.abspath(sys.argv[0])))
else:
GlobalConfig['LastDir']=os.environ['HOME'].decode('utf-8')
if GlobalConfig['LastDir'].strip()=='' or os.path.isdir(GlobalConfig['LastDir'])==False:
if MYOS == 'Windows':
GlobalConfig['LastDir']=os.path.dirname(AnyToUnicode(os.path.abspath(sys.argv[0])))
else:
GlobalConfig['LastDir']=os.environ['HOME'].decode('utf-8')
if MYOS == 'Windows':
GlobalConfig['IconDir']=os.path.dirname(AnyToUnicode(os.path.abspath(sys.argv[0])))+u"\\icon"
else:
GlobalConfig['IconDir']=cur_file_dir()+u"/icon"
try:
GlobalConfig['defaultsavedir']=config.get('settings','defaultsavedir')
except:
GlobalConfig['defaultsavedir']=GlobalConfig['LastDir']
try:
GlobalConfig['numberofthreads']=config.getint('settings','numberofthreads')
except:
GlobalConfig['numberofthreads']=10
try:
GlobalConfig['LoadLastFile']=config.getboolean('settings','LoadLastFile')
except:
GlobalConfig['LoadLastFile']=True
try:
GlobalConfig['AutoScrollInterval']=config.getfloat('settings','AutoScrollInterval')
except:
GlobalConfig['AutoScrollInterval']=12000
try:
GlobalConfig['MaxBookDB']=config.getint('settings','MaxBookDB')
except:
GlobalConfig['MaxBookDB']=50
try:
GlobalConfig['HideToolbar']=config.getboolean('settings','HideToolbar')
except:
GlobalConfig['HideToolbar']=False
try:
GlobalConfig['MaxOpenedFiles']=config.getint('settings','MaxOpenedFiles')
except:
GlobalConfig['MaxOpenedFiles']=5
try:
GlobalConfig['RemindInterval']=config.getint('settings','RemindInterval')
except:
GlobalConfig['RemindInterval']=60
try:
GlobalConfig['EnableSidebarPreview']=config.getboolean('settings','EnableSidebarPreview')
except:
GlobalConfig['EnableSidebarPreview']=True
try:
GlobalConfig['VerCheckOnStartup']=config.getboolean('settings','VerCheckOnStartup')
except:
GlobalConfig['VerCheckOnStartup']=True
try:
GlobalConfig['HashTitle']=config.getboolean('settings','HashTitle')
except:
GlobalConfig['HashTitle']=False
try:
GlobalConfig['ShowAllFileInSidebar']=config.getboolean('settings','ShowAllFileInSidebar')
except:
GlobalConfig['ShowAllFileInSidebar']=True
try:
GlobalConfig['vbookpunc']=config.getboolean('settings','vbookpunc')
except:
GlobalConfig['vbookpunc']=True
try:
t_flist=(config.items('LastOpenedFiles'))
di={}
for f in t_flist:
di[f[0]]=f[1]
flist=[]
tmp_newl=di.keys()
newl=[]
for n in tmp_newl:
newl.append(int(n))
newl.sort()
for k in newl:
flist.append((k,di[str(k)]))
i=1
for f in flist:
if i>GlobalConfig['MaxOpenedFiles']: break
else:
i+=1
if f[1].find(u'|')==-1:OpenedFileList.append({'file':f[1],'type':'normal','zfile':''})
else:
(zfile,filename)=f[1].split('|',2)
OpenedFileList.append({'file':filename,'type':'zip','zfile':zfile})
except:
OpenedFileList=[]
try:
GlobalConfig['LastPos']=config.getint('LastPosition','pos')
filename=config.get('LastPosition','lastfile')
if filename.find(u"*")==-1:
if filename.find(u"|")<>-1:
GlobalConfig['LastZipFile']=filename.split(u"|")[0]
GlobalConfig['LastFile']=filename.split(u"|")[1]
else:
GlobalConfig['LastFile']=filename
GlobalConfig['LastZipFile']=''
else:
GlobalConfig['LastFile']=filename
GlobalConfig['LastZipFile']=''
except:
GlobalConfig['LastFile']=''
GlobalConfig['LastZipFile']=''
GlobalConfig['LastPos']=0
try:
blist=(config.items('BookMark'))
bookmark={}
for bk in blist:
bk_info=bk[1].split(u'?',2)
BookMarkList.append({'filename':bk_info[0],'pos':int(bk_info[1]),'line':bk_info[2]})
except:
BookMarkList=[]
#Read Font and Color
try:
ft_list=(config.items('Appearance'))
gen_last=False
for ft in ft_list:
name=ft[0]
f=ft[1].split('|')
if name=='last':
GlobalConfig['CurFont']=wx.Font(int(f[0]),int(f[1]),int(f[2]),int(f[3]),eval(f[4]),f[5],int(f[6]))
GlobalConfig['CurFColor']=eval(f[7])
GlobalConfig['CurBColor']=eval(f[8])
if len(f)>9:
if f[9]<>'None':
GlobalConfig['backgroundimg']=f[9]
else:
GlobalConfig['backgroundimg']=None
GlobalConfig['showmode']=f[10]
GlobalConfig['backgroundimglayout']=f[11]
GlobalConfig['underline']=eval(f[12])
GlobalConfig['underlinestyle']=int(f[13])
GlobalConfig['underlinecolor']=str2list(f[14])
GlobalConfig['pagemargin']=int(f[15])
GlobalConfig['bookmargin']=int(f[16])
GlobalConfig['vbookmargin']=int(f[17])
GlobalConfig['centralmargin']=int(f[18])
GlobalConfig['linespace']=int(f[19])
GlobalConfig['vlinespace']=int(f[20])
gen_last=True
else:
l={}
l['font']=wx.Font(int(f[0]),int(f[1]),int(f[2]),int(f[3]),eval(f[4]),f[5],int(f[6]))
l['fcolor']=eval(f[7])
l['bcolor']=eval(f[8])
if len(f)>9:
if f[9]<>'None':
l['backgroundimg']=f[9]
else:
l['backgroundimg']=None
l['showmode']=f[10]
l['backgroundimglayout']=f[11]
l['underline']=eval(f[12])
l['underlinestyle']=int(f[13])
l['underlinecolor']=str2list(f[14])
l['pagemargin']=int(f[15])
l['bookmargin']=int(f[16])
l['vbookmargin']=int(f[17])
l['centralmargin']=int(f[18])
l['linespace']=int(f[19])
l['vlinespace']=int(f[20])
if len(f)==22:
l['name']=f[21]
else:
l['name']=name
l['config']=ft[1]
ThemeList.append(l)
except:
GlobalConfig['CurFont']=wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "")
GlobalConfig['CurFColor']=(0,0,0,0)
GlobalConfig['CurBColor']='LIGHT BLUE'
GlobalConfig['backgroundimg']="default.jpg"
GlobalConfig['backgroundimglayout']='tile'
GlobalConfig['showmode']='paper'
GlobalConfig['underline']=True
GlobalConfig['underlinecolor']='GREY'
GlobalConfig['underlinestyle']=wx.DOT
GlobalConfig['pagemargin']=50
GlobalConfig['bookmargin']=50
GlobalConfig['vbookmargin']=50
GlobalConfig['centralmargin']=20
GlobalConfig['linespace']=5
GlobalConfig['vlinespace']=15
if gen_last==False:
GlobalConfig['CurFont']=wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "")
GlobalConfig['CurFColor']=(0,0,0,0)
GlobalConfig['CurBColor']='LIGHT BLUE'
GlobalConfig['backgroundimg']="default.jpg"
GlobalConfig['backgroundimglayout']='tile'
GlobalConfig['showmode']='paper'
GlobalConfig['underline']=True
GlobalConfig['underlinecolor']='GREY'
GlobalConfig['underlinestyle']=wx.DOT
GlobalConfig['pagemargin']=50
GlobalConfig['bookmargin']=50
GlobalConfig['vbookmargin']=50
GlobalConfig['centralmargin']=20
GlobalConfig['linespace']=5
GlobalConfig['vlinespace']=15
#Read BookDB
try:
bk_list=(config.items('BookDB'))
for bk in bk_list:
BookDB.append({'key':bk[0],'pos':int(bk[1])})
except:
BookDB=[]
if MYOS != "Windows":
if os.path.isdir(GlobalConfig['ConfigDir']+u'/litebook_tmp/')==False:
cmd_line=[]
cmd_line.append('rm')
cmd_line.append('-f')
cmd_line.append(GlobalConfig['ConfigDir']+u'/litebook_tmp')
subprocess.call(cmd_line)
cmd_line=[]
cmd_line.append('mkdir')
cmd_line.append('-p')
cmd_line.append(GlobalConfig['ConfigDir']+u'/litebook_tmp')
subprocess.call(cmd_line)
else:
tmp_list=glob.glob(GlobalConfig['ConfigDir']+u'/litebook_tmp/*')
for f in tmp_list:
try:
os.remove(f)
except:
return
#print os.path.abspath(GlobalConfig['IconDir'])
def writeConfigFile(lastpos):
global GlobalConfig,OpenedFileList,load_zip,current_file,current_zip_file,OnScreenFileList,BookMarkList,ThemeList,BookDB,HOSTNAME
# save settings
config = MyConfig()
config.add_section('settings')
config.set('settings','vbookpunc',unicode(GlobalConfig['vbookpunc']))
config.set('settings','LastDir',GlobalConfig['LastDir'])
config.set('settings','LoadLastFile',unicode(GlobalConfig['LoadLastFile']))
config.set('settings','AutoScrollInterval',unicode(GlobalConfig['AutoScrollInterval']))
config.set('settings','MaxOpenedFiles',unicode(GlobalConfig['MaxOpenedFiles']))
config.set('settings','MaxBookDB',unicode(GlobalConfig['MaxBookDB']))
config.set('settings','RemindInterval',unicode(GlobalConfig['RemindInterval']))
config.set('settings','EnableSidebarPreview',unicode(GlobalConfig['EnableSidebarPreview']))
config.set('settings','VerCheckOnStartup',unicode(GlobalConfig['VerCheckOnStartup']))
config.set('settings','HashTitle',unicode(True))
config.set('settings','ShowAllFileInSidebar',unicode(GlobalConfig['ShowAllFileInSidebar']))
config.set('settings','HideToolbar',unicode(GlobalConfig['HideToolbar']))
config.set('settings','ProxyServer',unicode(GlobalConfig['proxyserver']))
config.set('settings','EnableESC',unicode(GlobalConfig['EnableESC']))
config.set('settings','ProxyPort',unicode(GlobalConfig['proxyport']))
config.set('settings','ProxyUser',unicode(GlobalConfig['proxyuser']))
config.set('settings','ProxyPass',unicode(GlobalConfig['proxypass']))
config.set('settings','UseProxy',unicode(GlobalConfig['useproxy']))
config.set('settings','DefaultActionUponDownloadFinished',unicode(GlobalConfig['DAUDF']))
config.set('settings','LastWebSearchKeyword',unicode(GlobalConfig['lastwebsearchkeyword']))
config.set('settings','defaultsavedir',unicode(GlobalConfig['defaultsavedir']))
config.set('settings','numberofthreads',unicode(GlobalConfig['numberofthreads']))
config.set('settings','lastweb',unicode(GlobalConfig['lastweb']))
config.set('settings','installdefaultconfig',unicode(GlobalConfig['InstallDefaultConfig']))
config.set('settings','ShareRoot',unicode(GlobalConfig['ShareRoot']))
config.set('settings','LTBNETRoot',unicode(GlobalConfig['LTBNETRoot']))
if 'kadp_ctrl' in GlobalConfig:
(lport,nodeids)=GlobalConfig['kadp_ctrl'].getinfo(False)
config.set('settings','LTBNETID',nodeids)
config.set('settings','LTBNETPort',unicode(GlobalConfig['LTBNETPort']))
config.set('settings','RunWebserverAtStartup',unicode(GlobalConfig['RunWebserverAtStartup']))
config.set('settings','RunUPNPAtStartup',unicode(GlobalConfig['RunUPNPAtStartup']))
config.set('settings','EnableLTBNET',unicode(GlobalConfig['EnableLTBNET']))
config.set('settings','ServerPort',unicode(GlobalConfig['ServerPort']))
config.set('settings','mDNS_interface',unicode(GlobalConfig['mDNS_interface']))
config.set('settings','toolsize',unicode(GlobalConfig['ToolSize']))
config.set('settings','BookDirPrefix',unicode(GlobalConfig['BookDirPrefix']))
# save opened files
config.add_section('LastOpenedFiles')
i=0
for f in OpenedFileList:
if f['type']=='normal':
fname=getBookPath(f['file'])
config.set('LastOpenedFiles',unicode(i),fname)
else:
fname=getBookPath(f['zfile'])
config.set('LastOpenedFiles',unicode(i),fname+u"|"+f['file'])
i+=1
# save last open files and postion
config.add_section('LastPosition')
config.set('LastPosition','pos',unicode(lastpos))
if OnScreenFileList.__len__()==1: #if there are multiple files opening, then last postition can not be remembered
if not load_zip or current_zip_file=='':
fname=getBookPath(current_file)
config.set('LastPosition','lastfile',fname)
else:
fname=getBookPath(current_zip_file)
config.set('LastPosition','lastfile',fname+u"|"+current_file)
else:
tstr=u''
for onscrfile in OnScreenFileList:
tstr+=onscrfile[0]+u'*'
tstr=tstr[:-1]
config.set('LastPosition','lastfile',tstr)
# save bookmarks
config.add_section('BookMark')
bookmark={}
i=0
for bookmark in BookMarkList:
config.set('BookMark',unicode(i),bookmark['filename']+u'?'+unicode(bookmark['pos'])+u'?'+bookmark['line'])
i+=1
# Save font and color
config.add_section('Appearance')
ft=GlobalConfig['CurFont']
save_str=unicode(ft.GetPointSize())+u'|'+unicode(ft.GetFamily())+u'|'+unicode(ft.GetStyle())+u'|'+unicode(ft.GetWeight())+u'|'+unicode(ft.GetUnderlined())+u'|'+ft.GetFaceName()+u'|'+unicode(ft.GetDefaultEncoding())+u'|'+unicode(GlobalConfig['CurFColor'])+u'|'+unicode(GlobalConfig['CurBColor'])
save_str+=u'|'+unicode(GlobalConfig['backgroundimg'])
save_str+=u'|'+unicode(GlobalConfig['showmode'])
save_str+=u'|'+unicode(GlobalConfig['backgroundimglayout'])
save_str+=u'|'+unicode(GlobalConfig['underline'])
save_str+=u'|'+unicode(GlobalConfig['underlinestyle'])
save_str+=u'|'+unicode(GlobalConfig['underlinecolor'])
save_str+=u'|'+unicode(GlobalConfig['pagemargin'])
save_str+=u'|'+unicode(GlobalConfig['bookmargin'])
save_str+=u'|'+unicode(GlobalConfig['vbookmargin'])
save_str+=u'|'+unicode(GlobalConfig['centralmargin'])
save_str+=u'|'+unicode(GlobalConfig['linespace'])
save_str+=u'|'+unicode(GlobalConfig['vlinespace'])
config.set('Appearance','last',save_str)
# Save Theme List
for t in ThemeList:
config.set('Appearance',t['name'],t['config'])
# Save Book DB
config.add_section('BookDB')
for bk in BookDB:
config.set('BookDB',unicode(bk['key']),unicode(bk['pos']))
#write into litebook.ini
conffile=GlobalConfig['path_list']['conf']
ConfigFile=codecs.open(conffile,encoding='utf-8',mode='w')
config.write(ConfigFile)
ConfigFile.close()
return True
def getBookPath(fpath):
"""
return masked filepath
"""
if GlobalConfig['BookDirPrefix']=='':
return fpath
if os.path.commonprefix([GlobalConfig['BookDirPrefix'],fpath])==GlobalConfig['BookDirPrefix']:
plen=len(GlobalConfig['BookDirPrefix'])
fname=fpath[plen+1:]
else:
fname=fpath
return fname
def joinBookPath(fname):
"""
return joined(by prefix) full path of book
"""
if GlobalConfig['BookDirPrefix']=='' or os.path.isabs(fname):
return fname
return os.path.join(GlobalConfig['BookDirPrefix'],fname)
def UpdateOpenedFileList(filename,ftype,zfile=''):
#need to work on this function to support prefix
global OpenedFileList,GlobalConfig,SqlCon
fi={}
fi['type']=ftype
fi['file']=filename
fi['zfile']=zfile
if fi['type']=='normal':
fi['file']=getBookPath(fi['file'])
else:
fi['zfile']=getBookPath(fi['zfile'])
sqlstr="insert into book_history values ('"+unicode(fi['file'])+"','"+ftype+"','"+unicode(fi['zfile'])+"',"+str(time.time())+");"
try:
SqlCon.execute(sqlstr)
SqlCon.commit()
except:
return
for x in OpenedFileList:
if x['file']==fi['file']:
if x['type']=='normal':
OpenedFileList.remove(x)
OpenedFileList.insert(0,x)
return
else:
if x['zfile']==zfile:
OpenedFileList.remove(x)
OpenedFileList.insert(0,x)
return
OpenedFileList.insert(0,fi)
if OpenedFileList.__len__()>GlobalConfig['MaxOpenedFiles']:
i=0
delta=OpenedFileList.__len__()-GlobalConfig['MaxOpenedFiles']
while i<delta:
OpenedFileList.pop()
i+=1
def VersionCheck():
"""
Get latest version from offical website
return (internal_ver(float),text_ver(unicode),whatsnew(unicode)
"""
try:
f=urllib2.urlopen('http://code.google.com/p/litebook-project/wiki/LatestVer')
except:
return (False,False,False)
iver=False
tver=False
wtsnew=False
p1=re.compile('##########(.+)##########')
p2=re.compile('----------(.+)----------')
p3=re.compile('@@@@@@@@(.+)@@@@@@@@')
for line in f:
if line.find('##########') != -1:
iver=float(p1.search(line).group(1))
tver=p2.search(line).group(1).decode('utf-8')
wtsnew=p3.search(line).group(1).decode('utf-8')
wtsnew=wtsnew.replace('\\n','\n')
break
return (iver,tver,wtsnew)
##def VersionCheck(os):
## try:
## f=urllib.urlopen("http://code.google.com/p/litebook-project/wiki/UrlChecking")
## except:
## return False
## for line in f:
## if line.find('litebookwin')<>-1:
## line=line.strip()
## p=re.compile('<.*?>',re.S)
## line=p.sub('',line)
## info=line.split(' ')
## found_1=False
## found_2=False
## for word in info:
## if word.find('litebook'+os+'latestversion')<>-1:
## latest_ver=word.split('----')[1]
## found_1=True
## if word.find('litebook'+os+'downloadurl')<>-1 :
## download_url=word.split('----')[1]
## found_2=True
## if found_1==False or found_2==False:
## f.close()
## return False
## else:
## f.close()
## return (latest_ver,'http://'+download_url)
def htmname2uni(htm):
"""replace the HTML codepoint into unicode character"""
if htm[1]=='#':
try:
uc=unichr(int(htm[2:-1]))
return uc
except:
return htm
else:
try:
uc=unichr(htmlentitydefs.name2codepoint[htm[1:-1]])
return uc
except:
return htm
def htm2txt(inf):
""" filter out all html tags/JS script in input string, return a clean string"""
f_str=inf
#conver <p> to "\n"
p=re.compile('<\s*p\s*>',re.I)
f_str=p.sub('\n',f_str)
#conver <br> to "\n"
p=re.compile('<br.*?>',re.I)
f_str=p.sub('\n',f_str)
#conver "\n\r" to "\n"
p=re.compile('\n\r',re.S)
f_str=p.sub('\n',f_str)
#this is used to remove protection of http://www.jjwxc.net
p=re.compile('<font color=.*?>.*?</font>',re.I|re.S)
f_str=p.sub('',f_str)
#this is used to remove protection of HJSM
p=re.compile("<\s*span\s*class='transparent'\s*>.*?<\s*/span\s*>",re.I|re.S)
f_str=p.sub('',f_str)
#remove <script xxxx>xxxx</script>
p=re.compile('<script.*?>.*?</script>',re.I|re.S)
f_str=p.sub('',f_str)
#remove <style></style>
p=re.compile('<style>.*?</style>',re.I|re.S)
f_str=p.sub('',f_str)
#remove <option>
p=re.compile('<option.*?>.*?</option>',re.I|re.S)
f_str=p.sub('',f_str)
#remove <xxx>
p=re.compile('<.*?>',re.S)
f_str=p.sub('',f_str)
#remove <!-- -->
p=re.compile('<!--.*?-->',re.S)
f_str=p.sub('',f_str)
#conver into space
p=re.compile(' ',re.I)
f_str=p.sub(' ',f_str)
#convert html codename like """ into real character
p=re.compile("&#?\w{1,9};")
str_list=p.findall(f_str)
e_list=[]
for x in str_list:
if x not in e_list:
e_list.append(x)
for x in e_list:
f_str=f_str.replace(x,htmname2uni(x))
#convert more than 5 newline in a row into one newline
f_str=f_str.replace("\r\n","\n")
p=re.compile('\n{5,}')
f_str=p.sub('\n',f_str)
return f_str
def jarfile_decode(infile):
global MYOS
if not zipfile.is_zipfile(infile):
return False
zfile=zipfile.ZipFile(infile)
if MYOS == 'Windows':
cache_dir=os.environ['USERPROFILE'].decode('gbk')+u"\\litebook\\cache"
else:
cache_dir=unicode(os.environ['HOME'],'utf-8')+u"/litebook/cache"
fp=open(infile,'rb')
s=fp.read()
m=hashlib.md5()
m.update(s)
c_name=m.hexdigest()
if os.path.isfile(cache_dir+os.sep+c_name):
ffp=codecs.open(cache_dir+os.sep+c_name,encoding='gbk',mode='r')
try:
s=ffp.read()
if s<>'' and s<>None and s<>False:
ffp.close()
return s
else:
ffp.close()
except:
ffp.close()
i=1
content=u''
while True:
try:
txt=zfile.read(str(i))
except:
break
content+=txt.decode('utf-16','ignore')
i+=1
s=content
s=s.encode('gbk','ignore')
s=s.decode('gbk')
CFile=codecs.open(cache_dir+os.sep+c_name,encoding='gbk',mode='w')
CFile.write(s)
CFile.close()
return s
def epubfile_decode(infile):
#decode epub file,return unicode
global lb_hash
if not zipfile.is_zipfile(infile):return False
zfile=zipfile.ZipFile(infile)
if MYOS == 'Windows':
cache_dir=os.environ['USERPROFILE'].decode('gbk')+u"\\litebook\\cache"
else:
cache_dir=unicode(os.environ['HOME'],'utf-8')+u"/litebook/cache"
fp=open(infile,'rb')
s=fp.read()
m=hashlib.md5()
m.update(s)
c_name=m.hexdigest()
if os.path.isfile(cache_dir+os.sep+c_name):
ffp=codecs.open(cache_dir+os.sep+c_name,encoding='gbk',mode='r')
try:
s=ffp.read()
if s<>'' and s<>None and s<>False:
ffp.close()
return s
else:
ffp.close()
except:
ffp.close()
container_xml = zfile.open('META-INF/container.xml')
context = etree.iterparse(container_xml)
opfpath='OPS/content.opf'
for action, elem in context:
if elem.tag[-8:].lower()=='rootfile':
try:
opfpath=elem.attrib['full-path']
except:
break
break
#print "opfpath is ",opfpath
opf_file = zfile.open(opfpath)
context = etree.iterparse(opf_file)
toc_path = None
for action, elem in context:
#print elem.tag,'---',elem.attrib
attr_list={}
for k,v in elem.attrib.items():
attr_list[k.lower()]=v
if 'media-type' in attr_list and attr_list['media-type'].lower()=='application/x-dtbncx+xml':
toc_path = attr_list['href']
break
#print "toc_path is ",toc_path
if toc_path == None:
return False
toc_path = os.path.dirname(opfpath)+'/'+toc_path
#print "toc_path is ",toc_path
if toc_path[0]=='/':
toc_path=toc_path[1:]
#print "toc_path is ",toc_path
toc_file = zfile.open(toc_path)
context = etree.iterparse(toc_file)
clist=[]
for action, elem in context:
if elem.tag.split('}')[1].lower()=='content':
attr_list={}
for k,v in elem.attrib.items():
attr_list[k.lower()]=v
if 'src' in attr_list:
clist.append(os.path.dirname(toc_path)+'/'+attr_list['src'])
## i=1
#print "clist is ",clist
content=u''
## clist=[]
## for fname in zfile.namelist():
## fext=os.path.splitext(fname)[1].lower()
## if fext=='.ncx':
## dirfile=fname
## if fext in ['.xml','.html','.htm','.xhtml']:
## if fname<>'META-INF/container.xml':
## clist.append(fname)
## fp=zfile.open(dirfile)
toc_file = zfile.open(toc_path)
instr=toc_file.read()
gc=gcepub.GCEPUB(instr)
gc.parser()
rlist=gc.GetRList()
clist.sort(cmp=cmp_filename)
for fname in clist:
if fname[0]=='/':
fname=fname[1:]
try:
fp=zfile.open(fname,"r")
except:break
txt=fp.read()
if not isinstance(fname,unicode):fname=fname.decode('gbk')
try:
chapter=rlist[os.path.basename(fname)]
except:
chapter='LiteBook'
content+=lb_hash+chapter+'\n'
try:
content+=txt.decode('utf-8','ignore')
except:
content+=txt.decode('utf-16','ignore')
s=htm2txt(content)
s=s.encode('gbk','ignore')
s=s.decode('gbk')
CFile=codecs.open(cache_dir+os.sep+c_name,encoding='gbk',mode='w')
CFile.write(s)
CFile.close()
return s
import struct
import zlib
import sys
def umd_field_decode(fp,pos):
"""" This function is to decode each field inside umd file"""
fp.seek(pos)
field_type_list={2:'title',3:'author',4:'year',5:'month',6:'day',7:'gender',8:'publisher',9:'vendor'}
dtype=struct.unpack('=H',fp.read(2))
if dtype[0]<>11:
field_type=field_type_list[dtype[0]]
field_value=u''
i=pos+3
fp.seek(i,0)
field_len=int(ord(fp.read(1)))
field_len=field_len-5
i+=1
fp.seek(i,0)
m=i
while m<i+field_len:
onechar=unichr(struct.unpack('=H',fp.read(2))[0])
field_value+=onechar
m+=2
fp.seek(m)
else:
field_type='content'
pos+=4
fp.seek(pos,0)
field_len=struct.unpack('=I',fp.read(4))[0]
pos+=5
fp.seek(pos,0)
## print field_len
chapter_type=struct.unpack('=H',fp.read(2))[0]
## print hex(chapter_type)
pos+=4
fp.seek(pos,0)
r1=struct.unpack('=I',fp.read(4))[0]
## print "random-1 is "+str(hex(r1))
pos+=5
fp.seek(pos,0)
r2=struct.unpack('=I',fp.read(4))[0]
## print "random-2 is "+str(hex(r2))
pos+=4
fp.seek(pos,0)
offset_len=struct.unpack('=I',fp.read(4))[0]-9
## print "offset_len is "+str(offset_len)
i=0
pos+=4
fp.seek(pos,0)
chapter_offset=[]
while i<offset_len:
chapter_offset.append(struct.unpack('=I',fp.read(4))[0])
## print chapter_offset
i+=4
fp.seek(pos+i,0)
## print "chapter offsets are:"
## print chapter_offset
pos+=offset_len+1
fp.seek(pos,0)
ch_t_type=struct.unpack('=H',fp.read(2))[0]
## print "ch_title_type is "+str(hex(ch_t_type))
pos+=4
fp.seek(pos,0)
r3=struct.unpack('=I',fp.read(4))[0]
## print "random-3 is "+str(hex(r3))
pos+=5
fp.seek(pos,0)
r4=struct.unpack('=I',fp.read(4))[0]
## print "random-4 is "+str(hex(r4))
pos+=4
fp.seek(pos,0)
ch_title_len=struct.unpack('=I',fp.read(4))[0]-9
m=0
pos+=4
fp.seek(pos,0)
while m<ch_title_len:
t_len=ord(struct.unpack('=c',fp.read(1))[0])
pos+=1
fp.seek(pos,0)
n=pos
t_val=u''
while n<pos+t_len:
onechar=unichr(struct.unpack('=H',fp.read(2))[0])
t_val+=onechar
n+=2
fp.seek(n)
## print t_val.encode('gbk',"replace")
m+=1+t_len
pos+=t_len
fp.seek(pos,0)
## print "chapter title len is "+str(ch_title_len)
fp.seek(pos,0)
t_tag=fp.read(1)
content=u''
while t_tag=='$':
pos+=5
fp.seek(pos,0)
content_len=struct.unpack(GetPint(),fp.read(4))[0]-9
## print "content_len is:"+str(content_len)
#content_len=192450
pos+=4
fp.seek(pos,0)
x=content_len/65535
y=content_len%65535
n=0
zstr=''
while n<x:
xx=fp.read(65535)
zstr+=xx
pos+=65535
fp.seek(pos,0)
n+=1
zstr+=fp.read(y)
pos+=y
z_len=zstr.__len__()
## print "z_len is "+str(z_len)
ystr=zlib.decompress(zstr)
y_len=ystr.__len__()
## print "y_len is "+str(y_len)
ystr=ystr.replace('\x29\x20','\n\x00')
content+=ystr.decode('utf-16','ignore')
## sys.exit()
## n=0
## while n<y_len:
## onechar=unichr(struct.unpack('H',ystr[n:n+2])[0])
## if onechar==u'\u2029':
## onechar=u'\n'
## content+=onechar
## n+=2
#print content.encode('GBK','replace')
fp.seek(pos,0)
t_tag=fp.read(1)
## print t_tag
#print content.encode('GBK','ignore')
fp.seek(pos,0)
if fp.read(1)=='#':
pos+=1
fp.seek(pos,0)
m_tag=struct.unpack('=H',fp.read(2))[0]
else:
m_tag=0
while m_tag<>0xc:
if m_tag==0xf1:
pos+=20
else:
if m_tag==0xa:
pos+=4
fp.seek(pos,0)
R1=struct.unpack('=I',fp.read(4))[0]
## print "Random-1 is "+str(hex(R1))
pos+=4
else:
if m_tag==0x81:
pos+=8
fp.seek(pos,0)
## print fp.read(1)
pos+=5
fp.seek(pos,0)
page_count=struct.unpack('=I',fp.read(4))[0]-9
pos+=page_count+4
else:
if m_tag==0x87:
pos+=15
fp.seek(pos,0)
offset_len=struct.unpack('=I',fp.read(4))[0]-9
## print "offset_len is "+str(offset_len)
## i=0
pos+=4+offset_len
## fp.seek(pos,0)
## chapter_offset=[]
## while i<offset_len:
## chapter_offset.append(struct.unpack('I',fp.read(4))[0])
## i+=4
## fp.seek(pos+i,0)
## print "chapter offsets are:"
## print chapter_offset
else:
if m_tag==0x82:
pos+=14
fp.seek(pos,0)
cover_len=struct.unpack(GetPint(),fp.read(4))[0]-9
pos+=cover_len+4
else:
if m_tag==0xb:
pos+=8
else:
fp.seek(pos,0)
t_tag=fp.read(1)
while t_tag=='$':
pos+=5
fp.seek(pos,0)
content_len=struct.unpack(GetPint(),fp.read(4))[0]-9
## print "content_len is:"+str(content_len)
pos+=4
fp.seek(pos,0)
x=content_len/65535
y=content_len%65535
n=0
zstr=''
while n<x:
xx=fp.read(65535)
zstr+=xx
pos+=65535
fp.seek(pos,0)
n+=1
zstr+=fp.read(y)
pos+=y
z_len=zstr.__len__()
## print "z_len is "+str(z_len)
ystr=zlib.decompress(zstr)
y_len=ystr.__len__()
## print "y_len is "+str(y_len)
ystr=ystr.replace('\x29\x20','\n\x00')
content+=ystr.decode('utf-16','ignore')
fp.seek(pos,0)
t_tag=fp.read(1)
## print t_tag
#print content.encode('GBK','ignore')
fp.seek(pos,0)
xxx=fp.read(1)
if xxx=='#':
pos+=1
fp.seek(pos,0)
m_tag=struct.unpack('=H',fp.read(2))[0]
else:
m_tag=0
## print type(content)
return ('Content',content,pos,True)
return (field_type,field_value,m,False)
def umd_decode(infile):
"""This function will decode a umd file, and return a dict include all the fields"""
umdinfo={}
f=open(infile,'rb')
bytes=f.read(4)
tag=struct.unpack('=cccc',bytes)
if tag<>('\x89', '\x9b', '\x9a', '\xde'): return False # check if the file is the umd file
f.seek(9)
ftype=ord(f.read(1))
if ftype<>0x1: return False #0x1 means txt,0x2 mean picture
(u_type,u_value,pos,end)=umd_field_decode(f,13)
umdinfo[u_type]=u_value
i=1
end=False
while end<>True:
(u_type,u_value,pos,end)=umd_field_decode(f,pos+1)
umdinfo[u_type]=u_value
## print umdinfo['author']
## print umdinfo['title']
## print umdinfo['publisher']
## print umdinfo['vendor']
return umdinfo
def HumanSize(ffsize):
fsize=float(ffsize)
if fsize>=1000000000.0:
r=float(fsize)/1000000000.0
return '%(#).2f' % {'#':r}+' GB'
else:
if fsize>=1000000.0:
r=float(fsize)/1000000.0
return '%(#).2f' % {'#':r}+' MB'
else:
if fsize>=1000.0:
r=float(fsize)/1000.0
return '%(#).2f' % {'#':r}+' KB'
else:
return '< 1KB'
def unrar(rfile,filename):
###This funtion will use unrar command line to extract file from rar file"""
global GlobalConfig
cmd_line=[]
cmd_line.append(u"unrar")
cmd_line.append('x')
cmd_line.append('-y')
cmd_line.append('-inul')
cmd_line.append(rfile)
cmd_line.append(filename)
cmd_line.append(GlobalConfig['ConfigDir']+"/litebook_tmp/")
if subprocess.call(cmd_line)==0:
if isinstance(filename,str):
filename=filename.decode('gbk')
fp=open(GlobalConfig['ConfigDir']+u"/litebook_tmp/"+filename,'r')
txt=fp.read()
fp.close()
return txt
else:
return False
def ch2num(ch):
if not isinstance(ch,unicode):
ch=ch.decode("gbk")
chnum_str=u'(零|一|二|三|四|五|六|七|八|九|十|百|千|万|0|1|2|3|4|5|6|7|8|9)'
ch_ten_str=u'(十|百|千|万)'
ch_ten_dict={u'十':u'0',u'百':u'00',u'千':u'000',u'万':u'0000',}
ch_dict={u'零':u'0',u'一':u'1',u'二':u'2',u'三':u'3',u'四':u'4',u'五':u'5',u'六':u'6',u'七':u'7',u'八':u'8',u'九':u'9',}
p=re.compile(u'第'+chnum_str+u'+(章|节|部|卷)',re.L|re.U)
m_list=p.finditer(ch)
# mid_str=m.string[m.start():m.end()]
rr=[]
#print m_list
for pr in m_list:
mid_str=pr.string[pr.start():pr.end()]
mid_str=mid_str[1:-1]
if mid_str[0]==u'十':
if len(mid_str)<>1:
mid_str=mid_str.replace(u'十',u'1',1)
else:
rr.append(10)
break
if mid_str[-1:]==u'万':
try:
mid_str+=ch_ten_dict[mid_str[-2:-1]]+u'0000'
except:
mid_str+=u'0000'
else:
try:
mid_str+=ch_ten_dict[mid_str[-1:]]
except:
pass
p=re.compile(ch_ten_str,re.L|re.U)
mid_str=p.sub('',mid_str)
for key,val in ch_dict.items():
mid_str=mid_str.replace(key,val)
rr.append(long(mid_str))
i=0
x=0
while i<len(rr):
x+=rr[i]*math.pow(10,5*(3-i))
i+=1
return long(x)
class ZipFileDialog(wx.Dialog):
"""ZIP/RAR file list dialog, using TreeCtrl"""
selected_files=[]
openmethod='load'
def __init__(self,parent,zipfilename):
#begin wxGlade: ZipFileDialog.__init__
#kwds["style"] = wx.DEFAULT_DIALOG_STYLE
self.file_icon_list={}
self.selected_files=[]
wx.Dialog.__init__(self, parent,-1,'')
self.tree_ctrl_1 = wx.TreeCtrl(self, -1, style=wx.TR_HAS_BUTTONS|wx.TR_LINES_AT_ROOT|wx.TR_MULTIPLE|wx.TR_MULTIPLE|wx.TR_DEFAULT_STYLE|wx.SUNKEN_BORDER)
self.button_2 = wx.Button(self, -1, u"打开")
self.button_3 = wx.Button(self, -1, u"取消")
self.button_4 = wx.Button(self, -1, u"添加")
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnOpen, self.tree_ctrl_1)
self.Bind(wx.EVT_BUTTON, self.OnOpen, self.button_2)
self.Bind(wx.EVT_BUTTON, self.OnCancell, self.button_3)
self.Bind(wx.EVT_BUTTON, self.OnAppend, self.button_4)
# end wxGlade
self.tree_ctrl_1.Bind(wx.EVT_CHAR,self.OnKey)
self.Bind(wx.EVT_ACTIVATE,self.OnWinActive)
root=self.tree_ctrl_1.AddRoot(zipfilename)
self.tree_ctrl_1.SetItemImage(root,0,wx.TreeItemIcon_Normal)
if os.path.splitext(zipfilename)[1].lower()== ".zip":
try:
zfile=zipfile.ZipFile(zipfilename)
except:
dlg = wx.MessageDialog(None, zipfilename+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return
for zz in zfile.namelist():
self.AddLeaf(zz,self.tree_ctrl_1)
else:
try:
rfile=rarfile.RarFile(zipfilename)
except:
dlg = wx.MessageDialog(None, zipfilename+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return
rarfile_list=[]
rname_list=[]
for line in rfile.namelist():
line=line.replace('\\','/')
#line=line.decode('GBK')
# if isinstance(line,unicode):
# line=line.encode('gbk')
if rfile.getinfo(line).isdir():
# if isinstance(line,str):
# line=line.decode('gbk')
line+="/"
rarfile_list.append((line.replace("plugi","/")))
for rr in rarfile_list:
self.AddLeaf(rr,self.tree_ctrl_1)
self.image_list=wx.ImageList(16,16,mask=False,initialCount=5)
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/ClosedFolder.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["closedfolder"]=0
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/OpenFolder.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["openfolder"]=1
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/file.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["file"]=2
self.tree_ctrl_1.SetImageList(self.image_list)
def __set_properties(self):
# begin wxGlade: ZipFileDialog.__set_properties
self.SetTitle(u"打开压缩包中的文件")
self.SetSize((400, 400))
# end wxGlade
def __do_layout(self):
# begin wxGlade: ZipFileDialog.__do_layout
sizer_5 = wx.BoxSizer(wx.VERTICAL)
sizer_6 = wx.BoxSizer(wx.HORIZONTAL)
sizer_5.Add(self.tree_ctrl_1, 1, wx.EXPAND, 0)
sizer_6.Add((20, 20), 1, 0, 0)
sizer_6.Add(self.button_4, 0, 0, 0)
sizer_6.Add((20, 20), 1, 0, 0)
sizer_6.Add(self.button_2, 0, 0, 0)
sizer_6.Add((20, 20), 1, 0, 0)
sizer_6.Add(self.button_3, 0, 0, 0)
sizer_6.Add((20, 20), 1, 0, 0)
sizer_5.Add(sizer_6, 0, wx.EXPAND, 0)
self.SetSizer(sizer_5)
self.Layout()
# end wxGlade
def OnOpen(self, event): # wxGlade: ZipFileDialog.<event_handler>
item_selected=self.tree_ctrl_1.GetSelections()
for item in item_selected:
if self.tree_ctrl_1.GetChildrenCount(item)==0:
if isinstance(self.tree_ctrl_1.GetPyData(item),str):
s_item=self.tree_ctrl_1.GetPyData(item).decode('gbk')
else:
s_item=self.tree_ctrl_1.GetPyData(item)
self.selected_files.append(s_item)
if self.selected_files==[]:
event.Skip()
return False
else:
self.Close()
def OnCancell(self, event): # wxGlade: ZipFileDialog.<event_handler>
self.Destroy()
def OnAppend(self, event): # wxGlade: ZipFileDialog.<event_handler>
item_selected=self.tree_ctrl_1.GetSelections()
for item in item_selected:
full_name=''
while item<>self.tree_ctrl_1.GetRootItem():
full_name=self.tree_ctrl_1.GetItemText(item)+full_name
item=self.tree_ctrl_1.GetItemParent(item)
self.selected_files.append(full_name)
self.openmethod='append'
self.Close()
def AddLeaf(self,tree_item,tree):
try:
tree_item=tree_item.decode("gbk")
except:
pass
i_list=tree_item.split(u"/")
field_count=len(i_list)
m=1
if i_list[len(i_list)-1]=='':
i_list=i_list[:-1]
rt=tree.GetRootItem()
for i in i_list:
item,cookie=tree.GetFirstChild(rt)
found_r=False
while item:
if tree.GetItemText(item)==i:
rt=item
found_r=True
break
else:
item,cookie=tree.GetNextChild(rt,cookie)
if not found_r:
child_id=tree.AppendItem(rt,i)
if m<>field_count:
tree.SetItemImage(child_id,1,wx.TreeItemIcon_Normal)
else:
tree.SetItemImage(child_id,2,wx.TreeItemIcon_Normal)
tree.SetPyData(child_id,tree_item)
rt=child_id
m+=1
return
def OnKey(self,event):
key=event.GetKeyCode()
if key==wx.WXK_ESCAPE:
self.Destroy()
else:
event.Skip()
def OnWinActive(self,event):
if event.GetActive():self.tree_ctrl_1.SetFocus()
class MyFrame(wx.Frame,wx.lib.mixins.listctrl.ColumnSorterMixin):
buff=u''
currentTextAttr=wx.TextAttr()
search_str=''
search_flg=1
last_search_pos=0
showfullscr=False
autoscroll=False
Clock=True
current_pos=0
last_pos=0
slider=None
mousedelta=0
last_mouse_event=None
UpdateSidebar=False
SidebarPos=300 # inital postion value for dir sidebar
Formated=False
cur_catalog=None
func_list={
u'向上翻行':'self.text_ctrl_1.ScrollLine(-1)',
u'向下翻行':'self.text_ctrl_1.ScrollLine(1)',
u'向上翻页':'self.text_ctrl_1.ScrollP(-1)',
u'向下翻页':'self.text_ctrl_1.ScrollP(1)',
u'向上翻半页':'self.text_ctrl_1.ScrollHalfP(-1)',
u'向下翻半页':'self.text_ctrl_1.ScrollHalfP(1)',
u'前进10%':'self.text_ctrl_1.ScrollPercent(10,1)',
u'后退10%':'self.text_ctrl_1.ScrollPercent(10,-1)',
u'前进1%':'self.text_ctrl_1.ScrollPercent(1,1)',
u'后退1%':'self.text_ctrl_1.ScrollPercent(1,-1)',
u'跳到首页':'self.text_ctrl_1.ScrollTop()',
u'跳到结尾':'self.text_ctrl_1.ScrollBottom()',
u'文件列表':'self.Menu101(None)',
u'打开文件':'self.Menu102(None)',
u'另存为':'self.Menu108(None)',
u'关闭':'self.Menu103(None)',
u'上一个文件':'self.Menu104(None)',
u'下一个文件':'self.Menu105(None)',
u'搜索小说网站':'self.Menu110(None)',
u'重新载入插件':'self.Menu111(None)',
u'选项':'self.Menu106(None)',
u'退出':'self.Menu107(None)',
u'拷贝':'self.Menu202(None)',
u'查找':'self.Menu203(None)',
u'替换':'self.Menu206(None)',
u'查找下一个':'self.Menu204(None)',
u'查找上一个':'self.Menu205(None)',
u'纸张显示模式':'self.Menu601(None)',
u'书本显示模式':'self.Menu602(None)',
u'竖排书本显示模式':'self.Menu603(None)',
u'显示工具栏':'self.Menu501(None)',
u'放大工具栏':'self.Menu512(None)',
u'缩小工具栏':'self.Menu511(None)',
u'显示目录':'self.Menu509(None)',
u'全屏显示':'self.Menu503(None)',
u'显示文件侧边栏':'self.Menu502(None)',
u'自动翻页':'self.Menu505(None)',
u'智能分段':'self.Tool44(None)',
u'添加到收藏夹':'self.Menu301(None)',
u'整理收藏夹':'self.Menu302(None)',
u'简明帮助':'self.Menu401(None)',
u'版本更新内容':'self.Menu404(None)',
u'检查更新':'self.Menu403(None)',
u'关于':'self.Menu402(None)',
u'过滤HTML标记':'self.Tool41(None)',
u'切换为简体字':'self.Tool42(None)',
u'切换为繁体字':'self.Tool43(None)',
u'显示进度条':'self.ShowSlider()',
u'增大字体':'self.ChangeFontSize(1)',
u'减小字体':'self.ChangeFontSize(-1)',
u'清空缓存':'self.Menu112()',
u'最小化':'self.OnESC(None)',
u'生成EPUB文件':'self.Menu704()',
u'启用WEB服务器':'self.Menu705()',
u'检测端口是否开启':'self.Menu706()',
u'使用UPNP添加端口映射':'self.Menu707()',
u'显示章节侧边栏':'self.Menu510(None)',
u'搜索LTBNET':'self.Menu113(None)',
u'下载管理器':'self.Menu114(None)',
u'管理订阅':'self.Menu115(None)',
u'WEB下载管理器':'self.Menu116(None)',
u'跳转历史':'self.Menu513(None)',
}
def __init__(self,parent,openfile=None):
global GlobalConfig, MYOS
self.buff=u''
self.currentLine=0
self.toolbar_visable=True
self.FileHistoryDiag=None
self.cnsort=cnsort()
self.last_search_pos=False
self.title_str=u'litebook 轻巧读书'
self.AllowUpdate = False
self.streamID = 0
self.currentSID=self.streamID
# begin wxGlade: MyFrame.__init__
#kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self,parent,-1)
#display the splash
bitmap = wx.Bitmap(GlobalConfig['IconDir']+"/l2_splash.gif", wx.BITMAP_TYPE_ANY)
splash_frame = wx.SplashScreen(bitmap,wx.SPLASH_NO_TIMEOUT |wx.SPLASH_CENTRE_ON_SCREEN,3000,parent=self )
self.window_1 = wx.SplitterWindow(self, -1, style=wx.SP_3D|wx.SP_BORDER)
self.window_1_pane_2 = wx.Panel(self.window_1, -1)
self.window_1_pane_1 = wx.Panel(self.window_1, -1)
self.window_1_pane_mulu = wx.Panel(self.window_1, -1)
self.list_ctrl_1 = wx.ListCtrl(self.window_1_pane_1, -1, style=wx.LC_REPORT)
self.list_ctrl_mulu = wx.ListCtrl(self.window_1_pane_mulu, -1, style=wx.LC_REPORT)
self.list_ctrl_mulu.InsertColumn(0,u"章节名称",width=-1)
self.text_ctrl_1 = liteview.LiteView(self.window_1_pane_2)
self.window_1_pane_mulu.Hide()
self.window_1_pane_1.Hide()
#set droptarget
dt = FileDrop(self)
self.text_ctrl_1.SetDropTarget(dt)
#load apperance
if GlobalConfig['backgroundimg']<>'' and GlobalConfig['backgroundimg']<>None:
self.text_ctrl_1.SetBackgroundColour(GlobalConfig['CurBColor'])
self.text_ctrl_1.SetImgBackground(GlobalConfig['backgroundimg'],GlobalConfig['backgroundimglayout'])
else:
self.text_ctrl_1.SetBackgroundColour(GlobalConfig['CurBColor'])
self.text_ctrl_1.SetFColor(GlobalConfig['CurFColor'])
self.text_ctrl_1.SetFont(GlobalConfig['CurFont'])
self.text_ctrl_1.SetUnderline(GlobalConfig['underline'],GlobalConfig['underlinestyle'],GlobalConfig['underlinecolor'])
self.text_ctrl_1.SetSpace(GlobalConfig['pagemargin'],GlobalConfig['bookmargin'],GlobalConfig['vbookmargin'],GlobalConfig['centralmargin'],GlobalConfig['linespace'],GlobalConfig['vlinespace'])
self.text_ctrl_1.SetVbookpunc(GlobalConfig['vbookpunc'])
self.text_ctrl_2 = wx.TextCtrl(self.window_1_pane_1, -1, "",style=wx.TE_PROCESS_TAB|wx.TE_PROCESS_ENTER)
# Menu Bar
self.frame_1_menubar = wx.MenuBar()
wxglade_tmp_menu = wx.Menu()
wxglade_tmp_menu.Append(101, u"文件列表(&L)"+KeyMenuList[u'文件列表'], u"打开文件列表", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(102, u"打开文件(&O)"+KeyMenuList[u'打开文件'], u"打开文件", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(108, u"另存为...(&S)"+KeyMenuList[u'另存为'], u"打开文件", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(103, u"关闭(&C)"+KeyMenuList[u'关闭'], u"关闭当前文件", wx.ITEM_NORMAL)
wxglade_tmp_menu.AppendSeparator()
wxglade_tmp_menu_sub = wx.Menu()
wxglade_tmp_menu_sub.Append(104, u"上一个文件(&P)"+KeyMenuList[u'上一个文件'], u"打开上一个文件", wx.ITEM_NORMAL)
wxglade_tmp_menu_sub.Append(105, u"下一个文件(&N)"+KeyMenuList[u'下一个文件'], u"打开下一个文件", wx.ITEM_NORMAL)
wxglade_tmp_menu.AppendMenu(wx.NewId(), u"按文件序号顺序打开", wxglade_tmp_menu_sub, "")
wxglade_tmp_menu_sub = wx.Menu()
i=1000
for f in OpenedFileList:
i+=1
f['MenuID']=i
if f['type']=='normal':wxglade_tmp_menu_sub.Append(i,f['file'],f['file'],wx.ITEM_NORMAL)
else:wxglade_tmp_menu_sub.Append(i,f['zfile']+u'|'+f['file'],f['file'],wx.ITEM_NORMAL)
self.Bind(wx.EVT_MENU, self.OpenLastFile, id=i)
self.LastFileMenu=wxglade_tmp_menu_sub
wxglade_tmp_menu.AppendMenu(wx.NewId(), u"曾经打开的文件", wxglade_tmp_menu_sub, "")
wxglade_tmp_menu.Append(109, u"以往打开文件历史", u"显示曾经打开的所有文件列表", wx.ITEM_NORMAL)
wxglade_tmp_menu.AppendSeparator()
wxglade_tmp_menu.Append(110, u"搜索小说网站(&S)"+KeyMenuList[u'搜索小说网站'], u"搜索小说网站", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(116, u"WEB下载管理器"+KeyMenuList[u'WEB下载管理器'], u"WEB下载管理器", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(115, u"管理订阅"+KeyMenuList[u'管理订阅'], u"管理订阅", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(111, u"重新载入插件"+KeyMenuList[u'重新载入插件'], u"重新载入插件", wx.ITEM_NORMAL)
wxglade_tmp_menu.AppendSeparator()
wxglade_tmp_menu.Append(113, u"搜索LTBNET"+KeyMenuList[u'搜索LTBNET'], u"搜索LTBNET", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(114, u"下载管理器"+KeyMenuList[u'下载管理器'], u"下载管理器", wx.ITEM_NORMAL)
wxglade_tmp_menu.AppendSeparator()
wxglade_tmp_menu.Append(112, u"清空缓存(&O)"+KeyMenuList[u'清空缓存'], u"清空缓存目录", wx.ITEM_NORMAL)
wxglade_tmp_menu.AppendSeparator()
wxglade_tmp_menu.Append(106, u"选项(&O)"+KeyMenuList[u'选项'], u"程序的设置选项", wx.ITEM_NORMAL)
wxglade_tmp_menu.AppendSeparator()
wxglade_tmp_menu.Append(107, u"退出(&X)"+KeyMenuList[u'退出'], u"退出本程序", wx.ITEM_NORMAL)
self.frame_1_menubar.Append(wxglade_tmp_menu, u"文件(&F)")
wxglade_tmp_menu = wx.Menu()
wxglade_tmp_menu.Append(202, u"拷贝(&C)"+KeyMenuList[u'拷贝'], u"将选中的内容拷贝到剪贴板", wx.ITEM_NORMAL)
wxglade_tmp_menu.AppendSeparator()
wxglade_tmp_menu.Append(203, u"查找(&S)"+KeyMenuList[u'查找'], u"在打开的文件中查找", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(204, u"查找下一个(&N)"+KeyMenuList[u'查找下一个'], u"查找下一个", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(205, u"查找上一个(&N)"+KeyMenuList[u'查找上一个'], u"查找上一个", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(206, u"替换(&R)"+KeyMenuList[u'替换'], u"在打开的文件中查找并替换", wx.ITEM_NORMAL)
self.frame_1_menubar.Append(wxglade_tmp_menu, u"查找(&S)")
wxglade_tmp_menu = wx.Menu()
self.ViewMenu=wxglade_tmp_menu
wxglade_tmp_menu.AppendRadioItem(601,u'纸张显示模式'+KeyMenuList[u'纸张显示模式'],u'设置当前显示模式为纸张')
wxglade_tmp_menu.AppendRadioItem(602,u'书本显示模式'+KeyMenuList[u'书本显示模式'],u'设置当前显示模式为书本')
wxglade_tmp_menu.AppendRadioItem(603,u'竖排书本显示模式'+KeyMenuList[u'竖排书本显示模式'],u'设置当前显示模式为竖排书本')
wxglade_tmp_menu.AppendSeparator()
wxglade_tmp_menu.Append(507, u"增大字体"+KeyMenuList[u'增大字体'], u"增大字体", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(508, u"减小字体"+KeyMenuList[u'减小字体'], u"减小字体", wx.ITEM_NORMAL)
wxglade_tmp_menu.AppendSeparator()
wxglade_tmp_menu.Append(501, u"显示工具栏"+KeyMenuList[u'显示工具栏'], u"是否显示工具栏", wx.ITEM_CHECK)
wxglade_tmp_menu.Append(511, u"缩小工具栏"+KeyMenuList[u'缩小工具栏'], u"缩小工具栏", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(512, u"放大工具栏"+KeyMenuList[u'放大工具栏'], u"放大工具栏", wx.ITEM_NORMAL)
wxglade_tmp_menu.AppendSeparator()
wxglade_tmp_menu.Append(503, u"全屏显示"+KeyMenuList[u'全屏显示'], u"全屏显示", wx.ITEM_CHECK)
wxglade_tmp_menu.Append(502, u"显示文件侧边栏"+KeyMenuList[u'显示文件侧边栏'], u"是否显示文件侧边栏", wx.ITEM_CHECK)
wxglade_tmp_menu.Append(510, u"显示章节侧边栏"+KeyMenuList[u'显示章节侧边栏'], u"是否显示章节侧边栏", wx.ITEM_CHECK)
wxglade_tmp_menu.Append(505, u"自动翻页"+KeyMenuList[u'自动翻页'], u"是否自动翻页", wx.ITEM_CHECK)
wxglade_tmp_menu.Append(506, u"显示进度条"+KeyMenuList[u'显示进度条'], u"显示进度条", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(509, u"显示章节"+KeyMenuList[u'显示目录'], u"显示章节", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(513, u"跳转历史"+KeyMenuList[u'跳转历史'], u"跳转历史", wx.ITEM_NORMAL)
if GlobalConfig['HideToolbar']:
wxglade_tmp_menu.Check(501,True)
self.SidebarMenu=wxglade_tmp_menu
wxglade_tmp_menu.Append(504, u"智能分段"+KeyMenuList[u'智能分段'], u"智能分段", wx.ITEM_CHECK)
self.FormatMenu=wxglade_tmp_menu
self.frame_1_menubar.Append(wxglade_tmp_menu, u"视图(&T)")
wxglade_tmp_menu = wx.Menu()
wxglade_tmp_menu.Append(301, u"添加到收藏夹(&A)"+KeyMenuList[u'添加到收藏夹'], u"将当前阅读位置添加到收藏夹", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(302, u"整理收藏夹(&M)"+KeyMenuList[u'整理收藏夹'], u"整理收藏夹", wx.ITEM_NORMAL)
self.frame_1_menubar.Append(wxglade_tmp_menu, u"收藏(&V)")
wxglade_tmp_menu = wx.Menu()
wxglade_tmp_menu.Append(701, u"过滤HTML标签"+KeyMenuList[u'过滤HTML标记'], u"过滤HTML标签", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(702, u"简体转繁体"+KeyMenuList[u'切换为繁体字'], u"简体转繁体", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(703, u"繁体转简体"+KeyMenuList[u'切换为简体字'], u"繁体转简体", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(704, u"生成EPUB文件"+KeyMenuList[u'生成EPUB文件'], u"生成EPUB文件", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(705, u"启用WEB服务器"+KeyMenuList[u'启用WEB服务器'], u"是否启用WEB服务器", wx.ITEM_CHECK)
wxglade_tmp_menu.Append(706, u'检测端口是否开启'+KeyMenuList[u'检测端口是否开启'], u'检测端口是否开启', wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(707, u'使用UPNP添加端口映射'+KeyMenuList[u'使用UPNP添加端口映射'], u'使用UPNP添加端口映射', wx.ITEM_NORMAL)
self.frame_1_menubar.Append(wxglade_tmp_menu, u"工具(&T)")
wxglade_tmp_menu = wx.Menu()
wxglade_tmp_menu.Append(401, u"简明帮助(&B)"+KeyMenuList[u'简明帮助'], u"简明帮助", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(404, u"版本更新内容"+KeyMenuList[u'版本更新内容'], u"版本更新内容", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(403, u"检查更新(&C)"+KeyMenuList[u'检查更新'], u"在线检查是否有更新的版本", wx.ITEM_NORMAL)
wxglade_tmp_menu.Append(402, u"关于(&A)"+KeyMenuList[u'关于'], u"关于本程序", wx.ITEM_NORMAL)
self.frame_1_menubar.Append(wxglade_tmp_menu, u"帮助(&H)")
self.SetMenuBar(self.frame_1_menubar)
# Menu Bar end
self.frame_1_statusbar = self.CreateStatusBar(4, 0)
# Tool Bar
self.ResetTool((GlobalConfig['ToolSize'],GlobalConfig['ToolSize']))
# Tool Bar end
#self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_RICH2)
self.Bind(wx.EVT_MENU, self.Menu101, id=101)
self.Bind(wx.EVT_MENU, self.Menu102, id=102)
self.Bind(wx.EVT_MENU, self.Menu103, id=103)
self.Bind(wx.EVT_MENU, self.Menu104, id=104)
self.Bind(wx.EVT_MENU, self.Menu105, id=105)
self.Bind(wx.EVT_MENU, self.Menu106, id=106)
self.Bind(wx.EVT_MENU, self.Menu107, id=107)
self.Bind(wx.EVT_MENU, self.Menu108, id=108)
self.Bind(wx.EVT_MENU, self.Menu109, id=109)
self.Bind(wx.EVT_MENU, self.Menu110, id=110)
self.Bind(wx.EVT_MENU, self.Menu111, id=111)
self.Bind(wx.EVT_MENU, self.Menu112, id=112)
self.Bind(wx.EVT_MENU, self.Menu113, id=113)
self.Bind(wx.EVT_MENU, self.Menu114, id=114)
self.Bind(wx.EVT_MENU, self.Menu115, id=115)
self.Bind(wx.EVT_MENU, self.Menu116, id=116)
self.Bind(wx.EVT_MENU, self.Menu202, id=202)
self.Bind(wx.EVT_MENU, self.Menu203, id=203)
self.Bind(wx.EVT_MENU, self.Menu204, id=204)
self.Bind(wx.EVT_MENU, self.Menu205, id=205)
self.Bind(wx.EVT_MENU, self.Menu206, id=206)
self.Bind(wx.EVT_MENU, self.Menu301, id=301)
self.Bind(wx.EVT_MENU, self.Menu302, id=302)
self.Bind(wx.EVT_MENU, self.Menu401, id=401)
self.Bind(wx.EVT_MENU, self.Menu402, id=402)
self.Bind(wx.EVT_MENU, self.Menu403, id=403)
self.Bind(wx.EVT_MENU, self.Menu404, id=404)
self.Bind(wx.EVT_MENU, self.Menu501, id=501)
self.Bind(wx.EVT_MENU, self.Menu502, id=502)
self.Bind(wx.EVT_MENU, self.Menu503, id=503)
self.Bind(wx.EVT_MENU, self.Menu505, id=505)
self.Bind(wx.EVT_MENU, self.ShowSlider, id=506)
self.Bind(wx.EVT_MENU, self.Menu507, id=507)
self.Bind(wx.EVT_MENU, self.Menu508, id=508)
self.Bind(wx.EVT_MENU, self.Menu509, id=509)
self.Bind(wx.EVT_MENU, self.Menu510, id=510)
self.Bind(wx.EVT_MENU, self.Menu511, id=511)
self.Bind(wx.EVT_MENU, self.Menu512, id=512)
self.Bind(wx.EVT_MENU, self.Menu513, id=513)
self.Bind(wx.EVT_MENU, self.Menu601, id=601)
self.Bind(wx.EVT_MENU, self.Menu602, id=602)
self.Bind(wx.EVT_MENU, self.Menu603, id=603)
self.Bind(wx.EVT_MENU, self.Menu704, id=704)
self.Bind(wx.EVT_MENU, self.Menu705, id=705)
self.Bind(wx.EVT_MENU, self.Menu706, id=706)
self.Bind(wx.EVT_MENU, self.Menu707, id=707)
self.Bind(wx.EVT_MENU, self.Tool41, id=701)
self.Bind(wx.EVT_MENU, self.Tool43, id=702)
self.Bind(wx.EVT_MENU, self.Tool42, id=703)
self.Bind(wx.EVT_MENU, self.Tool44, id=504)
self.Bind(wx.EVT_TOOL, self.Menu110, id=110)
self.Bind(wx.EVT_TOOL, self.Menu101, id=11)
self.Bind(wx.EVT_TOOL, self.Menu103, id=13)
self.Bind(wx.EVT_TOOL, self.Menu106, id=16)
self.Bind(wx.EVT_TOOL, self.Menu105, id=15)
self.Bind(wx.EVT_TOOL, self.Menu104, id=14)
self.Bind(wx.EVT_TOOL, self.Menu108, id=18)
self.Bind(wx.EVT_TOOL, self.Menu203, id=23)
self.Bind(wx.EVT_TOOL, self.Menu204, id=24)
self.Bind(wx.EVT_TOOL, self.Menu205, id=25)
self.Bind(wx.EVT_TOOL, self.Menu301, id=31)
self.Bind(wx.EVT_TOOL, self.Menu302, id=32)
self.Bind(wx.EVT_TOOL, self.Tool41, id=41)
self.Bind(wx.EVT_TOOL, self.Tool42, id=42)
self.Bind(wx.EVT_TOOL, self.Tool43, id=43)
self.Bind(wx.EVT_TOOL, self.Tool44, id=44)
self.Bind(wx.EVT_TOOL, self.Menu601, id=61)
self.Bind(wx.EVT_TOOL, self.Menu602, id=62)
self.Bind(wx.EVT_TOOL, self.Menu603, id=63)
#self.text_ctrl_1.Bind(wx.EVT_MOUSEWHEEL,self.MyMouseMW) end wxGlade
self.Bind(wx.EVT_LIST_ITEM_ACTIVATED,self.OnActMulu,self.list_ctrl_mulu)
self.Bind(wx.EVT_TOOL, self.Menu502, id=52)
self.text_ctrl_1.Bind(wx.EVT_CHAR,self.OnChar)
self.text_ctrl_2.Bind(wx.EVT_CHAR,self.OnChar3)
self.list_ctrl_1.Bind(wx.EVT_CHAR,self.OnChar2)
self.list_ctrl_mulu.Bind(wx.EVT_CHAR,self.OnChar2)
#self.list_ctrl_1.Bind(wx.EVT_KEY_UP,self.OnCloseSiderbar)
#self.text_ctrl_2.Bind(wx.EVT_KEY_UP,self.OnCloseSiderbar)
self.Bind(wx.EVT_FIND, self.OnFind)
self.Bind(wx.EVT_FIND_NEXT, self.OnFind)
self.Bind(wx.EVT_FIND_CLOSE, self.OnFindClose)
self.Bind(wx.EVT_FIND_REPLACE, self.OnReplace)
self.Bind(wx.EVT_FIND_REPLACE_ALL, self.OnReplace)
self.Bind(wx.EVT_CLOSE,self.OnClose)
self.Bind(wx.EVT_ACTIVATE,self.OnWinActive)
self.Bind(EVT_UPDATE_STATUSBAR,self.UpdateStatusBar)
self.Bind(EVT_ReadTimeAlert,self.ReadTimeAlert)
self.Bind(EVT_DFA,self.DownloadFinished)
## self.Bind(EVT_DUA,self.UpdateStatusBar)
self.Bind(EVT_DUA,self.UpdateWebDownloadProgress)
self.Bind(EVT_AME,self.AlertMsg)
self.Bind(EVT_ScrollDownPage,self.scrolldownpage)
## self.Bind(EVT_GetPos,self.getPos)
self.Bind(EVT_VerCheck,self.DisplayVerCheck)
self.Bind(wx.EVT_SPLITTER_DCLICK,self.OnSplitterDClick,self.window_1)
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected,self.list_ctrl_1)
self.Bind(wx.EVT_SIZE,self.onSize)
self.list_ctrl_1.Bind(wx.EVT_CHAR,self.OnDirChar)
self.Bind(wx.EVT_TEXT,self.SearchSidebar,self.text_ctrl_2)
self.Bind(EVT_UPDV,self.UpdateValue)
# self.text_ctrl_1.Bind(wx.EVT_MIDDLE_DCLICK,self.MyMouseMDC)
# self.text_ctrl_1.Bind(wx.EVT_RIGHT_DOWN,self.MyMouseRU)
# self.text_ctrl_1.Bind(wx.EVT_MOUSEWHEEL,self.MyMouseMW)
# self.text_ctrl_1.Bind(wx.EVT_MIDDLE_DOWN,self.MyMouseMDW)
#register ESC as system hotkey
if MYOS == 'Windows':
if GlobalConfig['EnableESC']:
self.RegisterHotKey(1,0,wx.WXK_ESCAPE)
self.Bind(wx.EVT_HOTKEY,self.OnESC)
self.SetTitle(self.title_str)
# load last opened file
if openfile<>None:
if isinstance(openfile,str):
enc=chardet.detect(openfile)['encoding']
openfile=openfile.decode(enc)
self.LoadFile([openfile],startup=True)
else:
if GlobalConfig['LoadLastFile']==True:
flist=[]
if GlobalConfig['LastFile'] != "" and GlobalConfig['LastFile'] != None:
if GlobalConfig['LastFile'].find('*')==-1: # if there is only one last opened file
## flist.append(GlobalConfig['LastFile'])
if GlobalConfig['LastZipFile']=='':
if GlobalConfig['BookDirPrefix'] != '':
flist.append(joinBookPath(GlobalConfig['LastFile']))
if flist[0].strip()<>'':self.LoadFile(flist,pos=GlobalConfig['LastPos'],startup=True)
else:
flist.append(GlobalConfig['LastFile'])
zfilename=joinBookPath(GlobalConfig['LastZipFile'])
if flist[0].strip()<>'':self.LoadFile(flist,'zip',zfilename,pos=GlobalConfig['LastPos'],startup=True)
else: # if there are multiple last opened files
for f in GlobalConfig['LastFile'].split('*'):
flist=[]
if f.find('|')==-1:
flist.append(f)
self.LoadFile(flist,openmethod='append',startup=True)
else:
flist.append(f.split('|')[1])
self.LoadFile(flist,'zip',f.split('|')[0].strip(),openmethod='append',startup=True)
self.text_ctrl_1.ShowPosition(GlobalConfig['LastPos'])
self.text_ctrl_1.Bind(wx.EVT_MOUSEWHEEL,self.MyMouseMW)
#Start Clocking
self.clk_thread=ClockThread(self)
#max the window
self.Maximize(True)
modes={'paper':601,'book':602,'vbook':603}
tmodes={'paper':61,'book':62,'vbook':63}
self.ViewMenu.Check(modes[self.text_ctrl_1.show_mode],True)
self.frame_1_toolbar.ToggleTool(tmodes[self.text_ctrl_1.show_mode],True)
#start the display pos thread
self.display_pos_thread=DisplayPosThread(self)
#start auto counting thread
self.auto_count_thread=AutoCountThread(self)
#start assign images of sidebar
self.PvFrame=PreviewFrame(self,-1)
self.image_list=wx.ImageList(16,16,mask=False,initialCount=5)
self.file_icon_list={}
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/folder.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["folder"]=0
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/txtfile.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["txtfile"]=1
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/zipfile.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["zipfile"]=2
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/htmlfile.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["htmlfile"]=3
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/rarfile.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["rarfile"]=4
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/file.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["file"]=5
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/jar.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["jarfile"]=6
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/umd.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["umdfile"]=7
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/up.png",wx.BITMAP_TYPE_ANY)
self.up=self.image_list.Add(bmp)
self.file_icon_list["up"]=8
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/down.png",wx.BITMAP_TYPE_ANY)
self.dn=self.image_list.Add(bmp)
self.file_icon_list["down"]=9
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/epub.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["epub"]=10
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/Driver.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["driver"]=11
self.list_ctrl_1.AssignImageList(self.image_list,wx.IMAGE_LIST_SMALL)
self.list_ctrl_1.InsertColumn(0,u'文件名',width=400)
self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActive, self.list_ctrl_1)
self.itemDataMap={}
wx.lib.mixins.listctrl.ColumnSorterMixin.__init__(self,3)
self.LastDir=''
#if enabled, check version update
if GlobalConfig['VerCheckOnStartup']:
self.version_check_thread=VersionCheckThread(self,False)
#hide the text_ctrl's cursor
#self.text_ctrl_1.Bind(wx.EVT_SET_FOCUS, self.TextOnFocus)
#self.text_ctrl_1.HideNativeCaret()
self.__set_properties()
self.__do_layout()
self.WebDownloadManager=web_download_manager.WebDownloadManager(self)
if FullVersion:
#add UPNP mapping via thread, otherwise it will block, and it takes long time
self.upnp_t=None
if GlobalConfig['RunUPNPAtStartup']:
self.upnp_t = ThreadAddUPNPMapping(self)
self.upnp_t.start()
#starting web server if configured
self.server=None
if GlobalConfig['RunWebserverAtStartup']:
try:
self.server = ThreadedLBServer(('', GlobalConfig['ServerPort']), LBHTTPRequestHandler)
except socket.error:
splash_frame.Close()
dlg = wx.MessageDialog(self,u'端口'+
str(GlobalConfig['ServerPort'])+
u'已被占用,WEB服务器无法启动!或许是因为litebook已经在运行?',
u'出错了!',
wx.OK | wx.ICON_ERROR
)
dlg.ShowModal()
dlg.Destroy()
# Start a thread with the server -- that thread will then start one
# more thread for each request
self.server_thread = threading.Thread(target=self.server.serve_forever)
# Exit the server thread when the main thread terminates
self.server_thread.setDaemon(True)
try:
self.server_thread.start()
mbar=self.GetMenuBar()
mbar.Check(705,True)
except:
splash_frame.Close()
dlg = wx.MessageDialog(self, u'启动WEB服务器失败',
u'出错了!',
wx.OK | wx.ICON_ERROR
)
dlg.ShowModal()
dlg.Destroy()
#print "starting mDNS"
#start mDNS ifconfigured
self.mDNS=None
if GlobalConfig['RunWebserverAtStartup']:
if MYOS == 'Linux':
host_ip=GetMDNSIP()
elif MYOS == 'Darwin':
host_ip=GetMDNSIP_OSX()
else:
host_ip=GetMDNSIP_Win()
if host_ip:
self.mDNS=Zeroconf.Zeroconf(host_ip)
self.mDNS_svc=Zeroconf.ServiceInfo("_opds._tcp.local.", "litebook_shared._opds._tcp.local.", socket.inet_aton(host_ip), GlobalConfig['ServerPort'], 0, 0, {'version':'0.10'})
self.mDNS.registerService(self.mDNS_svc)
#start KADP
self.KPUB_thread=None
self.DownloadManager=None
self.lsd=None
if GlobalConfig['EnableLTBNET']:
kadp_ip='127.0.0.1'
if MYOS == 'Windows':
kadp_exe = cur_file_dir()+"\kadp\KADP.exe"
cmd = [
kadp_exe,
'-product',
str(GlobalConfig['LTBNETPort']),
GlobalConfig['LTBNETID'],
'0',
'1',
]
else:
cmd = [
'python',
cur_file_dir()+"/KADP.py",
'-product',
str(GlobalConfig['LTBNETPort']),
GlobalConfig['LTBNETID'],
'0',
'1',
]
#following is the test code
## kadp_ip='218.21.123.99'
## cmd = [
## 'python',
## cur_file_dir()+"/KADP.py",
## '-server',
## kadp_ip,
## '50200',
## '11110111100000009999',
## '/root/kconf-21',
## '0',
## ]
GlobalConfig['kadp_ctrl'] = xmlrpclib.Server('http://'+kadp_ip+':50201/')
if hasattr(sys.stderr, 'fileno'):
childstderr = sys.stderr
elif hasattr(sys.stderr, '_file') and hasattr(sys.stderr._file, 'fileno'):
childstderr = sys.stderr._file
else:
# Give up and point child stderr at nul
childStderrPath = 'nul'
childstderr = file(childStderrPath, 'a')
#childstderr = file('nul', 'a')
if MYOS == 'Windows':
self.KADP_Process = subprocess.Popen(cmd, stdin=childstderr,stdout=childstderr,stderr=childstderr,creationflags = win32process.CREATE_NO_WINDOW)
else:
self.KADP_Process = subprocess.Popen(cmd)
self.KPUB_thread = kpub.KPUB(GlobalConfig['ShareRoot'],rloc_base_url=u'http://SELF:'+str(GlobalConfig['ServerPort'])+'/')
self.KPUB_thread.start()
#create download manager
self.DownloadManager = download_manager.DownloadManager(self,GlobalConfig['ShareRoot'])
#create LTBNET search dialog
self.lsd = ltbsearchdiag.LTBSearchDiag(self,self.DownloadManager.addTask,'http://'+kadp_ip+':50201/')
#wx.CallLater(10000,self.chkPort,False)
splash_frame.Close()
#print "splash_frame clsoed"
#set show mode, this has to be here, otherwise system won't load if showmode is book or vbook
self.text_ctrl_1.SetShowMode(GlobalConfig['showmode'])
mlist={'paper':601,'book':602,'vbook':603}
tlist={'paper':61,'book':62,'vbook':63}
self.ViewMenu.Check(mlist[GlobalConfig['showmode']],True)
self.frame_1_toolbar.ToggleTool(tlist[GlobalConfig['showmode']],True)
self.frame_1_menubar.Check(501,self.frame_1_toolbar.IsShown())
self.websubscrdlg=None
if FullVersion==False:
mbar=self.GetMenuBar()
mbar.Enable(113,False)
mbar.Enable(114,False)
mbar.Enable(705,False)
mbar.Enable(706,False)
mbar.Enable(707,False)
## def TextOnFocus(self,event):
## self.text_ctrl_1.HideNativeCaret()
## event.Skip()
##
def __set_properties(self):
# begin wxGlade: MyFrame.__set_properties
_icon = wx.EmptyIcon()
_icon.CopyFromBitmap(wx.Bitmap(GlobalConfig['IconDir']+u"/litebook-icon_32x32.png", wx.BITMAP_TYPE_ANY))
self.SetIcon(_icon)
#self.SetTitle(u"轻巧看书 LiteBook")
self.SetSize((640, 480))
# statusbar fields
self.frame_1_statusbar.SetStatusWidths([-2, -1,-1,-3])
frame_1_statusbar_fields = ["ready."]
for i in range(len(frame_1_statusbar_fields)):
self.frame_1_statusbar.SetStatusText(frame_1_statusbar_fields[i], i)
# end wxGlade
# load last appearance
## if str(type(GlobalConfig['CurFont']))=="<class 'wx._gdi.Font'>":
## self.text_ctrl_1.SetFont(GlobalConfig['CurFont'])
## if GlobalConfig['CurFColor']<>'':
## self.text_ctrl_1.SetForegroundColour(GlobalConfig['CurFColor'])
## if GlobalConfig['CurBColor']<>'':
## self.text_ctrl_1.SetBackgroundColour(GlobalConfig['CurBColor'])
## self.text_ctrl_1.Refresh()
def __do_layout(self):
global GlobalConfig
# begin wxGlade: MyFrame.__do_layout
sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
#Use splitwindow to add dir sidebar
sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2 = wx.BoxSizer(wx.VERTICAL)
sizer_mulu=wx.BoxSizer(wx.VERTICAL)
sizer_2.Add(self.text_ctrl_2, 0, wx.EXPAND, 0)
sizer_2.Add(self.list_ctrl_1, 1, wx.EXPAND, 0)
sizer_mulu.Add(self.list_ctrl_mulu,1,wx.EXPAND,1)
self.window_1_pane_1.SetSizer(sizer_2)
self.window_1_pane_mulu.SetSizer(sizer_mulu)
sizer_3.Add(self.text_ctrl_1, 1, wx.EXPAND, 0)
self.window_1_pane_2.SetSizer(sizer_3)
#self.window_1.Initialize(self.window_1_pane_2)
#self.window_1.UpdateSize()
self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2,self.SidebarPos)
self.window_1.Unsplit(self.window_1_pane_1)
sizer_1.Add(self.window_1, 1, wx.EXPAND, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
#Hide the toolbar if it is hidden when litebook exit last time
if GlobalConfig['HideToolbar']:
self.GetToolBar().Hide()
self.SetToolBar(None)
self.Refresh()
self.Layout()
# end wxGlade
def onSize(self, event):
self.text_ctrl_1.SetSize(self.GetClientSize())
event.Skip()
return
def ResetTool(self,newsize=(32,32)):
global MYOS
try:
self.frame_1_toolbar.ClearTools()
self.frame_1_toolbar.Destroy()
except:
pass
self.frame_1_toolbar = wx.ToolBar(self, -1, style=wx.TB_HORIZONTAL|wx.TB_FLAT|wx.TB_3DBUTTONS)
self.SetToolBar(self.frame_1_toolbar)
self.frame_1_toolbar.SetToolBitmapSize(newsize)
self.frame_1_toolbar.SetMargins((0,0))
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"Network-32x32.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddLabelTool(110, u"搜索并下载", bmp, wx.NullBitmap, wx.ITEM_NORMAL, u"搜索并下载", u"搜索并下载")
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"DirSideBar.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddCheckLabelTool(52, u"打开文件侧边栏",bmp, wx.NullBitmap, u"打开文件侧边栏", u"打开文件侧边栏")
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"file-open-32x32.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddLabelTool(11, u"打开", bmp, wx.NullBitmap, wx.ITEM_NORMAL, u"打开文件", u"打开文件列表")
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"file-close-32x32.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddLabelTool(13, u"关闭", bmp, wx.NullBitmap, wx.ITEM_NORMAL, u"关闭文件", u"关闭文件")
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"savefile-32x32.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddLabelTool(18, u"另存为", bmp, wx.NullBitmap, wx.ITEM_NORMAL, u"另存为", u"另存为")
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"option-32x32.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddLabelTool(16, u"选项", bmp, wx.NullBitmap, wx.ITEM_NORMAL, u"选项", u"选项")
self.frame_1_toolbar.AddSeparator()
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"next-32x32.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddLabelTool(15, u"下一个", bmp, wx.NullBitmap, wx.ITEM_NORMAL, u"下一个文件", u"下一个文件")
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"previous-32x32.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddLabelTool(14, u"上一个", bmp, wx.NullBitmap, wx.ITEM_NORMAL, u"上一个文件", u"上一个文件")
self.frame_1_toolbar.AddSeparator()
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"paper.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddRadioLabelTool(61,u'纸张显示模式',bmp, wx.NullBitmap,u'纸张显示模式',u'纸张显示模式')
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"openbook.jpg", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddRadioLabelTool(62,u'书本显示模式',bmp, wx.NullBitmap,u'书本显示模式',u'书本显示模式')
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"vbook.jpg", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddRadioLabelTool(63,u'竖排书本显示模式',bmp, wx.NullBitmap,u'竖排书本显示模式',u'竖排书本显示模式')
self.frame_1_toolbar.AddSeparator()
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"search-32x32.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddLabelTool(23, u"查找", bmp, wx.NullBitmap, wx.ITEM_NORMAL, u"搜索", u"搜索")
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"search-next-32x32.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddLabelTool(24, u"查找下一个", bmp, wx.NullBitmap, wx.ITEM_NORMAL, u"搜索下一个", u"搜索下一个")
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"search-previous-32x32.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddLabelTool(25, u"查找上一个", bmp, wx.NullBitmap, wx.ITEM_NORMAL, u"搜索上一个", u"搜索上一个")
self.frame_1_toolbar.AddSeparator()
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"bookmark-add-32x32.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddLabelTool(31, u"加入收藏夹", bmp, wx.NullBitmap, wx.ITEM_NORMAL, u"将当前阅读位置加入收藏夹", u"将当前阅读位置加入收藏夹")
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"bookmark-32x32.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddLabelTool(32, u"收藏夹", bmp, wx.NullBitmap, wx.ITEM_NORMAL, u"打开收藏夹", u"打开收藏夹")
self.frame_1_toolbar.AddSeparator()
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"format-32x32.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.FormatTool=self.frame_1_toolbar.AddCheckLabelTool(44, u"智能分段", bmp, wx.NullBitmap, u"智能分段", u"智能分段")
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"html--32x32.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddLabelTool(41, "HTML", bmp, wx.NullBitmap, wx.ITEM_NORMAL, u"过滤HTML标记", u"过滤HTML标记")
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"jian.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddLabelTool(42, u"切换为简体字", bmp, wx.NullBitmap, wx.ITEM_NORMAL, u"切换为简体字", u"切换为简体字")
bmp=wx.Bitmap(GlobalConfig['IconDir']+os.sep+u"fan.png", wx.BITMAP_TYPE_ANY)
bmp=bmp.ConvertToImage().Rescale(newsize[0],newsize[1],wx.IMAGE_QUALITY_HIGH).ConvertToBitmap()
self.frame_1_toolbar.AddLabelTool(43, u"切换为繁体字", bmp, wx.NullBitmap, wx.ITEM_NORMAL, u"切换为繁体字", u"切换为繁体字")
self.frame_1_toolbar.AddSeparator()
if MYOS == 'Linux':
wid=wx.ScreenDC().GetSize()[0]-1024+50
if wid<50:wid=50
if wid>200:wid=200
if MYOS == 'Linux':
self.sliderControl=wx.Slider(self.frame_1_toolbar, -1, 0, 0, 100,size=(wid,-1),style=wx.SL_LABELS)
else:
self.sliderControl=wx.Slider(self.frame_1_toolbar, -1, 0, 0, 100,style=wx.SL_LABELS)
self.sliderControl.SetSize((-1,newsize[0]))
self.frame_1_toolbar.AddControl(self.sliderControl)
self.sliderControl.Bind(wx.EVT_SCROLL,self.OnSScroll)
self.frame_1_toolbar.SetToolSeparation(5)
self.frame_1_toolbar.Realize()
def ResetMenu(self):
mbar=self.GetMenuBar()
mbar.SetLabel(101,u"文件列表(&L)"+KeyMenuList[u'文件列表'])
mbar.SetLabel(102,u"打开文件(&O)"+KeyMenuList[u'打开文件'])
mbar.SetLabel(108,u"另存为...(&S)"+KeyMenuList[u'另存为'])
mbar.SetLabel(103,u"关闭(&C)"+KeyMenuList[u'关闭'])
mbar.SetLabel(104,u"上一个文件(&P)"+KeyMenuList[u'上一个文件'])
mbar.SetLabel(105,u"下一个文件(&N)"+KeyMenuList[u'下一个文件'])
mbar.SetLabel(110,u"搜索小说网站(&S)"+KeyMenuList[u'搜索小说网站'])
mbar.SetLabel(111,u"重新载入插件"+KeyMenuList[u'重新载入插件'])
mbar.SetLabel(112,u"清空缓存"+KeyMenuList[u'清空缓存'])
mbar.SetLabel(113, u"搜索LTBNET"+KeyMenuList[u'搜索LTBNET'])
mbar.SetLabel(114, u"下载管理器"+KeyMenuList[u'下载管理器'])
mbar.SetLabel(115, u"管理订阅"+KeyMenuList[u'管理订阅'])
mbar.SetLabel(116, u"WEB下载管理器"+KeyMenuList[u'WEB下载管理器'])
mbar.SetLabel(106,u"选项(&O)"+KeyMenuList[u'选项'])
mbar.SetLabel(107,u"退出(&X)"+KeyMenuList[u'退出'])
mbar.SetLabel(202,u"拷贝(&C)"+KeyMenuList[u'拷贝'])
mbar.SetLabel(203,u"查找(&S)"+KeyMenuList[u'查找'])
mbar.SetLabel(204,u"查找下一个(&N)"+KeyMenuList[u'查找下一个'])
mbar.SetLabel(205,u"查找上一个(&N)"+KeyMenuList[u'查找上一个'])
mbar.SetLabel(206,u"替换(&R)"+KeyMenuList[u'替换'])
mbar.SetLabel(601,u'纸张显示模式'+KeyMenuList[u'纸张显示模式'])
mbar.SetLabel(602,u'书本显示模式'+KeyMenuList[u'书本显示模式'])
mbar.SetLabel(603,u'竖排书本显示模式'+KeyMenuList[u'竖排书本显示模式'])
mbar.SetLabel(501,u"显示工具栏"+KeyMenuList[u'显示工具栏'])
mbar.SetLabel(511,u"缩小工具栏"+KeyMenuList[u'缩小工具栏'])
mbar.SetLabel(512,u"放大工具栏"+KeyMenuList[u'放大工具栏'])
mbar.SetLabel(503, u"全屏显示"+KeyMenuList[u'全屏显示'])
mbar.SetLabel(502,u"显示文件侧边栏"+KeyMenuList[u'显示文件侧边栏'])
mbar.SetLabel(505,u"自动翻页"+KeyMenuList[u'自动翻页'])
mbar.SetLabel(506,u"显示进度条"+KeyMenuList[u'显示进度条'])
mbar.SetLabel(504,u"智能分段"+KeyMenuList[u'智能分段'])
mbar.SetLabel(507,u"增大字体"+KeyMenuList[u'增大字体'])
mbar.SetLabel(508,u"减小字体"+KeyMenuList[u'减小字体'])
mbar.SetLabel(509,u"显示章节"+KeyMenuList[u'显示目录'])
mbar.SetLabel(510,u'显示章节侧边栏'+KeyMenuList[u'显示章节侧边栏'])
mbar.SetLabel(301,u"添加到收藏夹(&A)"+KeyMenuList[u'添加到收藏夹'])
mbar.SetLabel(302,u"整理收藏夹(&M)"+KeyMenuList[u'整理收藏夹'])
mbar.SetLabel(701,u"过滤HTML标签"+KeyMenuList[u'过滤HTML标记'])
mbar.SetLabel(702,u"简体转繁体"+KeyMenuList[u'切换为繁体字'])
mbar.SetLabel(703,u"繁体转简体"+KeyMenuList[u'切换为简体字'])
mbar.SetLabel(704,u"生成EPUB文件"+KeyMenuList[u'生成EPUB文件'])
mbar.SetLabel(705,u"启用WEB服务器"+KeyMenuList[u'启用WEB服务器'])
mbar.SetLabel(706,u'检测端口是否开启'+KeyMenuList[u'检测端口是否开启'])
mbar.SetLabel(707,u'使用UPNP添加端口映射'+KeyMenuList[u'使用UPNP添加端口映射'])
mbar.SetLabel(401,u"简明帮助(&B)"+KeyMenuList[u'简明帮助'])
mbar.SetLabel(404,u"版本更新内容"+KeyMenuList[u'版本更新内容'])
mbar.SetLabel(403,u"检查更新(&C)"+KeyMenuList[u'检查更新'])
mbar.SetLabel(402,u"关于(&A)"+KeyMenuList[u'关于'])
mbar.Refresh()
def Menu101(self, event=None): # wxGlade: MyFrame.<event_handler>
dlg=MyOpenFileDialog(self)
dlg.ShowModal()
if dlg.zip_file=='':
if dlg.select_files<>[]:self.LoadFile(dlg.select_files,openmethod=dlg.open_method)
else:
self.LoadFile(dlg.select_files,'zip',dlg.zip_file,openmethod=dlg.open_method)
dlg.Destroy()
def Menu102(self, event): # wxGlade: MyFrame.<event_handler>
global GlobalConfig
wildcard = u"文本文件 (*.txt)|*.txt|" \
u"HTML文件 (*.htm;*.html)|*.htm;*.html|" \
u"电子书 (*.umd;*.jar;*.epub)|*.umd;*.jar;*.epub|" \
u"所有文件 (*.*)|*.*"
dlg = wx.FileDialog(
self, message="Choose a file",
defaultDir=GlobalConfig['LastDir'],
defaultFile="",
wildcard=wildcard,
style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR
)
if dlg.ShowModal() == wx.ID_OK:
flist=dlg.GetPaths()
#GlobalConfig['LastDir']=os.path.split(flist[0])[0]
self.LoadFile(flist)
#event.Skip()
def Menu103(self, event): # wxGlade: MyFrame.<event_handler>
global current_file,OnScreenFileList
if self.text_ctrl_1.GetValue()<>'':self.SaveBookDB()
self.text_ctrl_1.Clear()
self.buff=""
current_file=''
OnScreenFileList=[]
self.frame_1_statusbar.SetStatusText('Ready.')
self.SetTitle(self.title_str)
self.cur_catalog=None
def Menu104(self, event): # wxGlade: MyFrame.<event_handler>
self.LoadNextFile(-1)
def Menu105(self, event): # wxGlade: MyFrame.<event_handler>
self.LoadNextFile(1)
def Menu106(self, event): # wxGlade: MyFrame.<event_handler>
option_dlg=NewOptionDialog(self)
option_dlg.ShowModal()
#option_dlg.Destroy()
self.ResetMenu()
self.text_ctrl_1.SetShowMode(GlobalConfig['showmode'])
if GlobalConfig['backgroundimg']<>'' and GlobalConfig['backgroundimg']<>None:
self.text_ctrl_1.SetBackgroundColour(GlobalConfig['CurBColor'])
self.text_ctrl_1.SetImgBackground(GlobalConfig['backgroundimg'],GlobalConfig['backgroundimglayout'])
else:
self.text_ctrl_1.SetBackgroundColour(GlobalConfig['CurBColor'])
self.text_ctrl_1.bg_img=None
self.text_ctrl_1.SetVbookpunc(GlobalConfig['vbookpunc'])
self.text_ctrl_1.SetFColor(GlobalConfig['CurFColor'])
self.text_ctrl_1.SetFont(GlobalConfig['CurFont'])
self.text_ctrl_1.SetUnderline(GlobalConfig['underline'],GlobalConfig['underlinestyle'],GlobalConfig['underlinecolor'])
self.text_ctrl_1.SetSpace(GlobalConfig['pagemargin'],GlobalConfig['bookmargin'],GlobalConfig['vbookmargin'],GlobalConfig['centralmargin'],GlobalConfig['linespace'],GlobalConfig['vlinespace'])
self.text_ctrl_1.ReDraw()
modes={'paper':601,'book':602,'vbook':603}
tmodes={'paper':61,'book':62,'vbook':63}
self.ViewMenu.Check(modes[self.text_ctrl_1.show_mode],True)
self.frame_1_toolbar.ToggleTool(tmodes[self.text_ctrl_1.show_mode],True)
def Menu107(self, event): # wxGlade: MyFrame.<event_handler>
self.Close()
def Menu108(self, event): # wxGlade: MyFrame.<event_handler>
global GlobalConfig
wildcard = u"文本文件(UTF-8) (*.txt)|*.txt|" \
u"文本文件(GBK) (*.txt)|*.txt"
dlg = wx.FileDialog(
self, message=u"将当前文件另存为", defaultDir=GlobalConfig['LastDir'],
defaultFile="", wildcard=wildcard, style=wx.SAVE | wx.FD_OVERWRITE_PROMPT
)
if dlg.ShowModal() == wx.ID_OK:
savefilename=dlg.GetPath()
if dlg.GetFilterIndex()==0:
try:
fp=codecs.open(savefilename,encoding='utf-8',mode='w')
fp.write(self.text_ctrl_1.GetValue())
fp.close()
except:
err_dlg = wx.MessageDialog(None, u'写入文件:'+fname+u' 错误!',u"错误!",wx.OK|wx.ICON_ERROR)
err_dlg.ShowModal()
err_dlg.Destroy()
return False
else:
try:
fp=codecs.open(savefilename,encoding='GBK',mode='w')
ut=self.text_ctrl_1.GetValue().encode('GBK', 'ignore')
ut=unicode(ut, 'GBK', 'ignore')
fp.write(ut)
fp.close()
except:
err_dlg = wx.MessageDialog(None, u'写入文件:'+savefilename+u' 错误!',u"错误!",wx.OK|wx.ICON_ERROR)
err_dlg.ShowModal()
err_dlg.Destroy()
return False
dlg.Destroy()
def Menu109(self, event): # wxGlade: MyFrame.<event_handler>
if self.FileHistoryDiag==None:self.FileHistoryDiag=FileHistoryDialog(self)
#dlg=FileHistoryDialog(self)
self.FileHistoryDiag.ShowModal()
self.FileHistoryDiag.Hide()
def Menu112(self,evt):
global MYOS
dlg=wx.MessageDialog(self,u'此操作将清空目前所有的缓存文件,确认继续吗?',u'清空缓存',wx.NO_DEFAULT|wx.YES_NO|wx.ICON_QUESTION)
if dlg.ShowModal()==wx.ID_YES:
if MYOS == 'Windows':
flist=glob.glob(os.environ['USERPROFILE'].decode('gbk')+u"\\litebook\\cache\\*")
else:
flist=glob.glob(unicode(os.environ['HOME'],'utf-8')+u"/litebook/cache/*")
suc=True
for f in flist:
try:
os.remove(f)
except:
suc=False
dlg.Destroy()
if suc:
mstr=u'缓存已经全部清空!'
else:
mstr=u'操作结束,过程中发生一些错误'
dlg=wx.MessageDialog(self,mstr,u'清空缓存的结果',wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
def Menu111(self,event):
readPlugin()
def Menu110(self,event):
dlg=Search_Web_Dialog(self)
dlg.ShowModal()
try:
sitename=dlg.sitename
except:
sitename=None
if sitename<>None:
keyword=dlg.keyword
try:
dlg.Destroy()
except:
pass
dlg=web_search_result_dialog(self,sitename,keyword)
dlg.ShowModal()
#self.text_ctrl_1.SetValue(dlg.bk)
try:
dlg.Destroy()
except:
pass
def Menu113(self,evt):
"""
search LTBNET
"""
#lsd = ltbsearchdiag.LTBSearchDiag(self,self.DownloadManager.addTask,'http://127.0.0.1:50201')
if self.lsd==None:
dlg=wx.MessageDialog(self,u'LTBNET没有启动,无法搜索!',u'注意',wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
return
self.lsd.Show()
def Menu114(self,evt):
"""
Download Manager
"""
#global GlobalConfig
if self.DownloadManager==None:
dlg=wx.MessageDialog(self,u'LTBNET没有启动,无法下载!',u'注意',wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
return
self.DownloadManager.Show()
def Menu115(self,evt):
if self.websubscrdlg==None:
self.websubscrdlg=WebSubscrDialog(self)
self.websubscrdlg.ShowModal()
else:
self.websubscrdlg.ShowModal()
def Menu116(self,evt):
self.WebDownloadManager.Show()
def Menu202(self, event): # wxGlade: MyFrame.<event_handler>
self.text_ctrl_1.CopyText()
def Menu203(self, event): # wxGlade: MyFrame.<event_handler>
searchdata = wx.FindReplaceData()
searchdata.SetFlags(1)
searchdata.SetFindString(self.search_str)
searchdlg = wx.FindReplaceDialog(self, searchdata, "Find",wx.FR_NOWHOLEWORD)
searchdlg.data=searchdata
searchdlg.Show(True)
def Menu204(self, event): # wxGlade: MyFrame.<event_handler>
self.search_flg=wx.FR_DOWN
self.FindNext()
def Menu205(self, event): # wxGlade: MyFrame.<event_handler>
self.search_flg=0
self.FindNext()
def Menu206(self,evt):
searchdata = wx.FindReplaceData()
searchdata.SetFlags(1)
searchdata.SetFindString(self.search_str)
searchdlg = wx.FindReplaceDialog(self, searchdata, u"替换",wx.FR_REPLACEDIALOG| wx.FR_NOMATCHCASE | wx.FR_NOWHOLEWORD)
searchdlg.data=searchdata
searchdlg.Show(True)
def Menu301(self, event): # wxGlade: MyFrame.<event_handler>
global OnScreenFileList,BookMarkList
bookmark={}
pos=self.GetCurrentPos()
if self.text_ctrl_1.GetValue()<>'':
if OnScreenFileList.__len__()==1: # if there is only one current on_screen file
if not load_zip or current_zip_file=='':
bookmark['filename']=current_file
else:
bookmark['filename']=current_zip_file+u"|"+current_file
else:
tstr=u''
for onscrfile in OnScreenFileList:
tstr+=onscrfile[0]+u'*'
tstr=tstr[:-1]
bookmark['filename']=tstr
bookmark['pos']=pos
bookmark['line']=self.text_ctrl_1.GetValue()[pos:pos+30].splitlines()[0]
BookMarkList.append(bookmark)
dlg = wx.MessageDialog(self, u'当前阅读位置已加入收藏夹!',u"提示!",wx.OK|wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
def Menu302(self, event): # wxGlade: MyFrame.<event_handler>
bk_dlg=BookMarkDialog(self)
bk_dlg.ShowModal()
filename=bk_dlg.filename
pos=bk_dlg.pos
bk_dlg.Destroy()
if filename<>'':self.LoadBookmark(filename,pos)
def Menu401(self, event): # wxGlade: MyFrame.<event_handler>
url="file://"+cur_file_dir()+'/helpdoc/litebookhelp.htm'
webbrowser.open_new_tab(url)
def Menu404(self, event): # wxGlade: MyFrame.<event_handler>
url="file://"+cur_file_dir()+'/helpdoc/litebookhelp.htm#_Toc400963955'
webbrowser.open_new_tab(url)
def Menu402(self, event): # wxGlade: MyFrame.<event_handler>
global Version
# First we create and fill the info object
info = wx.AboutDialogInfo()
info.Name = self.title_str
info.Version = Version
info.Copyright = "(C) 2014 Hu Jun"
info.Description = u"轻巧看书,简单好用的看书软件!"
info.WebSite = (u"http://code.google.com/p/litebook-project/", u"官方网站")
#info.License = wordwrap(licenseText, 500, wx.ClientDC(self))
# Then we call wx.AboutBox giving it that info object
wx.AboutBox(info)
def Menu403(self, event): # wxGlade: MyFrame.<event_handler>
self.version_check_thread=VersionCheckThread(self)
def Menu501(self, event):
mytbar=self.GetToolBar()
if mytbar==None or not mytbar.IsShown():
self.ResetTool((GlobalConfig['ToolSize'],GlobalConfig['ToolSize']))
else:
mytbar.Hide()
self.SetToolBar(None)
self.Refresh()
self.Layout()
self.frame_1_menubar.Check(501,self.frame_1_toolbar.IsShown())
def CloseSidebar(self,evt=None):
"""Hide the directory sidebar"""
if self.window_1.IsSplit():
self.SidebarPos=self.window_1.GetSashPosition()
self.PvFrame.Hide()
self.window_1.Unsplit(self.window_1_pane_1)
self.frame_1_toolbar.ToggleTool(52,False)
self.SidebarMenu.Check(502,False)
self.text_ctrl_1.SetFocus()
def Menu502(self, event=None):
"""Show/Hide the directory sidebar"""
mbar=self.GetMenuBar()
if self.window_1.IsSplit():
if self.window_1_pane_1.IsShown():
self.SidebarPos=self.window_1.GetSashPosition()
self.PvFrame.Hide()
self.window_1.Unsplit(self.window_1_pane_1)
self.frame_1_toolbar.ToggleTool(52,False)
self.SidebarMenu.Check(502,False)
self.text_ctrl_1.SetFocus()
else:
self.window_1.Unsplit(self.window_1_pane_mulu)
mbar.Check(510,False)
self.DirSideBarReload()
self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2,self.SidebarPos)
self.frame_1_toolbar.ToggleTool(52,True)
self.SidebarMenu.Check(502,True)
self.list_ctrl_1.SetFocus()
else:
self.DirSideBarReload()
self.window_1.SplitVertically(self.window_1_pane_1, self.window_1_pane_2,self.SidebarPos)
self.frame_1_toolbar.ToggleTool(52,True)
self.SidebarMenu.Check(502,True)
self.list_ctrl_1.SetFocus()
def OnActMulu(self,evt):
ind=evt.GetIndex()
i=self.list_ctrl_mulu.GetItemData(ind)
if i<len(self.cur_catalog):
pos=self.cur_catalog[i][1]
self.text_ctrl_1.JumpTo(pos)
def Menu510(self, event=None):
"""Show/Hide the mulu sidebar"""
mbar=self.GetMenuBar()
if self.window_1.IsSplit():
if self.window_1_pane_mulu.IsShown():
self.SidebarPos=self.window_1.GetSashPosition()
self.window_1.Unsplit(self.window_1_pane_mulu)
mbar.Check(510,False)
self.text_ctrl_1.SetFocus()
else:
self.window_1.Unsplit(self.window_1_pane_1)
mbar.Check(502,False)
self.reloadMulu()
self.window_1.SplitVertically(self.window_1_pane_mulu, self.window_1_pane_2,self.SidebarPos)
mbar.Check(510,True)
self.list_ctrl_mulu.SetFocus()
else:
self.reloadMulu()
self.window_1.SplitVertically(self.window_1_pane_mulu, self.window_1_pane_2,self.SidebarPos)
mbar.Check(510,True)
self.list_ctrl_mulu.SetFocus()
def Menu511(self,evt):
global GlobalConfig
GlobalConfig['ToolSize']-=1
self.ResetTool((GlobalConfig['ToolSize'],GlobalConfig['ToolSize']))
def Menu512(self,evt):
global GlobalConfig
GlobalConfig['ToolSize']+=1
self.ResetTool((GlobalConfig['ToolSize'],GlobalConfig['ToolSize']))
def Menu513(self,evt):
values=self.text_ctrl_1.GetValue()
pos_list=self.text_ctrl_1.getPosList()
values_list=[]
for pos in pos_list:
values_list.append(u'字号:'+unicode(pos)+u" - "+values[pos:pos+20])
dlg = wx.SingleChoiceDialog(
self, u'跳转到之前阅读位置', u'选择位置',
choices=values_list,
style=wx.CHOICEDLG_STYLE
)
if dlg.ShowModal() == wx.ID_OK:
i=dlg.GetSelection()
pos=pos_list[i]
self.text_ctrl_1.JumpTo(pos)
dlg.Destroy()
def Menu503(self, event):
self.showfullscr=not self.showfullscr
self.ShowFullScreen(self.showfullscr,wx.FULLSCREEN_ALL)
if self.showfullscr:
self.text_ctrl_1.Bind(wx.EVT_CONTEXT_MENU, self.ShowFullScrMenu)
else:
self.text_ctrl_1.Bind(wx.EVT_CONTEXT_MENU, None)
def Menu505(self,event):
self.autoscroll=not self.autoscroll
def Menu507(self,evt):
self.ChangeFontSize(1)
def Menu508(self,evt):
self.ChangeFontSize(-1)
def reloadMulu(self):
## if self.cur_catalog==None:
## rlist=GenCatalog(self.text_ctrl_1.GetValue())
## self.cur_catalog=rlist
## else:
## rlist=self.cur_catalog
rlist=GenCatalog(self.text_ctrl_1.GetValue())
self.cur_catalog=rlist
self.list_ctrl_mulu.DeleteAllItems()
i=0
for c in rlist:
ind=self.list_ctrl_mulu.InsertStringItem(sys.maxint,c[0])
self.list_ctrl_mulu.SetItemData(ind,i)
i+=1
c_pos=self.text_ctrl_1.GetStartPos()
i=0
for cc in rlist:
if c_pos<cc[1]:
break
else:
i+=1
self.list_ctrl_mulu.Select(i-1)
self.list_ctrl_mulu.Focus(i-1)
self.list_ctrl_mulu.SetColumnWidth(0,-1)
self.list_ctrl_mulu.EnsureVisible(i-1)
def GetChapter(self):
"""
return following:
- rlist from GenCatalog
- clist from GenCatalog
- current chapter name
- current index in rlist
"""
## if self.cur_catalog==None:
## rlist=GenCatalog(self.text_ctrl_1.GetValue())
## self.cur_catalog=rlist
## else:
## rlist=self.cur_catalog
rlist=GenCatalog(self.text_ctrl_1.GetValue())
self.cur_catalog=rlist
c_pos=self.text_ctrl_1.GetStartPos()
i=0
for cc in rlist:
if c_pos<cc[1]:
break
else:
i+=1
return (rlist,i,rlist[i-1][0].strip())
def Menu509(self,evt):
## if self.cur_catalog==None:
## rlist,c_list=GenCatalog(self.text_ctrl_1.GetValue())
## self.cur_catalog=(rlist,c_list)
## else:
## rlist=self.cur_catalog[0]
## c_list=self.cur_catalog[1]
(rlist,i,cname)=self.GetChapter()
c_list=[]
for c in rlist:
c_list.append(c[0])
dlg = wx.SingleChoiceDialog(
self, u'选择章节并跳转', u'章节选择',
choices=c_list,
style=wx.CHOICEDLG_STYLE
)
## c_pos=self.text_ctrl_1.GetStartPos()
## i=0
## for cc in c_list:
## if c_pos<rlist[cc]:
## break
## else:
## i+=1
dlg.SetSelection(i-1)
if dlg.ShowModal() == wx.ID_OK:
i=dlg.GetSelection()
pos=rlist[i][1]
self.text_ctrl_1.JumpTo(pos)
dlg.Destroy()
def Menu601(self,event):
global GlobalConfig
self.text_ctrl_1.SetShowMode('paper')
self.text_ctrl_1.ReDraw()
self.ViewMenu.Check(601,True)
self.frame_1_toolbar.ToggleTool(61,True)
GlobalConfig['showmode']='paper'
def Menu602(self,event):
global GlobalConfig
self.text_ctrl_1.SetShowMode('book')
self.text_ctrl_1.ReDraw()
self.ViewMenu.Check(602,True)
self.frame_1_toolbar.ToggleTool(62,True)
GlobalConfig['showmode']='book'
def Menu603(self,event):
global GlobalConfig
self.text_ctrl_1.SetShowMode('vbook')
self.text_ctrl_1.ReDraw()
self.ViewMenu.Check(603,True)
self.frame_1_toolbar.ToggleTool(63,True)
GlobalConfig['showmode']='vbook'
def Menu704(self,evt):
global OnScreenFileList
if self.text_ctrl_1.GetValue()=="":
return
nlist=OnScreenFileList[0][0].split("|")
if len(nlist)>1:
curfile=nlist[1]
else:
curfile=nlist[0]
curfile=os.path.basename(curfile)
curfile=os.path.splitext(curfile)[0]
dlg=Convert_EPUB_Dialog(self,curfile,curfile,'')
dlg.ShowModal()
if dlg.id=='OK':
ldlg = GMD.GenericMessageDialog(self, u' 正在生成EPUB文件。。。',u"生成中...",wx.ICON_INFORMATION)
ldlg.Show()
ldlg.Update()
txt2epub(self.text_ctrl_1.GetValue(),dlg.outfile,dlg.title,[dlg.author,],dlg.divide_method,dlg.zishu)
ldlg.Destroy()
dlg.Destroy()
def Menu705(self,evt):
global MYOS
mbar=self.GetMenuBar()
if not mbar.IsChecked(705):
self.server.shutdown()
if self.mDNS<>None:
self.mDNS.unregisterService(self.mDNS_svc)
# self.mDNS.close()
else:
if self.server==None:
try:
self.server = ThreadedLBServer(('', GlobalConfig['ServerPort']), LBHTTPRequestHandler)
except socket.error:
dlg = wx.MessageDialog(self,u'端口'+
str(GlobalConfig['ServerPort'])+
u'已被占用,WEB服务器无法启动!或许是因为litebook已经在运行?',
u'出错了!',
wx.OK | wx.ICON_ERROR
)
dlg.ShowModal()
dlg.Destroy()
mbar.Check(705,False)
return
try:
self.server_thread = threading.Thread(target=self.server.serve_forever)
self.server_thread.setDaemon(True)
self.server_thread.start()
except Exception as inst:
dlg = wx.MessageDialog(self, u'WEB服务器启动错误!\n'+str(inst),u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
mbar.Check(705,False)
try:
if MYOS == 'Linux':
host_ip=GetMDNSIP()
elif MYOS == 'Darwin':
host_ip=GetMDNSIP_OSX()
else:
host_ip=GetMDNSIP_Win()
if host_ip:
self.mDNS=Zeroconf.Zeroconf(host_ip)
## print host_ip
self.mDNS_svc=Zeroconf.ServiceInfo("_opds._tcp.local.", "litebook_shared._opds._tcp.local.", socket.inet_aton(host_ip), GlobalConfig['ServerPort'], 0, 0, {'version':'0.10'})
self.mDNS.registerService(self.mDNS_svc)
except Exception as inst:
print traceback.format_exc()
dlg = wx.MessageDialog(self, u'mDNS服务启动错误!\n'+str(inst),u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
def chkPort(self,AlertOnOpen=True):
global GlobalConfig
if not 'kadp_ctrl' in GlobalConfig:
dlg=wx.MessageDialog(self,u'LTBNET没有启动,无法检测!',u'注意',wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
return
if AlertOnOpen==True:
evt = UpdateStatusBarEvent(FieldNum = 3, Value =u'正在检测端口是否开启...')
wx.PostEvent(self, evt)
GlobalConfig['kadp_ctrl'].checkPort(False)
Tchkreport=ThreadChkPort(self,AlertOnOpen)
Tchkreport.start()
def Menu706(self,evt):
self.chkPort()
def Menu707(self,evt):
if self.upnp_t != None and self.upnp_t.isAlive():
return
else:
evt = UpdateStatusBarEvent(FieldNum = 3, Value =u'正在通过UPNP添加端口映射...')
wx.PostEvent(self, evt)
self.upnp_t = ThreadAddUPNPMapping(self)
self.upnp_t.start()
def AlertMsg(self,evt):
dlg = wx.MessageDialog(self, evt.txt,u"注意!",wx.OK|wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
def ChangeFontSize(self,delta):
global GlobalConfig
cur_size=GlobalConfig['CurFont'].GetPointSize()
cur_size+=delta
if cur_size<4:cur_size=4
if cur_size>64:cur_size=64
GlobalConfig['CurFont'].SetPointSize(cur_size)
self.text_ctrl_1.SetFont(GlobalConfig['CurFont'])
self.text_ctrl_1.ReDraw()
def MyMouseMW(self,event):
delta=event.GetWheelRotation()
if delta>0:
self.text_ctrl_1.ScrollLine(-1,1)
elif delta<0:
self.text_ctrl_1.ScrollLine(1,1)
## def MyMouseMDC(self,event):
## #self.last_mouse_event=1
## if event.RightIsDown():
## self.LoadNextFile(-1)
## else:
## self.LoadNextFile(1)
## event.Skip(False)
## event.StopPropagation()
## clickEvent = wx.CommandEvent(wx.wxEVT_COMMAND_LEFT_CLICK, self.text_ctrl_1.GetId())
## self.text_ctrl_1.ProcessEvent(clickEvent)
def ShowPopMenu(self,event):
if not self.showfullscr:
if not hasattr(self,"popupID_1"):
self.popupID_1=wx.NewId()
self.popupID_2=wx.NewId()
self.popupID_3=wx.NewId()
self.popupID_4=wx.NewId()
self.popupID_5=wx.NewId()
self.text_ctrl_1.Bind(wx.EVT_MENU, self.OnFullScrMenu, id=self.popupID1)
menu = wx.Menu()
item = wx.MenuItem(menu, self.popupID1,u"拷贝")
menu.Append(self.popupID_2, u"全选")
menu.Break()
menu.Append(self.popupID_3,u"切换工具栏")
menu.Append(self.popupID_4,u"切换全屏显示")
menu.Append(self.popupID_5,u"切换文件侧边栏")
menu.AppendItem(item)
self.text_ctrl_1.PopupMenu(menu)
menu.Destroy()
else:
event.Skip()
def ShowFullScrMenu(self,event):
if self.showfullscr:
if not hasattr(self,"popupID1"):
self.popupID1=wx.NewId()
self.text_ctrl_1.Bind(wx.EVT_MENU, self.OnFullScrMenu, id=self.popupID1)
menu = wx.Menu()
item = wx.MenuItem(menu, self.popupID1,u"关闭全屏")
menu.AppendItem(item)
self.text_ctrl_1.PopupMenu(menu)
menu.Destroy()
else:
event.Skip()
def OnFullScrMenu(self,event):
self.ShowFullScreen(False,wx.FULLSCREEN_ALL)
self.text_ctrl_1.Bind(wx.EVT_CONTEXT_MENU, None)
self.showfullscr=False
self.ViewMenu.Check(503,False)
def OnSScroll(self,evt):
tval=self.sliderControl.GetValue()
if tval<>100:
tpos=int(float(self.text_ctrl_1.ValueCharCount)*(float(tval)/100.0))
self.text_ctrl_1.JumpTo(tpos)
else:
self.text_ctrl_1.ScrollBottom()
self.text_ctrl_1.SetFocus()
def Tool41(self, event): # wxGlade: MyFrame.<event_handler>
txt=self.text_ctrl_1.GetValue()
txt=htm2txt(txt)
## of=codecs.open(u'1.txt',encoding='gbk',mode='w')
## of.write(txt)
## of.close()
self.text_ctrl_1.SetValue(txt)
def Tool42(self, event): # wxGlade: MyFrame.<event_handler>
txt=self.text_ctrl_1.GetValue()
txt=FtoJ(txt)
pos=self.GetCurrentPos()
self.text_ctrl_1.SetValue(txt)
self.text_ctrl_1.JumpTo(pos)
def Tool43(self, event): # wxGlade: MyFrame.<event_handler>
txt=self.text_ctrl_1.GetValue()
txt=JtoF(txt)
pos=self.GetCurrentPos()
self.text_ctrl_1.SetValue(txt)
self.text_ctrl_1.JumpTo(pos)
def fenduan(self): #HJ: auto optimize the paragraph layout
self.BackupValue=self.text_ctrl_1.GetValue()
istr=self.text_ctrl_1.GetValue()
#convert more than 3 newlines in a row into one newline
p=re.compile('([ \t\f\v]*\n){2,}',re.S)
istr=p.sub("\n",istr)
#find out how much words can current line hold
mmm=self.text_ctrl_1.GetClientSizeTuple()
f=self.text_ctrl_1.GetFont()
dc=wx.WindowDC(self.text_ctrl_1)
dc.SetFont(f)
nnn,hhh=dc.GetTextExtent(u"国")
line_capacity=mmm[0]/nnn
#combile short-lines together
p=re.compile(".*\n")
line_list=p.findall(istr)
i2=[]
last_len=0
#cc=0
line_start=True
for line in line_list:
cur_len=len(line)
if cur_len<line_capacity-2:
if cur_len>last_len-3:
if not line_start:
line=line.strip()
else:
line=line.rstrip()
line_start=False
#line=line[:-1]
#cc+=1
else:
line_start=True
i2.append(line)
last_len=cur_len
self.text_ctrl_1.SetValue("".join(i2))
def Tool44(self,event):
if self.Formated:
self.text_ctrl_1.SetValue(self.BackupValue)
self.FormatMenu.Check(504,False)
self.frame_1_toolbar.ToggleTool(44,False)
else:
self.fenduan()
self.FormatMenu.Check(504,True)
self.frame_1_toolbar.ToggleTool(44,True)
self.Formated=not self.Formated
# end of class MyFrame
def LoadFile(self, filepath,type='file',zipfilepath='',openmethod='load',pos=0,startup=False):
global GlobalConfig,current_file,current_file_list,current_zip_file,load_zip,OnScreenFileList,CurOnScreenFileIndex, MYOS
utext=u''
ii=0#this is used increase randombility of LiteBook-ID
if self.text_ctrl_1.GetValue()<>'':self.SaveBookDB()
if openmethod=='load':
self.buff=""
OnScreenFileList=[]
if startup==False:
ldlg = GMD.GenericMessageDialog(self, u' 正在载入。。。',u"载入中...",wx.ICON_INFORMATION)
ldlg.Show()
ldlg.Refresh()
ldlg.Update()
else:
ldlg=GMD.GenericMessageDialog(self, u' 正在载入。。。',u"载入中...",wx.ICON_INFORMATION)
if type=='file':
if os.path.isfile(filepath[0])==False:
ldlg.Destroy()
return False
if filepath[0].strip()<>'':GlobalConfig['LastDir']=os.path.split(filepath[0])[0]
else:
ldlg.Destroy()
return
load_zip=False
self.GenList('file')
for eachfile in filepath:
ii+=1
if os.path.isfile(eachfile):
file_ext=os.path.splitext(eachfile)[1].lower()
if file_ext==".jar":
utext=jarfile_decode(eachfile)
if utext==False:
dlg = wx.MessageDialog(self, eachfile+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
ldlg.Destroy()
return False
m=hashlib.md5()
eachfile=eachfile.encode('gbk')
if GlobalConfig['HashTitle']==False:
m.update(utext.encode('gbk','ignore'))
else:
m.update(os.path.split(eachfile)[1])
eachfile=eachfile.decode('gbk')
hashresult=m.hexdigest()
fsize=utext.__len__()
else:
if file_ext==".umd":
umdinfo=umd_decode(eachfile)
if umdinfo==False:
dlg = wx.MessageDialog(self, eachfile+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
ldlg.Destroy()
return False
utext=umdinfo['Content']
m=hashlib.md5()
eachfile=eachfile.encode('gbk')
if GlobalConfig['HashTitle']==False:
m.update(utext.encode('gbk','ignore'))
else:
m.update(os.path.split(eachfile)[1])
eachfile=eachfile.decode('gbk')
hashresult=m.hexdigest()
fsize=utext.__len__()
else:
if file_ext==".epub":
utext=epubfile_decode(eachfile)
if utext==False:
dlg = wx.MessageDialog(self, eachfile+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
ldlg.Destroy()
return False
m=hashlib.md5()
eachfile=eachfile.encode('gbk')
if GlobalConfig['HashTitle']==False:
m.update(utext.encode('gbk','ignore'))
else:
m.update(os.path.split(eachfile)[1])
eachfile=eachfile.decode('gbk')
hashresult=m.hexdigest()
fsize=utext.__len__()
else:
coding=DetectFileCoding(eachfile)
if coding=='error':
ldlg.Destroy()
return False
try:
file_handler=open(eachfile,'rb')
t_buff=file_handler.read()
except:
dlg = wx.MessageDialog(self, eachfile+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
ldlg.Destroy()
return False
m=hashlib.md5()
if GlobalConfig['HashTitle']==False:
m.update(t_buff)
else:
eachfile=eachfile.encode('gbk')
m.update(os.path.split(eachfile)[1])
eachfile=eachfile.decode('gbk')
hashresult=m.hexdigest()
utext=AnyToUnicode(t_buff,coding)
fsize=utext.__len__()
if file_ext=='.htm' or file_ext=='.html':utext=htm2txt(utext)
id=utext.__len__()+ii
OnScreenFileList.append((eachfile,id,fsize,hashresult))
self.text_ctrl_1.Clear()
if self.buff<>'': self.buff+="\n\n"
self.buff+="--------------"+eachfile+"--------------LiteBook-ID:"+unicode(id)+u"\n\n"
self.buff+=utext
self.text_ctrl_1.SetValue(self.buff)
UpdateOpenedFileList(eachfile,'normal')
self.UpdateLastFileMenu()
self.frame_1_statusbar.SetStatusText(os.path.split(eachfile)[1])
current_file=eachfile
current_zip_file=''
else:
if os.path.isfile(zipfilepath)==False:
ldlg.Destroy()
return False
if type=='zip':
if os.path.isfile(zipfilepath):
file_ext=os.path.splitext(zipfilepath)[1].lower()
if file_ext=='.zip':
load_zip=True
current_zip_file=zipfilepath
try:
if isinstance(zipfilepath, str):
zipfilepath=zipfilepath.decode('gbk')
zfile=zipfile.ZipFile(zipfilepath)
except:
dlg = wx.MessageDialog(self, zipfilepath+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
ldlg.Destroy()
return False
for eachfile in filepath:
ii+=1
each_ext=os.path.splitext(eachfile)[1].lower()
## if each_ext in ('.txt','.html','.htm'):
#print chardet.detect(eachfile)['encoding']
#eachfile=eachfile.encode('gbk')
coding=DetectFileCoding(eachfile,'zip',zipfilepath)
if coding=='error':
ldlg.Destroy()
return False
try:
if isinstance(eachfile, unicode):
eachfile=eachfile.encode('gbk')
t_buff=zfile.read(eachfile)
# t_buff=file_handler.read()
except:
dlg = wx.MessageDialog(self, eachfile+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
ldlg.Destroy()
return False
m=hashlib.md5()
if GlobalConfig['HashTitle']==False:
m.update(t_buff)
else:
m.update(os.path.split(eachfile)[1])
hashresult=m.hexdigest()
utext=AnyToUnicode(t_buff,coding)
fsize=utext.__len__()
if each_ext in ('.htm','.html'): utext=htm2txt(utext)
id=utext.__len__()+ii
OnScreenFileList.append((zipfilepath+u'|'+eachfile.decode('gbk'),id,fsize,hashresult))
self.text_ctrl_1.Clear()
if self.buff<>'': self.buff+="\n\n"
self.buff+=u"--------------"+zipfilepath+u' | '+eachfile.decode('gbk')+u"--------------LiteBook-ID:"+unicode(id)+u"\n\n"
self.buff+=utext
self.text_ctrl_1.SetValue(self.buff)
## GlobalConfig['CurFont'].SetPointSize(GlobalConfig['CurFont'].GetPointSize()+2)
## self.text_ctrl_1.SetFont(GlobalConfig['CurFont'])
## GlobalConfig['CurFont'].SetPointSize(GlobalConfig['CurFont'].GetPointSize()-2)
## self.text_ctrl_1.SetFont(GlobalConfig['CurFont'])
## self.text_ctrl_1.SetForegroundColour(GlobalConfig['CurFColor'])
## self.text_ctrl_1.SetBackgroundColour(GlobalConfig['CurBColor'])
## self.text_ctrl_1.Refresh()
## self.text_ctrl_1.Update()
UpdateOpenedFileList(eachfile.decode('gbk'),'zip',zipfilepath)
current_file=eachfile.decode('gbk')
self.GenList(zipfilepath)
else:
if file_ext=='.rar':
load_zip=True
current_zip_file=zipfilepath
for eachfile in filepath:
ii+=1
if MYOS == 'Windows':
try:
rfile=UnRAR2.RarFile(zipfilepath)
except:
dlg = wx.MessageDialog(self, zipfilepath+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
ldlg.Destroy()
return False
each_ext=os.path.splitext(eachfile)[1].lower()
if isinstance(eachfile,unicode):
eachfile=eachfile.encode('gbk')
coding=DetectFileCoding(eachfile,'rar',zipfilepath)
if coding=='error':
ldlg.Destroy()
return False
try:
file_handler=rfile.read_files(eachfile)
except:
dlg = wx.MessageDialog(self, eachfile+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
ldlg.Destroy()
return False
t_buff=file_handler[0][1]
else:
t_buff=unrar(zipfilepath,eachfile)
if t_buff==False:
dlg = wx.MessageDialog(self, zipfilepath+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
ldlg.Destroy()
return False
each_ext=os.path.splitext(eachfile)[1].lower()
if isinstance(eachfile,unicode):
eachfile=eachfile.encode('gbk')
#eachfile=eachfile.encode('gbk')
coding=DetectFileCoding(eachfile,'rar',zipfilepath)
if coding=='error':
ldlg.Destroy()
return False
m=hashlib.md5()
if GlobalConfig['HashTitle']==False:
m.update(t_buff)
else:
m.update(os.path.split(eachfile)[1])
if isinstance(eachfile,str):
eachfile=eachfile.decode('gbk')
hashresult=m.hexdigest()
utext=AnyToUnicode(t_buff,coding)
fsize=utext.__len__()
if each_ext in ('.htm','.html'): utext=htm2txt(utext)
id=utext.__len__()+ii
OnScreenFileList.append((zipfilepath+u'|'+eachfile,id,fsize,hashresult))
self.text_ctrl_1.Clear()
if self.buff<>'': self.buff+="\n\n"
self.buff+=u"--------------"+zipfilepath+u'|'+eachfile+u"--------------LiteBook-ID:"+unicode(id)+u"\n\n"
self.buff+=utext
self.text_ctrl_1.SetValue(self.buff)
UpdateOpenedFileList(eachfile,'rar',zipfilepath)
current_file=eachfile
self.GenList(zipfilepath)
tpos=0
if pos<>0:
tpos=pos
else:
if openmethod=='load':
for bk in BookDB:
if bk['key']==unicode(hashresult):
tpos=bk['pos']
break
if tpos<>0:self.text_ctrl_1.JumpTo(tpos)
#Auto Format the paragraph if it is enabled
if self.FormatMenu.IsChecked(504):
self.fenduan()
self.Formated=not self.Formated
#fresh sth
self.SetTitle(self.title_str+filepath[0])
self.cur_catalog=None
self.text_ctrl_1.SetFocus()
self.AllowUpdate = False
ldlg.Destroy()
def LoadNextFile(self, next):
global current_file,GlobalConfig,current_file_list,current_zip_file,load_zip,MYOS
#print "curen file is ",current_file_list
load_file=[]
if current_file=='' or current_file_list==[]:
dlg = wx.MessageDialog(self, u'请先打开一个文件!',u"提示!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return
if str(type(current_file))=="<type 'str'>":
try:
current_file=unicode(current_file,'gbk')
except:
current_file=unicode(current_file,'big5')
current_file_list=sorted(current_file_list,cmp=lambda x,y:cmp(ch2num(x),ch2num(y)))
try:
id=current_file_list.index(current_file)
except:
if MYOS == 'Windows':
xf=current_file.replace("/","\\")
id=current_file_list.index(current_file)
id+=next
if id<0 or id>=current_file_list.__len__():
dlg = wx.MessageDialog(self, u'到头了!',u"提示!",wx.OK|wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
else:
if not load_zip:
load_file.append(current_file_list[id])
self.LoadFile(load_file)
else:
load_file.append(current_file_list[id])
self.LoadFile(load_file,'zip',current_zip_file)
def GenList(self, zip):
global current_file,GlobalConfig,current_file_list,current_zip_file,load_zip
current_file_list=[]
if zip=='file':
flist=os.listdir(GlobalConfig['LastDir'])
for eachfile in flist:
cur_path=GlobalConfig['LastDir']+os.sep+eachfile
if not os.path.isdir(cur_path):
file_ext=os.path.splitext(cur_path)[1].lower()
if file_ext in ('.txt','.htm','.html','.umd','.jar'):
current_file_list.append(cur_path)
else:
prefix=os.path.dirname(current_file)
cur_ext=os.path.splitext(zip)[1].lower()
if cur_ext=='.zip':
zfile=zipfile.ZipFile(zip)
flist=zfile.namelist()
else:
if cur_ext=='.rar':
rfile=rarfile.RarFile(zip)
flist=rfile.namelist()
#print flist
for eachfile in flist:
if os.path.split(eachfile)[1]<>'':
file_ext=os.path.splitext(eachfile)[1].lower()
if file_ext in ('.txt','.htm','.html'):
if not isinstance(eachfile, unicode):
try:
utext=eachfile.decode('gbk')
except:
utext=eachfile.decode('big5')
else:
utext=eachfile
utext=utext.replace("\\","/")
myprefix=os.path.dirname(utext)
if myprefix==prefix or myprefix.replace("\\","/")==prefix:
current_file_list.append(utext)
def OnChar3(self, event):
global KeyConfigList
key=event.GetKeyCode()
if key==wx.WXK_RETURN or key==wx.WXK_TAB:
self.list_ctrl_1.SetFocus()
## self.list_ctrl_1.Select(self.list_ctrl_1.GetNextItem(-1))
else:
if key==wx.WXK_ESCAPE:
self.Menu502(None)
else:
event.Skip()
## def OnCloseSiderbar(self,evt):
## global KeyConfigList
## kstr=keygrid.key2str(evt)
## for kconfig in KeyConfigList:
## if kconfig[0]=='last':
## break
## i=1
## tl=len(kconfig)
## while i<tl:
## if kconfig[i][0]==u'显示文件侧边栏':
## break
## i+=1
## if kstr==kconfig[i][1]:
## self.CloseSidebar()
def OnChar2(self, event):
key=event.GetKeyCode()
if key==wx.WXK_TAB:
if self.window_1_pane_1.IsShown():
self.text_ctrl_2.SetFocus()
else:
if key==wx.WXK_ESCAPE:
if self.window_1_pane_mulu.IsShown():
self.window_1.Unsplit(self.window_1_pane_mulu)
elif self.window_1_pane_1.IsShown():
self.window_1.Unsplit(self.window_1_pane_1)
self.text_ctrl_1.SetFocus()
else:
event.Skip()
def OnChar(self,evt):
global KeyConfigList
keystr=keygrid.key2str(evt)
for kconfig in KeyConfigList:
if kconfig[0]=='last':
break
i=1
tl=len(kconfig)
while i<tl:
if keystr==kconfig[i][1]:break
i+=1
if i>=tl:
evt.Skip()
return
else:
eval(self.func_list[kconfig[i][0]])
## def OnChar(self, event):
## usedKeys=(wx.WXK_HOME,wx.WXK_END,wx.WXK_PAGEDOWN,wx.WXK_PAGEUP,wx.WXK_LEFT,wx.WXK_SPACE,wx.WXK_RIGHT,15,70,72,74,wx.WXK_ESCAPE,wx.WXK_TAB,wx.WXK_RETURN)
## CTRL=2
## ALT=1
## SHIFT=4
## key=event.GetKeyCode()
## Mod=event.GetModifiers()
## if key == wx.WXK_PAGEDOWN or key==wx.WXK_SPACE:
## self.text_ctrl_1.ScrollP(1)
## return
## if key==wx.WXK_RIGHT:
## if Mod==0:
## self.text_ctrl_1.ScrollP(1)
## return
## else:
## if Mod==2:
## self.LoadNextFile(1)
## return
## if key==wx.WXK_LEFT:
## if Mod==0:
## self.text_ctrl_1.ScrollP(-1)
## return
## else:
## if Mod==2:
## self.LoadNextFile(-1)
## return
## if key == wx.WXK_PAGEUP:
## self.text_ctrl_1.ScrollP(-1)
## return
## if key == wx.WXK_HOME :
## self.text_ctrl_1.ScrollTop()
## return
## if key == wx.WXK_END :
## self.text_ctrl_1.ScrollBottom()
## return
## if key == 12: # Ctrl+L to pop up OnScreenFileList dialog
## self.ChoseOnScreenFile()
## if key == 15: # Ctrl+O to open files
## self.Menu101(self)
#### if key==wx.WXK_ESCAPE:
#### self.Iconize()
## if key==wx.WXK_RETURN:
## self.autoscroll=not self.autoscroll
## if key==72: #ALT+H, filter out HTML tag
## self.Tool41(None)
##
## if key==74: #ALT+J, Fan to Jian
## self.Tool42(None)
##
## if key==70: #ALT+F, Jian to Fan
## self.Tool43(None)
##
## if key not in usedKeys:
## #print key
## event.Skip()
def OnFind(self, event):
fstr=event.GetFindString()
flag=event.GetFlags()
fstr=fstr.strip()
if self.last_search_pos==False: self.last_search_pos=self.text_ctrl_1.start_pos
if fstr<>'':
if fstr<>self.search_str:
self.search_str=fstr
pos=self.text_ctrl_1.Find(fstr,self.text_ctrl_1.start_pos)
else:
if flag&wx.FR_DOWN:
pos=self.text_ctrl_1.Find(fstr,self.last_search_pos+1)
else:
pos=self.text_ctrl_1.Find(fstr,self.last_search_pos-1,-1)
if pos==False:
dlg = wx.MessageDialog(self, u'没有找到"'+fstr+u'"',u"查找失败!",wx.OK|wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
else:
## self.text_ctrl_1.SetSelection(pos,pos+fstr.__len__())
## self.text_ctrl_1.ShowPosition(pos)
self.last_search_pos=pos
self.search_str=fstr
self.search_flg=flag
#event.GetDialog().Destroy()
def OnFindClose(self, event):
event.GetDialog().Destroy()
def FindNext(self):
if self.search_str=='': return
if self.last_search_pos==False: self.last_search_pos=self.text_ctrl_1.start_pos
if self.search_flg&wx.FR_DOWN:
pos=self.text_ctrl_1.Find(self.search_str,self.last_search_pos+1)
else:
pos=self.text_ctrl_1.Find(self.search_str,self.last_search_pos-1,-1)
if pos==False:
dlg = wx.MessageDialog(self, u'没有找到"'+self.search_str+u'"',u"查找失败!",wx.OK|wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
## self.text_ctrl_1.SetSelection(pos,pos+self.search_str.__len__())
## self.text_ctrl_1.ShowPosition(pos)
self.last_search_pos=pos
def OnReplace(self,evt):
fstr=evt.GetFindString()
rstr=evt.GetReplaceString()
flag=evt.GetFlags()
buf=self.text_ctrl_1.GetValue()
if evt.GetEventType()==wx.wxEVT_COMMAND_FIND_REPLACE:
pos=self.text_ctrl_1.GetValue().find(fstr,self.text_ctrl_1.start_pos)
#self.text_ctrl_1.JumpTo(pos)
buf=buf[:pos]+buf[pos:].replace(fstr,rstr,1)
self.text_ctrl_1.SetValue(buf)
self.last_search_pos=pos
self.text_ctrl_1.JumpTo(pos)
else:
buf=buf.replace(fstr,rstr)
self.text_ctrl_1.SetValue(buf)
evt.GetDialog().Destroy()
def OpenLastFile(self, event):
global OpenedFileList
id=event.GetId()
for f in OpenedFileList:
if f['MenuID']==id:
flist=[]
flist.append(f['file'])
if f['type']=='normal':
fname=joinBookPath(f['file'])
self.LoadFile([fname,])
else:
zfname=joinBookPath(f['zfile'])
self.LoadFile(flist,'zip',zfname)
break
def OnESC(self,event):
if self.IsIconized():
self.Iconize(False)
else:
self.Iconize()
def OnClose(self, event):
global OnDirectSeenPage,GlobalConfig,writeKeyConfig,MYOS,SqlCon
try:
SqlCon.commit()
SqlCon.close()
except:
pass
self.Hide()
if MYOS == 'Linux':
print "closing..."
SqlCon.close()
self.clk_thread.stop()
self.display_pos_thread.stop()
self.auto_count_thread.stop()
if FullVersion:
if self.KPUB_thread != None: self.KPUB_thread.stop()
time.sleep(1)
GlobalConfig['CurFontData']=self.text_ctrl_1.GetFont()
GlobalConfig['CurFColor']=self.text_ctrl_1.GetFColor()
GlobalConfig['CurBColor']=self.text_ctrl_1.GetBackgroundColour()
if self.GetToolBar()==None:
GlobalConfig['HideToolbar']=True
else:
GlobalConfig['HideToolbar']=not self.GetToolBar().IsShown()
if OnDirectSeenPage:
writeConfigFile(GlobalConfig['LastPos'])
else:
writeConfigFile(self.GetCurrentPos())
#stop KADP
if FullVersion:
mbar=self.GetMenuBar()
if mbar.IsChecked(705):
self.server.shutdown()
if self.mDNS<>None:
self.mDNS.close()
if 'kadp_ctrl' in GlobalConfig:
kadp_ctrl = GlobalConfig['kadp_ctrl']
## kadp_ctrl.preparestop(False)
## print "start to kill KADP"
## self.KADP_Process.kill()
## print "finish stop KADP"
try:
kadp_ctrl.stopall(False)
except:
try:
self.KADP_Process.kill()
except:
pass
## if MYOS != 'Windows':
## os.kill(self.KADP_Process.pid, signal.SIGKILL)
## else:
## os.kill(self.KADP_Process.pid, signal.CTRL_C_EVENT)
writeKeyConfig()
writeRedConf()
event.Skip()
def GetCurrentPos(self):
return self.text_ctrl_1.GetStartPos()
def ChoseOnScreenFile(self):
global OnScreenFileList
fl=[]
for f in OnScreenFileList:
fl.append(f[0])
dlg=wx.SingleChoiceDialog(
self, u'当前已经打开的文件列表', u'选择当前已打开的文件',
fl,
wx.CHOICEDLG_STYLE
)
if dlg.ShowModal() == wx.ID_OK:
selected=dlg.GetStringSelection()
for f in OnScreenFileList:
if f[0]==selected:
selected_id=f[1]
break
pos=self.text_ctrl_1.GetValue().find(u"LiteBook-ID:"+unicode(selected_id))
self.text_ctrl_1.ShowPosition(pos)
dlg.Destroy()
def LoadBookmark(self,filename,tpos):
global OnScreenFileList
self.text_ctrl_1.Clear()
self.buff=""
current_file=''
OnScreenFileList=[]
flist=[]
if filename.find('*')==-1:
if filename.find("|")==-1:
flist.append(filename)
self.LoadFile(flist,pos=tpos)
else:
(zfile,file)=filename.split("|")
flist.append(file)
self.LoadFile(flist,'zip',zfile,pos=tpos)
else:
for f in filename.split('*'):
flist=[]
if f.find('|')==-1:
flist.append(f)
self.LoadFile(flist,openmethod='append')
else:
flist.append(f.split('|')[1])
self.LoadFile(flist,'zip',f.split('|')[0].strip(),openmethod='append')
self.text_ctrl_1.ShowPosition(tpos)
def OnWinActive(self,event):
global Ticking
if event.GetActive():
if self.window_1.IsSplit():
self.list_ctrl_1.SetFocus()
else:
self.text_ctrl_1.SetFocus()
Ticking=True
else:
Ticking=False
def SaveBookDB(self):
global OnScreenFileList,BookDB,OnDirectSeenPage,GlobalConfig
pos=self.GetCurrentPos()
## tsize=0
## i=0
## for f in OnScreenFileList:
## tsize+=f[2]
## if pos<tsize: break
## i+=1
## id=i-1
## hash_id=OnScreenFileList[id][3]
## i=0
## tsize=0
## while i<id:
## pos-=OnScreenFileList[i][2]
if OnScreenFileList.__len__()>1: return #if there is multiple on scrren file, the the pos will not be remembered
try:
hash_id=OnScreenFileList[0][3]
except:
return
for bk in BookDB:
if bk['key']==hash_id:
if OnDirectSeenPage: GlobalConfig['LastPos']=pos
bk['pos']=pos
return
BookDB.insert(0,{'key':hash_id,'pos':pos})
if BookDB.__len__()>GlobalConfig['MaxBookDB']:
BookDB.pop()
## def DisplayPos(self,event):
## global OnScreenFileList
## while(True):
## try:
## pos=self.GetCurrentPos()[0]
## last_pos=self.text_ctrl_1.GetLastPosition()
## except:
## return
## if last_pos<>0:
## percent=int((float(pos)/float(last_pos))*100)
## allsize=0
## i=0
## pos+=2700
## for f in OnScreenFileList:
## allsize+=f[2]
## if pos<allsize: break
## i+=1
## if i>=OnScreenFileList.__len__():
## i=OnScreenFileList.__len__()-1
## fname=OnScreenFileList[i][0]
## try:
## self.frame_1_statusbar.SetStatusText(fname+u' , '+unicode(percent)+u'%',0)
## except:
## return
## time.sleep(0.5)
def UpdateStatusBar(self,event):
if event.FieldNum<>0:
self.frame_1_statusbar.SetStatusText(event.Value,event.FieldNum)
else:
self.frame_1_statusbar.SetStatusText(event.Value,event.FieldNum)
## dc=wx.ClientDC(self.frame_1_statusbar)
## field=self.frame_1_statusbar.GetFieldRect(0)
## field_len=field[2]-field[0]
## txt=event.Value
## txt_len=dc.GetTextExtent(txt)[0]
## if txt_len>field_len:
## tlist=txt.split(os.sep)
## print tlist
## m=len(tlist)
## txt=txt[:6]+u'.../'+tlist[m-2]+u"/"+tlist[m-1]
## self.frame_1_statusbar.SetStatusText(txt,0)
pos=int(self.text_ctrl_1.GetPosPercent())
self.sliderControl.SetValue(pos)
def ReadTimeAlert(self,event):
ttxt=u'现在是'+time.strftime("%H:%M:%S",time.localtime())+"\n"
ttxt+=u'你已经连续阅读了'+event.ReadTime
dlg = wx.MessageDialog(self, ttxt,u"友情提示!",wx.OK|wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
def scrolldownpage(self,event):
self.text_ctrl_1.ScrollP(1)
self.text_ctrl_1.ReDraw()
## def getPos(self,event):
## try:
## self.current_pos=self.GetCurrentPos()
## self.last_pos=self.text_ctrl_1.GetLastPosition()
## except:
## self.current_pos=0
## self.last_pos=0
# def MyMouseMDC(self,event):
# self.last_mouse_event=1
# if event.LeftIsDown():
# self.LoadNextFile(-1)
# else:
# self.LoadNextFile(1)
# event.Skip(False)
# event.StopPropagation()
# clickEvent = wx.CommandEvent(wx.wxEVT_COMMAND_LEFT_CLICK, self.text_ctrl_1.GetId())
# self.text_ctrl_1.ProcessEvent(clickEvent)
#
#
# def MyMouseRU(self,event):
# if self.last_mouse_event==1:
# self.last_mouse_event=0
# return
# else:
# event.Skip()
#
# def MyMouseMW(self,event):
# delta=event.GetWheelRotation()
# if event.RightIsDown():
# self.last_mouse_event=1
# if delta>0:
# self.text_ctrl_1.ScrollPages(-1)
# else:
# self.text_ctrl_1.ScrollPages(1)
# else:
# event.Skip()
#
# def MyMouseMDW(self,event):
# if self.last_mouse_event==1:
# self.last_mouse_event=0
# return
# else:
# event.Skip()
def DirSideBarReload(self):
""""This function is to reload directory sidebar with GlobalConfig['LastDir']"""
global GlobalConfig, MYOS
if GlobalConfig['LastDir']==self.LastDir and not self.UpdateSidebar:
return
else:
self.UpdateSidebar=False
if MYOS == 'Windows':
if ((self.LastDir.__len__()>GlobalConfig['LastDir'].__len__() and not (self.LastDir=='ROOT' and GlobalConfig['LastDir'][1:]==u':\\')))or GlobalConfig['LastDir']==u'ROOT':
RestorPos=True
if GlobalConfig['LastDir']=='ROOT':
RestorPosName=self.LastDir
else:
RestorPosName=self.LastDir.rsplit('\\',1)[1]
else:
RestorPos=False
else:
if self.LastDir=='':
RestorPos=False
else:
RestorPos=True
if GlobalConfig['LastDir']==u'/':
RestorPosName=self.LastDir
RestorPosName=self.LastDir[1:]
else:
RestorPosName=self.LastDir.rsplit(u'/',1)[1]
self.LastDir=GlobalConfig['LastDir']
#current_ext=os.path.splitext(GlobalConfig['LastDir'])[1].lower()
self.sideitemlist=[]
sideitem={}
newitem=wx.ListItem()
newitem.SetText(GlobalConfig['LastDir'])
self.list_ctrl_1.SetColumn(0,newitem)
self.list_ctrl_1.DeleteAllItems()
if str(type(GlobalConfig['LastDir']))=='<type \'str\'>':
GlobalConfig['LastDir']=unicode(GlobalConfig['LastDir'],'GBK','ignore')
if MYOS == 'Windows':
if GlobalConfig['LastDir']<>u'ROOT' and os.path.exists(GlobalConfig['LastDir']):
current_ext=os.path.splitext(GlobalConfig['LastDir'])[1].lower()
self.list_ctrl_1.DeleteAllItems()
try:
tlist=os.listdir(GlobalConfig['LastDir'])
except:
dlg = wx.MessageDialog(None, GlobalConfig['LastDir']+u' 目录打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,"..",self.file_icon_list['folder'])
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=('\x01'+u"..",)
self.sideitemlist.append({'py':u'..','item':self.list_ctrl_1.GetItem(index)})
self.window_1_pane_1.SetFocus()
self.list_ctrl_1.SetFocus()
self.list_ctrl_1.Focus(0)
return
file_list=[]
for m in tlist:
if not isinstance(m,unicode):
m=m.decode('gbk')
file_list.append(m)
else:
#List all windows drives
i=0
RPos=0
self.list_ctrl_1.DeleteAllItems()
drive_list=[]
drive_str = win32api.GetLogicalDriveStrings()
drive_list=drive_str.split('\x00')
drive_list.pop()
for drive in drive_list:
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,drive,self.file_icon_list['driver'])
if drive==RestorPosName:RPos=i
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=('\x01'+drive,)
self.sideitemlist.append({'py':self.cnsort.strToPYS(drive.lower()),'item':self.list_ctrl_1.GetItem(index)})
i+=1
key=self.text_ctrl_2.GetValue()
self.UpdateSearchSidebar(key)
self.list_ctrl_1.Focus(RPos)
self.list_ctrl_1.Select(RPos)
self.list_ctrl_1.Refresh()
self.list_ctrl_1.Update()
return
else:
try:
file_list=os.listdir(GlobalConfig['LastDir'])
except:
dlg = wx.MessageDialog(None, GlobalConfig['LastDir']+u' 目录打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,"..",self.file_icon_list['folder'])
# Date_str=u""
# self.list_ctrl_1.SetStringItem(index,2,Date_str)
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=('\x01'+u"..",)
self.sideitemlist.append({'py':u'..','item':self.list_ctrl_1.GetItem(index)})
self.window_1_pane_1.SetFocus()
self.list_ctrl_1.SetFocus()
self.list_ctrl_1.Focus(0)
return
file_list.sort(key=unicode.lower)
i=0
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,"..",self.file_icon_list['folder'])
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=('\x01'+u"..",)
self.sideitemlist.append({'py':u'..','item':self.list_ctrl_1.GetItem(index)})
i=0
RPos=0
bflist=[]
for n in file_list:
bflist.append(n)
for filename in file_list:
current_path=GlobalConfig['LastDir']+os.sep+filename+os.sep
current_path=os.path.normpath(current_path)
if os.path.isdir(current_path)== True:
if RestorPos:
if filename==RestorPosName:
RPos=i
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['folder'])
# statinfo = os.stat(current_path)
# Date_str=unicode(datetime.fromtimestamp(statinfo.st_mtime))[:19]
# self.list_ctrl_1.SetStringItem(index,2,Date_str)
self.list_ctrl_1.SetItemData(index,index)
self.sideitemlist.append({'py':self.cnsort.strToPYS(filename).lower(),'item':self.list_ctrl_1.GetItem(index)})
# Date_str=''
self.itemDataMap[index]=('\x01'+filename,)
bflist.remove(filename)
i+=1
RPos+=1
for filename in bflist:
current_path=GlobalConfig['LastDir']+u"/"+filename
rr=filename.rsplit('.',1)
not_visable=False
if rr.__len__()==1:
file_ext=''
else:
file_ext=rr[1]
if os.path.isdir(current_path)== False:
if file_ext=='txt' :
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['txtfile'])
else:
if (file_ext=='htm' or file_ext=='html'):
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['htmlfile'])
else:
if file_ext=='zip' :
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['zipfile'])
else:
if file_ext=='rar':
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['rarfile'])
else:
if file_ext=='jar' :
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['jarfile'])
else:
if file_ext=='umd':
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['umdfile'])
else:
if file_ext=='epub':
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['epub'])
else:
if GlobalConfig['ShowAllFileInSidebar']:
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['file'])
else:
not_visable=True
# self.list_ctrl_1.SetStringItem(index,1,file_size)
# self.list_ctrl_1.SetStringItem(index,2,Date_str)
if not_visable==False:
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=(filename,)
self.sideitemlist.append({'py':self.cnsort.strToPYS(filename.lower()),'item':self.list_ctrl_1.GetItem(index)})
key=self.text_ctrl_2.GetValue()
self.UpdateSearchSidebar(key)
self.list_ctrl_1.Focus(RPos)
self.list_ctrl_1.Select(RPos)
self.list_ctrl_1.Refresh()
self.list_ctrl_1.Update()
def OnItemActive(self,event):
"""Called when dir sidebar item was activated"""
global MYOS
self.PvFrame.Hide()
global GlobalConfig
item=event.GetItem()
filename=item.GetText()
if MYOS == 'Windows':
if filename[1:]==":\\" and not os.path.isdir(filename):
return False #means this driver is not ready
if GlobalConfig['LastDir']<>"ROOT":
current_path=GlobalConfig['LastDir']+u"\\"+filename
else:
current_path=filename
else:
if GlobalConfig['LastDir']<>'/':
current_path=GlobalConfig['LastDir']+u"/"+filename
else:
current_path=GlobalConfig['LastDir']+filename
current_path=os.path.normpath(current_path)
current_ext=os.path.splitext(current_path)[1].lower()
if os.path.isdir(current_path)== True:
if MYOS == 'Windows':
if current_path.find(":\\\\..")<>-1:
GlobalConfig['LastDir']=u"ROOT"
else:
GlobalConfig['LastDir']=os.path.normpath(current_path)
else:
GlobalConfig['LastDir']=os.path.normpath(current_path)
self.DirSideBarReload()
else:
if current_ext==".zip" or current_ext==".rar":
dlg=ZipFileDialog(self,current_path)
dlg.ShowModal()
if dlg.selected_files<>[]:
self.LoadFile(dlg.selected_files,'zip',current_path,openmethod=dlg.openmethod)
dlg.Destroy()
else:
dlg.Destroy()
else:
self.LoadFile([current_path,])
def ActiveItem(self,filename):
"""manually active an item"""
global MYOS
self.PvFrame.Hide()
if MYOS == 'Windows':
if filename[1:]==":\\" and not os.path.isdir(filename):
return False #means this driver is not ready
if GlobalConfig['LastDir']<>"ROOT":
current_path=GlobalConfig['LastDir']+u"\\"+filename
else:
current_path=filename
else:
if GlobalConfig['LastDir']<>'/':
current_path=GlobalConfig['LastDir']+u"/"+filename
else:
current_path=GlobalConfig['LastDir']+filename
current_path=os.path.normpath(current_path)
current_ext=os.path.splitext(current_path)[1].lower()
if os.path.isdir(current_path)== True:
if MYOS == 'Windows':
if current_path.find(":\\\\..")<>-1:
GlobalConfig['LastDir']=u"ROOT"
else:
GlobalConfig['LastDir']=os.path.normpath(current_path)
else:
GlobalConfig['LastDir']=os.path.normpath(current_path)
self.DirSideBarReload()
else:
if current_ext==".zip" or current_ext==".rar":
dlg=ZipFileDialog(self,current_path)
dlg.ShowModal()
if dlg.selected_files<>[]:
self.LoadFile(dlg.selected_files,'zip',current_path,openmethod=dlg.openmethod)
dlg.Destroy()
else:
dlg.Destroy()
else:
self.LoadFile([current_path,])
def OnSplitterDClick(self,event):
self.window_1.Unsplit(self.window_1_pane_1)
def GetListCtrl(self):
return self.list_ctrl_1
def GetSortImages(self):
return (self.dn,self.up)
def OnItemSelected(self,event):
global GlobalConfig
if not GlobalConfig['EnableSidebarPreview']: return
filename=unicode(self.list_ctrl_1.GetItemText(event.GetIndex()))
current_path=GlobalConfig['LastDir']+u"/"+filename
current_ext=os.path.splitext(current_path)[1].lower()
if current_ext=='.txt' or current_ext=='.htm' or current_ext=='.html':
coding=DetectFileCoding(current_path)
if coding=='error':return False
try:
file=open(current_path,'r')
except:
dlg = wx.MessageDialog(self, current_path+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return False
i=0
istr=''
while i<20:
try:
istr+=file.readline(500)
except:
dlg = wx.MessageDialog(self, current_path+u' 文件读取错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return False
i+=1
preview_buff=AnyToUnicode(istr,coding)
if current_ext=='.htm' or current_ext=='.html':
preview_buff=htm2txt(preview_buff)
#self.text_ctrl_3.SetValue(preview_buff)
(x,y)=self.list_ctrl_1.GetItemPosition(event.GetIndex())
#rect=self.list_ctrl_1.GetItemRect(event.GetIndex())
#print str(x)+" "+str(self.GetPosition())
self.PvFrame.SetPosition((self.GetPosition()[0]+self.window_1.GetSashPosition(),y))
self.PvFrame.SetText(preview_buff)
self.PvFrame.SetSize((400,200))
self.PvFrame.Hide()
self.PvFrame.Show()
self.list_ctrl_1.SetFocus()
file.close()
else:
self.PvFrame.Hide()
def OnDirChar(self,event):
global GlobalConfig, MYOS
key=event.GetKeyCode()
if key==wx.WXK_RIGHT:#Active Selected Item
i=self.list_ctrl_1.GetFocusedItem()
self.ActiveItem(self.list_ctrl_1.GetItemText(i))
return
if key==wx.WXK_LEFT:#Up dir
if MYOS == 'Windows':
current_path=GlobalConfig['LastDir']+u"\\.."
if GlobalConfig['LastDir']==u'ROOT':
return
if current_path.find(":\\\\..")<>-1:
GlobalConfig['LastDir']=u"ROOT"
else:
GlobalConfig['LastDir']=os.path.normpath(current_path)
else:
if GlobalConfig['LastDir']==u'/':return
current_path=GlobalConfig['LastDir']+u"/.."
GlobalConfig['LastDir']=os.path.normpath(current_path)
self.DirSideBarReload()
return
event.Skip()
def DisplayVerCheck(self,event):
dlg=VerCheckDialog(self,event.imsg)
#event.imsg,event.iurl
dlg.ShowModal()
def UpdateLastFileMenu(self):
global OpenedFileList
i=1000
total=2000
while i<total:
i+=1
try:
self.LastFileMenu.Remove(i) # the number of last opened files may less than maxopenedfiles, so need to try first
except:
pass
i=1000
for f in OpenedFileList:
i+=1
f['MenuID']=i
if f['type']=='normal':self.LastFileMenu.Append(i,f['file'],f['file'],wx.ITEM_NORMAL)
else:self.LastFileMenu.Append(i,f['zfile']+u'|'+f['file'],f['file'],wx.ITEM_NORMAL)
self.Bind(wx.EVT_MENU, self.OpenLastFile, id=i)
def DownloadFinished(self,event):
global OnScreenFileList,GlobalConfig,OnDirectSeenPage,SqlCur,SqlCon
if event.status=='nok':
dlg = wx.MessageDialog(self, event.name+u'下载失败!',
u'出错了!',
wx.OK | wx.ICON_ERROR
)
dlg.ShowModal()
dlg.Destroy()
return None
if GlobalConfig['DAUDF']==2:
savefilename=GlobalConfig['defaultsavedir']+"/"+event.name.strip()+".txt"
try:
fp=codecs.open(savefilename,encoding='GBK',mode='w')
ut=event.bk.encode('GBK', 'ignore')
ut=unicode(ut, 'GBK', 'ignore')
fp.write(ut)
fp.close()
except:
err_dlg = wx.MessageDialog(None, u'写入文件:'+savefilename+u' 错误!',u"错误!",wx.OK|wx.ICON_ERROR)
err_dlg.ShowModal()
err_dlg.Destroy()
return False
dlg = wx.MessageDialog(self, event.name+u'下载完毕,已保存在'+savefilename,
u'下载结束',
wx.OK | wx.ICON_INFORMATION
)
dlg.ShowModal()
dlg.Destroy()
return
dlg = MyChoiceDialog(self, event.name+u'下载完毕。我想:',u'下载结束',
[u'直接观看',u'另存为...'],GlobalConfig['DAUDF']
)
dlg.ShowModal()
try:
rr=dlg.chosen
subscr=dlg.subscr
except:
rr=None
subscr=False
dlg.Destroy()
if rr==u'直接观看':
OnDirectSeenPage=True
self.SaveBookDB()
self.text_ctrl_1.SetValue(event.bk)
OnScreenFileList=[]
OnScreenFileList.append((event.name,'',event.bk.__len__()))
#change the title
self.SetTitle(self.title_str+' --- '+event.name)
self.cur_catalog=None
else:
if rr==u'另存为...':
wildcard = u"文本文件(UTF-8) (*.txt)|*.txt|" \
u"文本文件(GBK) (*.txt)|*.txt"
dlg = wx.FileDialog(
self, message=u"将当前文件另存为", defaultDir=GlobalConfig['LastDir'],
defaultFile=event.name+u".txt", wildcard=wildcard, style=wx.SAVE | wx.FD_OVERWRITE_PROMPT
)
if dlg.ShowModal() == wx.ID_OK:
savefilename=dlg.GetPath()
if dlg.GetFilterIndex()==0:
try:
fp=codecs.open(savefilename,encoding='utf-8',mode='w')
fp.write(event.bk)
fp.close()
except:
err_dlg = wx.MessageDialog(None, u'写入文件:'+fname+u' 错误!',u"错误!",wx.OK|wx.ICON_ERROR)
err_dlg.ShowModal()
err_dlg.Destroy()
return False
else:
try:
fp=codecs.open(savefilename,encoding='GBK',mode='w')
ut=event.bk.encode('GBK', 'ignore')
ut=unicode(ut, 'GBK', 'ignore')
fp.write(ut)
fp.close()
except:
err_dlg = wx.MessageDialog(None, u'写入文件:'+savefilename+u' 错误!',u"错误!",wx.OK|wx.ICON_ERROR)
err_dlg.ShowModal()
err_dlg.Destroy()
return False
dlg.Destroy()
if subscr and event.bookstate != None:
bkstate=event.bookstate
if os.path.dirname(savefilename) == GlobalConfig['defaultsavedir']:
savefilename=os.path.basename(savefilename)
sqlstr="insert into subscr values('%s','%s','%s','%s',%s,'%s','%s')" % (
bkstate['bookname'],bkstate['index_url'],
bkstate['last_chapter_name'],bkstate['last_update'],
bkstate['chapter_count'],
savefilename,
event.plugin_name
)
SqlCur.execute(sqlstr)
SqlCon.commit()
self.text_ctrl_1.SetFocus()
def SearchSidebar(self,evt):
self.UpdateSearchSidebar(evt.GetString().strip())
def UpdateSearchSidebar(self,key):
py_key=key.strip()
rlist=[]
self.list_ctrl_1.DeleteAllItems()
if py_key<>'':
#print self.sideitemlist
for m in self.sideitemlist:
if m['py'].find(py_key)<>-1:
rlist.append(m['item'])
else:
for m in self.sideitemlist:
rlist.append(m['item'])
for m in rlist:
self.list_ctrl_1.InsertItem(m)
def ShowSlider(self,evt=None):
(x,y)=self.GetClientSize()
if self.slider==None:
try:
pos=int(self.text_ctrl_1.GetPosPercent())
except:
pos=0
self.slider=SliderDialog(self,pos,(x/2,y/2))
self.slider.Show()
else:
self.slider.Closeme()
def UpdateValue(self,evt):
if self.AllowUpdate == True and self.streamID==evt.sid:
self.text_ctrl_1.AppendValue(evt.value)
def UpdateWebDownloadProgress(self,evt):
self.WebDownloadManager.updateProgress(evt.Value,evt.url)
class MyOpenFileDialog(wx.Dialog,wx.lib.mixins.listctrl.ColumnSorterMixin):
global GlobalConfig
select_files=[]
zip_file=''
file_icon_list={}
open_method="load"
def __init__(self, *args, **kwds):
global GlobalConfig, MYOS
self.select_files=[]
# begin wxGlade: MyOpenFileDialog.__init__
kwds["style"] = wx.DEFAULT_DIALOG_STYLE | wx.WANTS_CHARS
wx.Dialog.__init__(self, *args, **kwds)
self.bitmap_button_3 = wx.BitmapButton(self, -1, wx.Bitmap(GlobalConfig['IconDir']+u"/reload-16x16.png", wx.BITMAP_TYPE_ANY))
self.text_ctrl_2 = wx.TextCtrl(self, -1, "", style=wx.TE_PROCESS_ENTER)
self.bitmap_button_1 = wx.BitmapButton(self, -1, wx.Bitmap(GlobalConfig['IconDir']+u"/folder-up-16x16.png", wx.BITMAP_TYPE_ANY))
self.bitmap_button_2 = wx.BitmapButton(self, -1, wx.Bitmap(GlobalConfig['IconDir']+u"/dir-tree-16x16.png", wx.BITMAP_TYPE_ANY))
self.list_ctrl_1 = wx.ListCtrl(self, -1, style=wx.LC_REPORT)
self.choice_1 = wx.Choice(self, -1, choices=[u"所有支持的文件格式(*.txt,*.htm,*.html,*.zip,*.rar,*.umd,*.jar)", u"文本文件(*.txt,*.htm,*.html)", u"压缩文件(*.rar,*.zip,*.umd,*.jar,*.epub)", u"所有文件(*.*)"])
self.button_4 = wx.Button(self, -1, u"添加")
self.button_5 = wx.Button(self, -1, u" 打开")
self.button_6 = wx.Button(self, -1, u"取消")
self.text_ctrl_3 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_BUTTON, self.OnReload, self.bitmap_button_3)
self.Bind(wx.EVT_TEXT_ENTER, self.OnEnter, self.text_ctrl_2)
self.Bind(wx.EVT_BUTTON, self.OnUpDir, self.bitmap_button_1)
self.Bind(wx.EVT_BUTTON, self.OnSelectDir, self.bitmap_button_2)
self.Bind(wx.EVT_CHOICE, self.OnChoiceSelected, self.choice_1)
self.Bind(wx.EVT_BUTTON, self.OnCancell, self.button_6)
# end wxGlade
self.Bind(wx.EVT_BUTTON, self.OnOpenFiles, self.button_5)
self.Bind(wx.EVT_BUTTON, self.OnAppendFiles, self.button_4)
self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected,self.list_ctrl_1)
self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActive, self.list_ctrl_1)
if MYOS == 'Windows':
self.list_ctrl_1.Bind(wx.EVT_CHAR,self.OnKey_Win)
else:
self.list_ctrl_1.Bind(wx.EVT_CHAR,self.OnKey)
self.Bind(wx.EVT_ACTIVATE,self.OnWinActive)
if MYOS != 'Windows':
self.list_ctrl_1.Bind(wx.EVT_CHAR,self.OnDirChar)
self.image_list=wx.ImageList(16,16,mask=False,initialCount=5)
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/folder.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["folder"]=0
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/txtfile.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["txtfile"]=1
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/zipfile.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["zipfile"]=2
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/htmlfile.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["htmlfile"]=3
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/rarfile.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["rarfile"]=4
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/file.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["file"]=5
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/jar.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["jarfile"]=6
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/umd.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["umdfile"]=7
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/up.png",wx.BITMAP_TYPE_ANY)
self.up=self.image_list.Add(bmp)
self.file_icon_list["up"]=8
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/down.png",wx.BITMAP_TYPE_ANY)
self.dn=self.image_list.Add(bmp)
self.file_icon_list["down"]=9
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/epub.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["epub"]=10
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/Driver.png",wx.BITMAP_TYPE_ANY)
self.image_list.Add(bmp)
self.file_icon_list["driver"]=11
self.list_ctrl_1.AssignImageList(self.image_list,wx.IMAGE_LIST_SMALL)
self.list_ctrl_1.InsertColumn(0,u'文件名',width=220)
self.list_ctrl_1.InsertColumn(1,u'长度')
self.list_ctrl_1.InsertColumn(2,u'日期',width=120)
self.text_ctrl_2.SetValue(GlobalConfig['LastDir'])
self.itemDataMap={}
wx.lib.mixins.listctrl.ColumnSorterMixin.__init__(self,3)
self.LastDir=''
self.Reload()
def __set_properties(self):
# begin wxGlade: MyOpenFileDialog.__set_properties
self.SetTitle("Open File")
self.SetSize((466, 491))
self.bitmap_button_3.SetSize(self.bitmap_button_3.GetBestSize())
self.text_ctrl_2.SetMinSize((350, -1))
self.bitmap_button_1.SetSize(self.bitmap_button_1.GetBestSize())
self.bitmap_button_2.SetSize(self.bitmap_button_2.GetBestSize())
self.choice_1.SetMinSize((220, 21))
self.choice_1.SetSelection(0)
self.button_6.SetDefault()
self.text_ctrl_3.SetMinSize((392, 120))
# end wxGlade
def __do_layout(self):
# begin wxGlade: MyOpenFileDialog.__do_layout
sizer_2 = wx.BoxSizer(wx.VERTICAL)
sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
sizer_3.Add(self.bitmap_button_3, 0, 0, 0)
sizer_3.Add(self.text_ctrl_2, 0, 0, 0)
sizer_3.Add(self.bitmap_button_1, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
sizer_3.Add(self.bitmap_button_2, 0, 0, 0)
sizer_2.Add(sizer_3, 0, wx.EXPAND, 2)
sizer_2.Add(self.list_ctrl_1, 1, wx.EXPAND, 0)
sizer_4.Add(self.choice_1, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_4.Add(self.button_4, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_4.Add(self.button_5, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_4.Add(self.button_6, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_2.Add(sizer_4, 0, wx.EXPAND, 1)
sizer_2.Add(self.text_ctrl_3, 0, wx.EXPAND, 0)
self.SetSizer(sizer_2)
self.Layout()
# end wxGlade
def Reload(self):
""""This function is to reload MyOpenFileDialog with GlobalConfig['LastDir']"""
global GlobalConfig, MYOS
if MYOS != 'Windows':
if self.LastDir=='':
RestorPos=False
else:
RestorPos=True
if GlobalConfig['LastDir']==u'/':
RestorPosName=self.LastDir
RestorPosName=self.LastDir[1:]
else:
RestorPosName=self.LastDir.rsplit(u'/',1)[1]
else:
if ((self.LastDir.__len__()>GlobalConfig['LastDir'].__len__() and not (self.LastDir=='ROOT' and GlobalConfig['LastDir'][1:]==u':\\')))or GlobalConfig['LastDir']==u'ROOT':
RestorPos=True
if GlobalConfig['LastDir']=='ROOT':
RestorPosName=self.LastDir
else:
RestorPosName=self.LastDir.rsplit('\\',1)[1]
else:
RestorPos=False
self.LastDir=GlobalConfig['LastDir']
if MYOS != 'Windows':
current_ext=os.path.splitext(GlobalConfig['LastDir'])[1].lower()
self.list_ctrl_1.DeleteAllItems()
if str(type(GlobalConfig['LastDir']))=='<type \'str\'>':
GlobalConfig['LastDir']=unicode(GlobalConfig['LastDir'],'GBK','ignore')
try:
file_list=os.listdir(GlobalConfig['LastDir'])
except:
dlg = wx.MessageDialog(None, GlobalConfig['LastDir']+u' 目录打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,"..",self.file_icon_list['folder'])
Date_str=u""
self.list_ctrl_1.SetStringItem(index,2,Date_str)
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=('\x01'+u"..",0,Date_str)
return False
else:
if GlobalConfig['LastDir']<>u'ROOT':
current_ext=os.path.splitext(GlobalConfig['LastDir'])[1].lower()
self.list_ctrl_1.DeleteAllItems()
try:
tlist=os.listdir(GlobalConfig['LastDir'])
except:
dlg = wx.MessageDialog(None, GlobalConfig['LastDir']+u' 目录打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,"..",self.file_icon_list['folder'])
Date_str=u""
self.list_ctrl_1.SetStringItem(index,2,Date_str)
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=('\x01'+u"..",0,Date_str)
#self.window_1_pane_1.SetFocus()
self.list_ctrl_1.SetFocus()
self.list_ctrl_1.Focus(0)
return
file_list=[]
for m in tlist:
m=AnyToUnicode(m,None)
file_list.append(m)
else:
#List all windows drives
i=0
RPos=0
self.list_ctrl_1.DeleteAllItems()
drive_list=[]
drive_str = win32api.GetLogicalDriveStrings()
drive_list=drive_str.split('\x00')
drive_list.pop()
for drive in drive_list:
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,drive,self.file_icon_list['driver'])
if drive==RestorPosName:RPos=i
Date_str=''
self.list_ctrl_1.SetStringItem(index,2,Date_str)
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=('\x01'+drive,0,Date_str)
i+=1
self.text_ctrl_2.SetValue(GlobalConfig['LastDir'])
self.list_ctrl_1.Focus(RPos)
self.list_ctrl_1.Select(RPos)
self.list_ctrl_1.Refresh()
return
file_list=[]
for m in tlist:
m=AnyToUnicode(m,None)
file_list.append(m)
file_list.sort(key=unicode.lower)
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,"..",self.file_icon_list['folder'])
Date_str=u""
self.list_ctrl_1.SetStringItem(index,2,Date_str)
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=('\x01'+u"..",0,Date_str)
i=0
RPos=0
bflist=[]
for n in file_list:
bflist.append(n)
for filename in file_list:
# if str(type(filename))=='<type \'str\'>':
# filename=unicode(filename,'GBK','ignore')
current_path=GlobalConfig['LastDir']+u"/"+filename+u"/"
current_path=os.path.normpath(current_path)
if os.path.isdir(current_path)== True:
if RestorPos:
if filename==RestorPosName:
RPos=i
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['folder'])
Date_str=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getctime(current_path)))
self.list_ctrl_1.SetStringItem(index,2,Date_str)
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=('\x01'+filename,0,Date_str)
bflist.remove(filename)
i+=1
RPos+=1
for filename in bflist:
current_path=GlobalConfig['LastDir']+u"/"+filename
#if os.path.isdir(current_path)== False:
if os.path.splitext(current_path)[1].lower()=='.txt' and self.choice_1.GetSelection()<>2:
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['txtfile'])
Date_str=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getctime(current_path)))
file_size=HumanSize(os.path.getsize(current_path))
self.list_ctrl_1.SetStringItem(index,1,file_size)
self.list_ctrl_1.SetStringItem(index,2,Date_str)
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=(filename,os.path.getsize(current_path),Date_str)
i+=1
else:
if (os.path.splitext(current_path)[1].lower()=='.htm' or os.path.splitext(current_path)[1].lower()=='.html') and self.choice_1.GetSelection()<>2:
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['htmlfile'])
Date_str=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getctime(current_path)))
file_size=HumanSize(os.path.getsize(current_path))
self.list_ctrl_1.SetStringItem(index,1,file_size)
self.list_ctrl_1.SetStringItem(index,2,Date_str)
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=(filename,os.path.getsize(current_path),Date_str)
else:
if os.path.splitext(current_path)[1].lower()=='.zip' and self.choice_1.GetSelection()<>1:
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['zipfile'])
Date_str=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getctime(current_path)))
#file_size=str(os.path.getsize(current_path))
file_size=HumanSize(os.path.getsize(current_path))
self.list_ctrl_1.SetStringItem(index,1,file_size)
self.list_ctrl_1.SetStringItem(index,2,Date_str)
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=(filename,os.path.getsize(current_path),Date_str)
else:
if os.path.splitext(current_path)[1].lower()=='.rar' and self.choice_1.GetSelection()<>1:
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['rarfile'])
Date_str=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getctime(current_path)))
file_size=HumanSize(os.path.getsize(current_path))
self.list_ctrl_1.SetStringItem(index,1,file_size)
self.list_ctrl_1.SetStringItem(index,2,Date_str)
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=(filename,os.path.getsize(current_path),Date_str)
else:
if os.path.splitext(current_path)[1].lower()=='.jar' and self.choice_1.GetSelection()<>1:
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['jarfile'])
Date_str=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getctime(current_path)))
file_size=HumanSize(os.path.getsize(current_path))
self.list_ctrl_1.SetStringItem(index,1,file_size)
self.list_ctrl_1.SetStringItem(index,2,Date_str)
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=(filename,os.path.getsize(current_path),Date_str)
else:
if os.path.splitext(current_path)[1].lower()=='.umd' and self.choice_1.GetSelection()<>1:
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['umdfile'])
Date_str=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getctime(current_path)))
file_size=HumanSize(os.path.getsize(current_path))
self.list_ctrl_1.SetStringItem(index,1,file_size)
self.list_ctrl_1.SetStringItem(index,2,Date_str)
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=(filename,os.path.getsize(current_path),Date_str)
else:
if os.path.splitext(current_path)[1].lower()=='.epub' and self.choice_1.GetSelection()<>1:
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['epub'])
Date_str=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getctime(current_path)))
file_size=HumanSize(os.path.getsize(current_path))
self.list_ctrl_1.SetStringItem(index,1,file_size)
self.list_ctrl_1.SetStringItem(index,2,Date_str)
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=(filename,os.path.getsize(current_path),Date_str)
else:
if self.choice_1.GetSelection()==3:
index=self.list_ctrl_1.InsertImageStringItem(sys.maxint,filename,self.file_icon_list['file'])
Date_str=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getctime(current_path)))
file_size=HumanSize(os.path.getsize(current_path))
self.list_ctrl_1.SetStringItem(index,1,file_size)
self.list_ctrl_1.SetStringItem(index,2,Date_str)
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=(filename,os.path.getsize(current_path),Date_str)
self.text_ctrl_2.SetValue(GlobalConfig['LastDir'])
self.list_ctrl_1.Focus(RPos)
self.list_ctrl_1.Select(RPos)
self.list_ctrl_1.Refresh()
def OnDirChar(self,event):
global GlobalConfig
key=event.GetKeyCode()
if key==wx.WXK_RIGHT:#Active Selected Item
i=self.list_ctrl_1.GetFocusedItem()
self.ActiveItem(self.list_ctrl_1.GetItemText(i))
return
if key==wx.WXK_LEFT:#Up dir
if GlobalConfig['LastDir']==u'/':return
current_path=GlobalConfig['LastDir']+u"/.."
GlobalConfig['LastDir']=os.path.normpath(current_path)
self.Reload()
return
event.Skip()
def OnReload(self, event): # wxGlade: MyOpenFileDialog.<event_handler>
global GlobalConfig
if os.path.isdir(self.text_ctrl_2.GetValue())== True:
GlobalConfig['LastDir']=self.text_ctrl_2.GetValue()
self.Reload()
else:
dlg = wx.MessageDialog(self, u'目录输入有误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
def OnEnter(self, event): # wxGlade: MyOpenFileDialog.<event_handler>
global GlobalConfig
if os.path.isdir(self.text_ctrl_2.GetValue())== True:
GlobalConfig['LastDir']=self.text_ctrl_2.GetValue()
self.Reload()
else:
dlg = wx.MessageDialog(self, u'目录输入有误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
def OnUpDir(self, event): # wxGlade: MyOpenFileDialog.<event_handler>
global GlobalConfig
GlobalConfig['LastDir']=GlobalConfig['LastDir'].rpartition(u'/')[0]
if GlobalConfig['LastDir'].find('/')==-1:
GlobalConfig['LastDir']+=u'/'
self.text_ctrl_2.SetValue(GlobalConfig['LastDir'])
self.Reload()
def OnSelectDir(self, event): # wxGlade: MyOpenFileDialog.<event_handler>
global GlobalConfig
dlg = wx.DirDialog(self, "Choose a directory:",
style=wx.DD_DEFAULT_STYLE
)
if dlg.ShowModal() == wx.ID_OK:
GlobalConfig['LastDir']=dlg.GetPath()
self.text_ctrl_2.SetValue(dlg.GetPath())
self.Reload()
dlg.Destroy()
def OnItemSelected(self,event):
global GlobalConfig
self.text_ctrl_3.SetValue('')
item=event.GetItem()
preview_buff=u''
filename=item.GetText()
current_path=GlobalConfig['LastDir']+u"/"+filename
current_ext=os.path.splitext(current_path)[1].lower()
if current_ext=='.txt' or current_ext=='.htm' or current_ext=='.html':
coding=DetectFileCoding(current_path)
if coding=='error':return False
try:
file=open(current_path,'r')
except:
dlg = wx.MessageDialog(self, current_path+u' 文件打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return False
i=0
istr=''
while i<20:
try:
istr+=file.readline(500)
except:
dlg = wx.MessageDialog(self, current_path+u' 文件读取错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return False
i+=1
preview_buff=AnyToUnicode(istr,coding)
if current_ext=='.htm' or current_ext=='.html':
preview_buff=htm2txt(preview_buff)
self.text_ctrl_3.SetValue(preview_buff)
file.close()
def OnItemActive(self,event):
global GlobalConfig, MYOS
item=event.GetItem()
filename=item.GetText()
if MYOS != 'Windows':
if GlobalConfig['LastDir']<>'/':
current_path=GlobalConfig['LastDir']+u"/"+filename
else:
current_path=GlobalConfig['LastDir']+filename
current_path=os.path.normpath(current_path)
else:
if filename[1:]==":\\" and not os.path.isdir(filename):
return False #means this driver is not ready
if GlobalConfig['LastDir']<>"ROOT":
current_path=GlobalConfig['LastDir']+u"\\"+filename
else:
current_path=filename
current_ext=os.path.splitext(current_path)[1].lower()
if os.path.isdir(current_path)== True:
if MYOS != 'Windows':
GlobalConfig['LastDir']=os.path.normpath(current_path)
self.text_ctrl_2.SetValue(GlobalConfig['LastDir'])
else:
if current_path.find(":\\\\..")<>-1:
GlobalConfig['LastDir']=u"ROOT"
else:
GlobalConfig['LastDir']=os.path.normpath(current_path)
self.Reload()
else:
if current_ext==".zip" or current_ext==".rar":
dlg=ZipFileDialog(self,current_path)
dlg.ShowModal()
if dlg.selected_files<>[]:
self.zip_file=current_path
self.select_files=dlg.selected_files
self.open_method=dlg.openmethod
dlg.Destroy()
#self.Destroy()
self.Close()
else:
dlg.Destroy()
else:
self.select_files.append(current_path)
#self.Destroy()
self.Close()
def ActiveItem(self,filename):
global GlobalConfig, MYOS
if MYOS != 'Windows':
if GlobalConfig['LastDir']<>'/':
current_path=GlobalConfig['LastDir']+u"/"+filename
else:
current_path=GlobalConfig['LastDir']+filename
current_path=os.path.normpath(current_path)
else:
if filename[1:]==":\\" and not os.path.isdir(filename):
return False #means this driver is not ready
if GlobalConfig['LastDir']<>"ROOT":
current_path=GlobalConfig['LastDir']+u"\\"+filename
else:
current_path=filename
current_ext=os.path.splitext(current_path)[1].lower()
if os.path.isdir(current_path)== True:
if MYOS != 'Windows':
GlobalConfig['LastDir']=os.path.normpath(current_path)
self.text_ctrl_2.SetValue(GlobalConfig['LastDir'])
else:
if current_path.find(":\\\\..")<>-1:
GlobalConfig['LastDir']=u"ROOT"
else:
GlobalConfig['LastDir']=os.path.normpath(current_path)
self.Reload()
else:
if current_ext==".zip" or current_ext==".rar":
dlg=ZipFileDialog(self,current_path)
dlg.ShowModal()
if dlg.selected_files<>[]:
self.zip_file=current_path
self.select_files=dlg.selected_files
self.open_method=dlg.openmethod
dlg.Destroy()
#self.Destroy()
self.Close()
else:
dlg.Destroy()
else:
self.select_files.append(current_path)
#self.Destroy()
self.Close()
def OnCancell(self, event): # wxGlade: MyOpenFileDialog.<event_handler>
self.Destroy()
def OnChoiceSelected(self, event): # wxGlade: MyOpenFileDialog.<event_handler>
self.Reload()
def OnKey(self,event):
key=event.GetKeyCode()
if key==wx.WXK_ESCAPE:
self.Destroy()
else:
event.Skip()
def OnKey_Win(self,event): #windows version
key=event.GetKeyCode()
if key==wx.WXK_RIGHT:#Active Selected Item
i=self.list_ctrl_1.GetFocusedItem()
self.ActiveItem(self.list_ctrl_1.GetItemText(i))
return
if key==wx.WXK_LEFT:#Up dir
current_path=GlobalConfig['LastDir']+u"\\.."
if GlobalConfig['LastDir']==u'ROOT':
return
if current_path.find(":\\\\..")<>-1:
GlobalConfig['LastDir']=u"ROOT"
else:
GlobalConfig['LastDir']=os.path.normpath(current_path)
self.Reload()
return
if key==wx.WXK_ESCAPE:
self.Destroy()
else:
event.Skip()
def OnOpenFiles(self,event):
global GlobalConfig
item=self.list_ctrl_1.GetNextSelected(-1)
while item<>-1:
filename=self.list_ctrl_1.GetItemText(item)
current_path=GlobalConfig['LastDir']+u"/"+filename
self.select_files.append(current_path)
item=self.list_ctrl_1.GetNextSelected(item)
self.open_method="load"
self.Close()
def OnAppendFiles(self,event):
global GlobalConfig
item=self.list_ctrl_1.GetNextSelected(-1)
while item<>-1:
filename=self.list_ctrl_1.GetItemText(item)
current_path=GlobalConfig['LastDir']+u"/"+filename
self.select_files.append(current_path)
item=self.list_ctrl_1.GetNextSelected(item)
self.open_method="append"
self.Close()
def OnWinActive(self,event):
if event.GetActive():self.list_ctrl_1.SetFocus()
def GetListCtrl(self):
return self.list_ctrl_1
def GetSortImages(self):
return (self.dn,self.up)
# end of class MyOpenFileDialog
class BookMarkDialog(wx.Dialog):
def __init__(self, *args, **kwds):
self.filename=''
self.pos=0
# begin wxGlade: BookMarkDialog.__init__
kwds["style"] = wx.DEFAULT_DIALOG_STYLE
wx.Dialog.__init__(self, *args, **kwds)
self.label_3 = wx.StaticText(self, -1, u"文件名:", style=wx.ALIGN_CENTRE)
self.text_ctrl_3 = wx.TextCtrl(self, -1, "", style=wx.TE_READONLY)
self.button_3 = wx.Button(self, -1, u"打开")
self.label_4 = wx.StaticText(self, -1, u"预览: ")
self.text_ctrl_4 = wx.TextCtrl(self, -1, "", style=wx.TE_READONLY)
self.button_4 = wx.Button(self, -1, u"删除")
self.list_box_1 = wx.ListBox(self, -1, choices=[], style=wx.LB_SINGLE)
self.__set_properties()
self.__do_layout()
# end wxGlade
self.Bind(wx.EVT_LISTBOX,self.OnSelected,self.list_box_1)
self.Bind(wx.EVT_LISTBOX_DCLICK,self.OnActive,self.list_box_1)
self.Bind(wx.EVT_BUTTON,self.OnActive,self.button_3)
self.Bind(wx.EVT_BUTTON,self.OnDel,self.button_4)
self.list_box_1.Bind(wx.EVT_CHAR,self.OnKey)
self.Bind(wx.EVT_ACTIVATE,self.OnWinActive)
self.ReDo()
def __set_properties(self):
# begin wxGlade: BookMarkDialog.__set_properties
self.SetTitle(u"收藏夹")
self.SetSize((500, 500))
self.text_ctrl_3.SetMinSize((350, -1))
self.text_ctrl_4.SetMinSize((350, -1))
self.list_box_1.SetMinSize((500,500))
# end wxGlade
def __do_layout(self):
# begin wxGlade: BookMarkDialog.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_2 = wx.BoxSizer(wx.VERTICAL)
sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
sizer_3.Add((10, 20), 0, 0, 0)
sizer_3.Add(self.label_3, 0, 0, 0)
sizer_3.Add(self.text_ctrl_3, 0, 0, 0)
sizer_3.Add((10, 20), 0, 0, 0)
sizer_3.Add(self.button_3, 0, 0, 0)
sizer_3.Add((10, 20), 0, 0, 0)
sizer_2.Add(sizer_3, 1, wx.EXPAND, 0)
sizer_4.Add((10, 20), 0, 0, 0)
sizer_4.Add(self.label_4, 0, wx.ALIGN_RIGHT, 0)
sizer_4.Add(self.text_ctrl_4, 0, 0, 0)
sizer_4.Add((10, 20), 0, 0, 0)
sizer_4.Add(self.button_4, 0, 0, 0)
sizer_4.Add((10, 20), 0, 0, 0)
sizer_2.Add(sizer_4, 1, wx.EXPAND, 0)
sizer_1.Add(sizer_2, 0, wx.EXPAND, 0)
sizer_1.Add(self.list_box_1, 1, wx.EXPAND, 0)
self.SetSizer(sizer_1)
self.Layout()
# end wxGlade
def ReDo(self):
global BookMarkList
bk_name_list=[]
self.list_box_1.Clear()
if BookMarkList.__len__()==0:return
for bk in BookMarkList:
bk_name_list.append(bk['filename'])
self.list_box_1.InsertItems(bk_name_list,0)
self.list_box_1.SetSelection(0)
self.text_ctrl_3.SetValue(BookMarkList[0]['filename'])
self.text_ctrl_4.SetValue(BookMarkList[0]['line'])
def OnSelected(self,event):
global BookMarkList
i=0
while not self.list_box_1.IsSelected(i):
i+=1
if i>=self.list_box_1.GetCount(): return
self.text_ctrl_3.SetValue(BookMarkList[i]['filename'])
self.text_ctrl_4.SetValue(BookMarkList[i]['line'])
def OnActive(self,event):
global BookMarkList
if BookMarkList.__len__()==0:return
i=0
while not self.list_box_1.IsSelected(i):
i+=1
if i>=self.list_box_1.GetCount(): return
self.filename=BookMarkList[i]['filename']
self.pos=BookMarkList[i]['pos']
self.Close()
def OnDel(self,event):
global BookMarkList
if BookMarkList.__len__()==0:return
i=0
while not self.list_box_1.IsSelected(i):
i+=1
if i>=self.list_box_1.GetCount(): return
BookMarkList.__delitem__(i)
self.ReDo()
if i>0:
i-=1
self.list_box_1.SetSelection(i)
self.text_ctrl_3.SetValue(BookMarkList[i]['filename'])
self.text_ctrl_4.SetValue(BookMarkList[i]['line'])
else:
self.text_ctrl_3.SetValue('')
self.text_ctrl_4.SetValue('')
# end of class BookMarkDialog
def OnKey(self,event):
key=event.GetKeyCode()
if key==wx.WXK_ESCAPE:
self.Destroy()
else:
event.Skip()
def OnWinActive(self,event):
if event.GetActive():self.list_box_1.SetFocus()
##class OptionDialog(wx.Dialog):
## def __init__(self, *args, **kwds):
## # begin wxGlade: OptionDialog.__init__
## kwds["style"] = wx.DEFAULT_DIALOG_STYLE
## wx.Dialog.__init__(self, *args, **kwds)
## self.notebook_1 = wx.Notebook(self, -1, style=0)
## self.notebook_1_pane_2 = wx.Panel(self.notebook_1, -1)
## self.notebook_1_pane_1 = wx.Panel(self.notebook_1, -1)
## self.notebook_1_pane_3 = wx.Panel(self.notebook_1, -1)
## self.sizer_3_staticbox = wx.StaticBox(self.notebook_1_pane_3, -1, u"下载")
## self.sizer_4_staticbox = wx.StaticBox(self.notebook_1_pane_3, -1, u"代理服务器")
##
## self.text_ctrl_4 = wx.TextCtrl(self.notebook_1_pane_1, -1, u"《老子》八十一章\n\n 1.道可道,非常道。名可名,非常名。无名天地之始。有名万物之母。故常无欲以观其妙。常有欲以观其徼。此两者同出而异名,同谓之玄。玄之又玄,众妙之门。\n\n 2.天下皆知美之为美,斯恶矣;皆知善之为善,斯不善已。故有无相生,难易相成,长短相形,高下相倾,音声相和,前後相随。是以圣人处无为之事,行不言之教。万物作焉而不辞。生而不有,为而不恃,功成而弗居。夫唯弗居,是以不去。\n\n 3.不尚贤, 使民不争。不贵难得之货,使民不为盗。不见可欲,使民心不乱。是以圣人之治,虚其心,实其腹,弱其志,强其骨;常使民无知、无欲,使夫智者不敢为也。为无为,则无不治。\n\n 4.道冲而用之,或不盈。渊兮似万物之宗。解其纷,和其光,同其尘,湛兮似或存。吾不知谁之子,象帝之先。\n\n 5.天地不仁,以万物为刍狗。圣人不仁,以百姓为刍狗。天地之间,其犹橐迭乎?虚而不屈,动而愈出。多言数穷,不如守中。", style=wx.TE_MULTILINE|wx.TE_READONLY)
## self.label_4 = wx.StaticText(self.notebook_1_pane_1, -1, u"显示方案:")
## self.combo_box_1 = wx.ComboBox(self.notebook_1_pane_1, -1, choices=[], style=wx.CB_DROPDOWN|wx.CB_READONLY)
## self.button_6 = wx.Button(self.notebook_1_pane_1, -1, u"另存为")
## self.button_7 = wx.Button(self.notebook_1_pane_1, -1, u"删除")
## self.static_line_1 = wx.StaticLine(self.notebook_1_pane_1, -1)
## self.button_9 = wx.Button(self.notebook_1_pane_1, -1, u"字体")
## self.button_10 = wx.Button(self.notebook_1_pane_1, -1, u"字体颜色")
## self.button_11 = wx.Button(self.notebook_1_pane_1, -1, u"背景颜色")
## self.label_5 = wx.StaticText(self.notebook_1_pane_2, -1, u"启动:")
## self.checkbox_1 = wx.CheckBox(self.notebook_1_pane_2, -1, u"自动载入上次阅读的文件")
## self.label_5_copy = wx.StaticText(self.notebook_1_pane_2, -1, u"启动:")
## self.checkbox_VerCheck = wx.CheckBox(self.notebook_1_pane_2, -1, u"检查更新")
## self.label_1 = wx.StaticText(self.notebook_1_pane_2, -1, u"自动翻页间隔(秒):")
## self.text_ctrl_1 = wx.TextCtrl(self.notebook_1_pane_2, -1, "")
## self.label_mof = wx.StaticText(self.notebook_1_pane_2, -1, u"最大曾经打开文件菜单数:")
## self.text_ctrl_mof = wx.TextCtrl(self.notebook_1_pane_2, -1, "")
##
## self.label_1_copy = wx.StaticText(self.notebook_1_pane_2, -1, u"连续阅读提醒时间(分钟):")
## self.text_ctrl_1_copy = wx.TextCtrl(self.notebook_1_pane_2, -1, "")
## self.label_1_copy_copy_copy = wx.StaticText(self.notebook_1_pane_2, -1, u"文件选择栏预览:")
## self.checkbox_Preview = wx.CheckBox(self.notebook_1_pane_2, -1, u"是否在文件选择侧边栏中预览文件内容")
## self.label_7 = wx.StaticText(self.notebook_1_pane_2, -1, u"文件选择栏显示")
## self.checkbox_5 = wx.CheckBox(self.notebook_1_pane_2, -1, u"是否在文件选择侧边栏中只显示支持的文件格式")
##
## self.label_2 = wx.StaticText(self.notebook_1_pane_3, -1, u"下载完毕后的缺省动作:")
## self.choice_1 = wx.Choice(self.notebook_1_pane_3, -1, choices=[u"直接阅读", u"另存为文件",u'直接保存在缺省目录'])
## self.label_12 = wx.StaticText(self.notebook_1_pane_3, -1, u"另存为的缺省目录:")
## self.text_ctrl_8 = wx.TextCtrl(self.notebook_1_pane_3, -1, "")
## self.button_1 = wx.Button(self.notebook_1_pane_3, -1, u"选择")
## self.label_11 = wx.StaticText(self.notebook_1_pane_3, -1, u"同时下载的线程个数(需插件支持;不能超过50):")
## self.text_ctrl_7 = wx.TextCtrl(self.notebook_1_pane_3, -1, "10")
## self.label_3 = wx.StaticText(self.notebook_1_pane_3, -1, u"启用代理服务器:")
## self.checkbox_2 = wx.CheckBox(self.notebook_1_pane_3, -1, "")
## self.label_6 = wx.StaticText(self.notebook_1_pane_3, -1, u"代理服务器地址:")
## self.text_ctrl_2 = wx.TextCtrl(self.notebook_1_pane_3, -1, "")
## self.label_8 = wx.StaticText(self.notebook_1_pane_3, -1, u"代理服务器端口:")
## self.text_ctrl_3 = wx.TextCtrl(self.notebook_1_pane_3, -1, "")
## self.label_9 = wx.StaticText(self.notebook_1_pane_3, -1, u"用户名:")
## self.text_ctrl_5 = wx.TextCtrl(self.notebook_1_pane_3, -1, "")
## self.label_10 = wx.StaticText(self.notebook_1_pane_3, -1, u"密码:")
## self.text_ctrl_6 = wx.TextCtrl(self.notebook_1_pane_3, -1, "")
##
##
## self.button_4 = wx.Button(self, -1, u"确定")
## self.button_5 = wx.Button(self, -1, u"取消")
##
## self.__set_properties()
## self.__do_layout()
## # end wxGlade
##
##
## #self.Bind(wx.EVT_BUTTON,self.OnOK,self.button_4)
## self.Bind(wx.EVT_BUTTON,self.OnSelFont,self.button_9)
## self.Bind(wx.EVT_BUTTON,self.OnSelFColor,self.button_10)
## self.Bind(wx.EVT_BUTTON,self.OnSelBColor,self.button_11)
## self.Bind(wx.EVT_BUTTON,self.OnSaveTheme,self.button_6)
## self.Bind(wx.EVT_BUTTON,self.OnDelTheme,self.button_7)
## self.Bind(wx.EVT_BUTTON,self.SelectDir,self.button_1)
## self.Bind(wx.EVT_COMBOBOX,self.OnSel,self.combo_box_1)
## self.Bind(wx.EVT_BUTTON,self.OnOk,self.button_4)
## self.Bind(wx.EVT_BUTTON,self.OnCancell,self.button_5)
## self.text_ctrl_4.Bind(wx.EVT_CHAR,self.OnKey)
## self.Bind(wx.EVT_ACTIVATE,self.OnWinActive)
##
## def __set_properties(self):
## global GlobalConfig,ThemeList
## # begin wxGlade: OptionDialog.__set_properties
## self.SetTitle(u"选项设置")
## self.combo_box_1.SetMinSize((150,-1))
## self.text_ctrl_4.SetMinSize((384, 189))
## self.text_ctrl_1.SetMinSize((30,-1))
## self.text_ctrl_8.SetMinSize((180, -1))
## self.text_ctrl_7.SetMinSize((40, -1))
## self.label_1_copy.SetToolTipString(u"0代表不提醒")
## self.text_ctrl_1_copy.SetMinSize((40, -1))
## self.text_ctrl_1_copy.SetToolTipString(u"0代表不提醒")
## self.text_ctrl_4.SetFont(GlobalConfig['CurFont'])
## self.text_ctrl_4.SetForegroundColour(GlobalConfig['CurFColor'])
## self.text_ctrl_4.SetBackgroundColour(GlobalConfig['CurBColor'])
## self.text_ctrl_4.Refresh()
## txt=self.text_ctrl_4.GetValue()
## self.text_ctrl_4.SetValue(txt)
## self.checkbox_VerCheck.SetValue(GlobalConfig['VerCheckOnStartup'])
## #append drop down list
## for t in ThemeList:
## self.combo_box_1.Append(t['name'])
## #seting load last file check box
## self.checkbox_1.SetValue(GlobalConfig['LoadLastFile'])
## self.checkbox_Preview.SetValue(GlobalConfig['EnableSidebarPreview'])
## self.text_ctrl_1.SetValue(unicode(GlobalConfig['AutoScrollInterval']/1000))
## self.text_ctrl_1_copy.SetValue(unicode(GlobalConfig['RemindInterval']))
## self.checkbox_5.SetValue(not GlobalConfig['ShowAllFileInSidebar'])
## self.text_ctrl_mof.SetMinSize((30, -1))
## self.text_ctrl_mof.SetValue(unicode(GlobalConfig['MaxOpenedFiles']))
##
## self.text_ctrl_2.SetMinSize((200, -1))
## self.text_ctrl_3.SetMinSize((50, -1))
## self.choice_1.Select(GlobalConfig['DAUDF'])
## self.checkbox_2.SetValue(GlobalConfig['useproxy'])
## self.text_ctrl_2.SetValue(unicode(GlobalConfig['proxyserver']))
## self.text_ctrl_3.SetValue(unicode(GlobalConfig['proxyport']))
## self.text_ctrl_5.SetValue(unicode(GlobalConfig['proxyuser']))
## self.text_ctrl_6.SetValue(unicode(GlobalConfig['proxypass']))
## self.text_ctrl_7.SetValue(unicode(GlobalConfig['numberofthreads']))
## self.text_ctrl_8.SetValue(unicode(GlobalConfig['defaultsavedir']))
##
## # end wxGlade
##
## def __do_layout(self):
## # begin wxGlade: OptionDialog.__do_layout
## sizer_5 = wx.BoxSizer(wx.VERTICAL)
## grid_sizer_1 = wx.GridSizer(1, 5, 0, 0)
##
## sizer_2 = wx.BoxSizer(wx.VERTICAL)
## sizer_4 = wx.StaticBoxSizer(self.sizer_4_staticbox, wx.VERTICAL)
## sizer_15 = wx.BoxSizer(wx.HORIZONTAL)
## sizer_14 = wx.BoxSizer(wx.HORIZONTAL)
## sizer_13 = wx.BoxSizer(wx.HORIZONTAL)
## sizer_12 = wx.BoxSizer(wx.HORIZONTAL)
## sizer_8 = wx.BoxSizer(wx.HORIZONTAL)
## sizer_3 = wx.StaticBoxSizer(self.sizer_3_staticbox, wx.VERTICAL)
##
## sizer_17 = wx.BoxSizer(wx.HORIZONTAL)
## sizer_18 = wx.BoxSizer(wx.HORIZONTAL)
## sizer_16 = wx.BoxSizer(wx.HORIZONTAL)
##
##
## sizer_9 = wx.BoxSizer(wx.VERTICAL)
## sizer_20 = wx.BoxSizer(wx.HORIZONTAL)
## sizer_1_copy_copy_copy = wx.BoxSizer(wx.HORIZONTAL)
## sizer_1_copy_copy = wx.BoxSizer(wx.HORIZONTAL)
## sizer_1_copy = wx.BoxSizer(wx.HORIZONTAL)
## sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
## sizer_mof = wx.BoxSizer(wx.HORIZONTAL)
## sizer_10 = wx.BoxSizer(wx.HORIZONTAL)
## sizer_10_copy = wx.BoxSizer(wx.HORIZONTAL)
## sizer_10_copy_1 = wx.BoxSizer(wx.HORIZONTAL)
## sizer_6 = wx.BoxSizer(wx.VERTICAL)
## sizer_11 = wx.BoxSizer(wx.HORIZONTAL)
## sizer_7 = wx.BoxSizer(wx.HORIZONTAL)
## sizer_6.Add(self.text_ctrl_4, 1, wx.EXPAND, 0)
## sizer_7.Add(self.label_4, 0, wx.ALIGN_CENTER_VERTICAL, 0)
## sizer_7.Add((10, 20), 0, 0, 0)
## sizer_7.Add(self.combo_box_1, 0, 0, 0)
## sizer_7.Add((10, 20), 0, 0, 0)
## sizer_7.Add(self.button_6, 0, 0, 0)
## sizer_7.Add((10, 20), 0, 0, 0)
## sizer_7.Add(self.button_7, 0, 0, 0)
## sizer_6.Add(sizer_7, 0, wx.EXPAND, 0)
## sizer_6.Add(self.static_line_1, 0, wx.EXPAND, 0)
## sizer_11.Add((20, 20), 0, 0, 0)
## sizer_11.Add(self.button_9, 0, 0, 0)
## sizer_11.Add((60, 20), 0, 0, 0)
## sizer_11.Add(self.button_10, 0, 0, 0)
## sizer_11.Add((60, 20), 0, 0, 0)
## sizer_11.Add(self.button_11, 0, 0, 0)
## sizer_11.Add((20, 20), 0, 0, 0)
## sizer_6.Add(sizer_11, 0, wx.EXPAND, 0)
## self.notebook_1_pane_1.SetSizer(sizer_6)
## sizer_10.Add(self.label_5, 0, 0, 0)
## sizer_10.Add(self.checkbox_1, 0, 0, 0)
## sizer_9.Add(sizer_10, 0, wx.EXPAND, 0)
## sizer_9.Add((20, 20), 0, 0, 0)
## sizer_10_copy_1.Add(self.label_5_copy, 0, 0, 0)
## sizer_10_copy_1.Add(self.checkbox_VerCheck, 0, 0, 0)
## sizer_10_copy.Add(sizer_10_copy_1, 0, wx.EXPAND, 0)
## sizer_9.Add(sizer_10_copy, 0, wx.EXPAND, 0)
## sizer_9.Add((20, 20), 0, 0, 0)
## sizer_1.Add(self.label_1, 0, wx.ALIGN_BOTTOM, 0)
## sizer_1.Add(self.text_ctrl_1, 0, 0, 0)
## sizer_9.Add(sizer_1, 0, wx.EXPAND, 0)
## sizer_9.Add((20, 20), 0, 0, 0)
## sizer_1_copy.Add(self.label_1_copy, 0, wx.ALIGN_BOTTOM, 0)
## sizer_1_copy.Add(self.text_ctrl_1_copy, 0, 0, 0)
## sizer_9.Add(sizer_1_copy, 0, wx.EXPAND, 0)
## sizer_9.Add((20, 20), 0, 0, 0)
## sizer_1_copy_copy_copy.Add(self.label_1_copy_copy_copy, 0, wx.ALIGN_BOTTOM, 0)
## sizer_1_copy_copy_copy.Add(self.checkbox_Preview, 0, 0, 0)
## sizer_9.Add(sizer_1_copy_copy_copy, 0, wx.EXPAND, 0)
## sizer_9.Add((20, 20), 0, 0, 0)
## sizer_20.Add(self.label_7, 0, wx.ALIGN_BOTTOM, 0)
## sizer_20.Add(self.checkbox_5, 0, 0, 0)
## sizer_9.Add(sizer_20, 0, wx.EXPAND, 0)
## sizer_9.Add((20, 20), 0, 0, 0)
## sizer_mof.Add(self.label_mof, 0, wx.ALIGN_BOTTOM, 0)
## sizer_mof.Add(self.text_ctrl_mof, 0, 0, 0)
## sizer_9.Add(sizer_mof, 0, wx.EXPAND, 0)
## self.notebook_1_pane_2.SetSizer(sizer_9)
##
## sizer_16.Add(self.label_2, 0, wx.ALL, 5)
## sizer_16.Add(self.choice_1, 0, 0, 0)
## sizer_3.Add(sizer_16, 1, wx.EXPAND, 0)
## sizer_18.Add(self.label_12, 0, wx.ALL, 5)
## sizer_18.Add(self.text_ctrl_8, 0, 0, 0)
## sizer_18.Add(self.button_1, 0, 0, 0)
## sizer_3.Add(sizer_18, 1, wx.EXPAND, 0)
## sizer_17.Add(self.label_11, 0, wx.ALL, 5)
## sizer_17.Add(self.text_ctrl_7, 0, 0, 0)
## sizer_3.Add(sizer_17, 1, wx.EXPAND, 0)
##
##
## sizer_2.Add(sizer_3, 1, wx.EXPAND, 0)
## sizer_8.Add(self.label_3, 0, wx.ALL, 5)
## sizer_8.Add(self.checkbox_2, 0, wx.ALL, 5)
## sizer_4.Add(sizer_8, 1, wx.EXPAND, 0)
## sizer_12.Add(self.label_6, 0, wx.ALL, 5)
## sizer_12.Add(self.text_ctrl_2, 0, 0, 0)
## sizer_4.Add(sizer_12, 1, wx.EXPAND, 0)
## sizer_13.Add(self.label_8, 0, wx.ALL, 5)
## sizer_13.Add(self.text_ctrl_3, 0, 0, 0)
## sizer_4.Add(sizer_13, 1, wx.EXPAND, 0)
## sizer_14.Add(self.label_9, 0, wx.ALL, 5)
## sizer_14.Add(self.text_ctrl_5, 0, 0, 0)
## sizer_4.Add(sizer_14, 1, wx.EXPAND, 0)
## sizer_15.Add(self.label_10, 0, wx.ALL, 5)
## sizer_15.Add(self.text_ctrl_6, 0, 0, 0)
## sizer_4.Add(sizer_15, 1, wx.EXPAND, 0)
## sizer_2.Add(sizer_4, 1, wx.EXPAND, 0)
## self.notebook_1_pane_3.SetSizer(sizer_2)
##
##
## self.notebook_1.AddPage(self.notebook_1_pane_1, u"界面设置")
## self.notebook_1.AddPage(self.notebook_1_pane_2, u"控制设置")
## self.notebook_1.AddPage(self.notebook_1_pane_3, u"下载设置")
## sizer_5.Add(self.notebook_1, 1, wx.EXPAND, 0)
## grid_sizer_1.Add((20, 20), 0, 0, 0)
## grid_sizer_1.Add(self.button_4, 0, 0, 0)
## grid_sizer_1.Add((20, 20), 0, 0, 0)
## grid_sizer_1.Add(self.button_5, 0, 0, 0)
## grid_sizer_1.Add((20, 20), 0, 0, 0)
## sizer_5.Add(grid_sizer_1, 0, wx.EXPAND, 0)
## self.SetSizer(sizer_5)
## sizer_5.Fit(self)
## self.Layout()
## # end wxGlade
##
## def OnSelFont(self,event):
## global GlobalConfig
## data=wx.FontData()
## data.SetInitialFont(GlobalConfig['CurFont'])
## data.SetColour(GlobalConfig['CurFColor'])
## data.EnableEffects(True)
## dlg = wx.FontDialog(self, data)
## if dlg.ShowModal() == wx.ID_OK:
## ft=dlg.GetFontData().GetChosenFont()
## self.text_ctrl_4.SetFont(ft)
## txt=self.text_ctrl_4.GetValue()
## self.text_ctrl_4.SetValue(txt)
##
## dlg.Destroy()
##
## def OnSelFColor(self,event):
## global GlobalConfig
## dlg = wx.ColourDialog(self)
## dlg.GetColourData().SetChooseFull(True)
## if dlg.ShowModal() == wx.ID_OK:
## data = dlg.GetColourData()
## self.text_ctrl_4.SetForegroundColour(data.GetColour())
## self.Refresh()
## #self.Update()
## txt=self.text_ctrl_4.GetValue()
## self.text_ctrl_4.SetValue(txt)
## dlg.Destroy()
##
## def OnSelBColor(self,event):
## global GlobalConfig
## dlg = wx.ColourDialog(self)
## dlg.GetColourData().SetChooseFull(True)
## if dlg.ShowModal() == wx.ID_OK:
## data = dlg.GetColourData()
## self.text_ctrl_4.SetBackgroundColour(data.GetColour())
## self.text_ctrl_4.Refresh()
## txt=self.text_ctrl_4.GetValue()
## self.text_ctrl_4.SetValue(txt)
##
## dlg.Destroy()
##
## def OnSaveTheme(self,event):
## global ThemeList
## l={}
## l['name']=''
## while l['name']=='':
## dlg = wx.TextEntryDialog(
## self, u'请输入新显示方案的名称(不能为空):',
## u'另存为新方案')
## if dlg.ShowModal() == wx.ID_OK:
## l['name']=dlg.GetValue().strip()
## dlg.Destroy()
## else:
## dlg.Destroy()
## return
## for t in ThemeList:
## if t['name']==l['name']:
## dlg = wx.MessageDialog(self, u'已经有叫这个名字的显示方案了,你确定要覆盖原有方案吗?',u"提示!",wx.YES_NO|wx.ICON_QUESTION)
## if dlg.ShowModal()==wx.ID_NO:
## dlg.Destroy()
## return
## else:
## ThemeList.remove(t)
## l['font']=self.text_ctrl_4.GetFont()
## l['fcolor']=self.text_ctrl_4.GetForegroundColour()
## l['bcolor']=self.text_ctrl_4.GetBackgroundColour()
## l['config']=unicode(l['font'].GetPointSize())+u':'+unicode(l['font'].GetFamily())+u':'+unicode(l['font'].GetStyle())+u':'+unicode(l['font'].GetWeight())+u':'+unicode(l['font'].GetUnderlined())+u':'+l['font'].GetFaceName()+u':'+unicode(l['font'].GetDefaultEncoding())+u':'+unicode(l['fcolor'])+u':'+unicode(l['bcolor'])
## ThemeList.append(l)
## self.combo_box_1.Clear()
## for t in ThemeList:
## self.combo_box_1.Append(t['name'])
## self.combo_box_1.SetSelection(self.combo_box_1.GetCount()-1)
##
##
##
##
## def OnDelTheme(self,event):
## global ThemeList
## name=self.combo_box_1.GetStringSelection()
## i=0
## if name<>u'':
## for t in ThemeList:
## if t['name']==name:
## ThemeList.remove(t)
## break
## i+=1
## self.combo_box_1.Clear()
## self.combo_box_1.SetValue('')
## for t in ThemeList:
## self.combo_box_1.Append(t['name'])
## self.combo_box_1.SetSelection(0)
##
##
##
## def OnSel(self,event):
## global ThemeList
## name=self.combo_box_1.GetStringSelection()
## if name<>u'':
## for t in ThemeList:
## if t['name']==name:
## self.text_ctrl_4.SetFont(t['font'])
## self.text_ctrl_4.SetForegroundColour(t['fcolor'])
## self.text_ctrl_4.SetBackgroundColour(t['bcolor'])
## self.text_ctrl_4.Refresh()
## txt=self.text_ctrl_4.GetValue()
## self.text_ctrl_4.SetValue(txt)
## break
##
## def OnOk(self,event):
## global ThemeList,GlobalConfig
## GlobalConfig['CurFont']=self.text_ctrl_4.GetFont()
## GlobalConfig['CurFColor']=self.text_ctrl_4.GetForegroundColour()
## GlobalConfig['CurBColor']=self.text_ctrl_4.GetBackgroundColour()
## GlobalConfig['LoadLastFile']=self.checkbox_1.GetValue()
## GlobalConfig['EnableSidebarPreview']=self.checkbox_Preview.GetValue()
## GlobalConfig['VerCheckOnStartup']=self.checkbox_VerCheck.GetValue()
## if GlobalConfig['ShowAllFileInSidebar']==self.checkbox_5.GetValue():
## self.GetParent().UpdateSidebar=True
## GlobalConfig['ShowAllFileInSidebar']=not self.checkbox_5.GetValue()
##
## try:
## GlobalConfig['AutoScrollInterval']=float(self.text_ctrl_1.GetValue())*1000
## except:
## GlobalConfig['AutoScrollInterval']=12000
## try:
## GlobalConfig['MaxOpenedFiles']=abs(int(self.text_ctrl_mof.GetValue()))
## except:
## GlobalConfig['MaxOpenedFiles']=5
## try:
## GlobalConfig['RemindInterval']=abs(int(self.text_ctrl_1_copy.GetValue()))
## except:
## GlobalConfig['RemindInterval']=60
##
## GlobalConfig['DAUDF']=self.choice_1.GetSelection()
## GlobalConfig['useproxy']=self.checkbox_2.GetValue()
## GlobalConfig['proxyserver']=self.text_ctrl_2.GetValue()
## try:
## GlobalConfig['proxyport']=int(self.text_ctrl_3.GetValue())
## except:
## GlobalConfig['proxyport']=0
## GlobalConfig['proxyuser']=self.text_ctrl_5.GetValue()
## GlobalConfig['proxypass']=self.text_ctrl_6.GetValue()
## try:
## GlobalConfig['numberofthreads']=int(self.text_ctrl_7.GetValue())
## except:
## GlobalConfig['numberofthreads']=1
## if GlobalConfig['numberofthreads']<=0 or GlobalConfig['numberofthreads']>50:
## GlobalConfig['numberofthreads']=1
## if not os.path.exists(self.text_ctrl_8.GetValue()):
## GlobalConfig['defaultsavedir']=''
## else:
## GlobalConfig['defaultsavedir']=self.text_ctrl_8.GetValue()
## if GlobalConfig['defaultsavedir']=='' and GlobalConfig['DAUDF']==2:
## dlg = wx.MessageDialog(self, u'请指定正确的缺省保存目录!',
## u'出错了!',
## wx.OK | wx.ICON_ERROR
## )
## dlg.ShowModal()
## dlg.Destroy()
## return
##
## self.Destroy()
##
## def OnCancell(self,event):
## self.Destroy()
##
## def OnKey(self,event):
## key=event.GetKeyCode()
## if key==wx.WXK_ESCAPE:
## self.Destroy()
## else:
## event.Skip()
##
##
## def OnWinActive(self,event):
## if event.GetActive():self.text_ctrl_4.SetFocus()
##
## def SelectDir(self,event):
## dlg = wx.DirDialog(self, u"请选择目录:",defaultPath=GlobalConfig['LastDir'],
## style=wx.DD_DEFAULT_STYLE
## )
## if dlg.ShowModal() == wx.ID_OK:
## self.text_ctrl_8.SetValue(dlg.GetPath())
##
## dlg.Destroy()
##
##class HelpDialog(wx.Dialog):
## def __init__(self, parent,mode="help"):
## # begin wxGlade: HelpDialog.__init__
## #kwds["style"] = wx.DEFAULT_DIALOG_STYLE
## wx.Dialog.__init__(self,parent,id=-1,title="")
## self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE|wx.TE_READONLY)
## self.button_1 = wx.Button(self, -1, u"确定")
##
## self.__set_properties(mode)
## self.__do_layout()
## # end wxGlade
## self.Bind(wx.EVT_BUTTON,self.OnOK,self.button_1)
## self.text_ctrl_1.Bind(wx.EVT_CHAR,self.OnKey)
## self.Bind(wx.EVT_ACTIVATE,self.OnWinActive)
##
## def __set_properties(self,mode):
## # begin wxGlade: HelpDialog.__set_properties
## self.SetTitle(u"帮助")
## if mode=="help":self.text_ctrl_1.SetMinSize((500,400))
## else:
## self.text_ctrl_1.SetMinSize((700,400))
## self.text_ctrl_1.SetFont(wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, ""))
## # end wxGlade
## if mode=="help":fname=cur_file_dir()+u"/LiteBook_Readme.txt"
## else:
## fname=cur_file_dir()+u"/LiteBook_WhatsNew.txt"
### try:
## f=open(fname,'r')
## t_buff=f.read()
### except:
### dlg = wx.MessageDialog(self, u'帮助文件LiteBook_Readme.txt打开错误!',u"错误!",wx.OK|wx.ICON_ERROR)
### dlg.ShowModal()
### dlg.Destroy()
### return False
## coding=DetectFileCoding(GlobalConfig['ConfigDir']+u"/LiteBook_Readme.txt")
## if coding=='error': return False
## utext=AnyToUnicode(t_buff,coding)
## self.text_ctrl_1.SetValue(utext)
## f.close()
##
## def __do_layout(self):
## # begin wxGlade: HelpDialog.__do_layout
## sizer_1 = wx.BoxSizer(wx.VERTICAL)
## sizer_1.Add(self.text_ctrl_1, 1, wx.EXPAND, 0)
## sizer_1.Add(self.button_1, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
## self.SetSizer(sizer_1)
## sizer_1.Fit(self)
## self.Layout()
## # end wxGlade
##
## def OnOK(self,event):
## self.Destroy()
##
## def OnKey(self,event):
## key=event.GetKeyCode()
## if key==wx.WXK_ESCAPE:
## self.Destroy()
## else:
## event.Skip()
##
##
## def OnWinActive(self,event):
## if event.GetActive():self.text_ctrl_1.SetFocus()
### end of class HelpDialog
##
####class LiteBookApp(wx.PySimpleApp):
#### def __init__(self, *args, **kwds):
#### appname="litebook-"+wx.GetUserId()
#### m_checker=wx.SingleInstanceChecker(appname)
#### if m_checker.IsAnotherRunning()==True:
#### wx.LogError("已经有一个LiteBook的进程正在运行中")
#### print "error"
#### return False
#### wx.PySimpleApp.__init__(self, *args, **kwds)
class ClockThread:
def __init__(self,win):
self.win=win
self.running=True
thread.start_new_thread(self.run, ())
def stop(self):
self.running=False
def run(self):
global GlobalConfig,Ticking
rt=0
t=0
while self.running:
if Ticking:
t+=1
rt+=1
thour=int(t/3600)
tmin=int(t%3600/60)
tsec=int(t%3600%60)
if rt==GlobalConfig['RemindInterval']*60:
evt1=ReadTimeAlert(ReadTime=unicode(thour)+u'小时'+unicode(tmin)+u'分钟')
wx.PostEvent(self.win,evt1)
rt=0
evt = UpdateStatusBarEvent(FieldNum = 2, Value =u'你已经阅读了 '+unicode(thour)+u'小时'+unicode(tmin)+u'分钟' )
wx.PostEvent(self.win, evt)
time.sleep(1)
class DisplayPosThread():
def __init__(self,win):
self.win=win
self.running=True
thread.start_new_thread(self.run, ())
def stop(self):
self.running=False
def run(self):
global OnScreenFileList
while self.running:
## evt=GetPosEvent()
#wx.PostEvent(self.win, evt)
percent=self.win.text_ctrl_1.GetPosPercent()
(rlist,i,cname)=self.win.GetChapter()
if percent<>False:
percent=int(percent)
try:
txt=unicode(percent)+u'%;'+cname+';'+OnScreenFileList[0][0]
except:
txt=" "
evt = UpdateStatusBarEvent(FieldNum = 0, Value =txt)
else:
evt = UpdateStatusBarEvent(FieldNum = 0, Value ='')
wx.PostEvent(self.win, evt)
time.sleep(0.5)
class VersionCheckThread():
def __init__(self,win,notify=True):
self.win=win
self.running=True
thread.start_new_thread(self.run, (notify,))
def stop(self):
self.running=False
def run(self,notify):
global I_Version
upgrade=False
osd={'Windows':'win','Linux':'linux','Darwin':'mac'}
(iver,tver,wtsn)=VersionCheck()
url=''
if not iver:
msg=u'版本检查过程中出错!'
else:
ver_f=iver
if ver_f>I_Version:
msg=u'LiteBook ver'+tver+u' 已经发布!\n'+wtsn
url='http://code.google.com/p/litebook-project/downloads/list'
upgrade=True
else:
msg=u'你使用的LiteBook已经是最新版本了。'
if not notify and not upgrade:
return
else:
evt=VerCheckEvent(imsg = msg, iurl = url)
wx.PostEvent(self.win, evt)
class AutoCountThread():
def __init__(self,win):
self.win=win
self.running=True
thread.start_new_thread(self.run, ())
def stop(self):
self.running=False
def run(self):
global GlobalConfig
i=int(GlobalConfig['AutoScrollInterval']/1000)
while self.running:
if self.win.autoscroll:
evt = UpdateStatusBarEvent(FieldNum = 1, Value =u"自动翻页已开启:"+unicode(i))
wx.PostEvent(self.win, evt)
if i==0:
i=int(GlobalConfig['AutoScrollInterval']/1000)
evt=ScrollDownPage()
wx.PostEvent(self.win, evt)
#self.win.text_ctrl_1.ScrollPages(1)
else:
i-=1
else:
evt = UpdateStatusBarEvent(FieldNum = 1, Value =u"自动翻页已关闭")
wx.PostEvent(self.win, evt)
time.sleep(1)
class MyConfig(ConfigParser.SafeConfigParser):
def write(self, fp):
"""Write an .ini-format representation of the configuration state."""
if self._defaults:
fp.write("[%s]\n" % ConfigParser.DEFAULTSECT)
for (key, value) in self._defaults.items():
fp.write("%s = %s\n" % (key, unicode(value).replace('\n', '\n\t')))
fp.write("\n")
for section in self._sections:
fp.write("[%s]\n" % section)
for (key, value) in self._sections[section].items():
if key != "__name__":
fp.write("%s = %s\n" %
(key, unicode(value).replace('\n', '\n\t')))
fp.write("\n")
class PreviewFrame(wx.Frame):
"""The Preview Frame for dir sidebar"""
def __init__(self, *args, **kwds):
# begin wxGlade: PreviewFrame.__init__
kwds["style"] = wx.CAPTION|wx.FRAME_TOOL_WINDOW
wx.Frame.__init__(self, *args, **kwds)
self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE|wx.TE_READONLY)
self.__set_properties()
self.__do_layout()
# end wxGlade
def __set_properties(self):
# begin wxGlade: PreviewFrame.__set_properties
self.SetTitle(u"预览")
self.SetSize((400, 200))
# end wxGlade
def __do_layout(self):
# begin wxGlade: PreviewFrame.__do_layout
sizer_3 = wx.BoxSizer(wx.VERTICAL)
sizer_3.Add(self.text_ctrl_1, 1, wx.EXPAND, 0)
self.SetSizer(sizer_3)
sizer_3.Fit(self)
self.Layout()
# end wxGlade
def SetText(self,strtxt):
self.text_ctrl_1.SetValue(strtxt)
# end of class PreviewFrame
class VerCheckDialog(wx.Dialog):
def __init__(self,parent,msg):
wx.Dialog.__init__(self, parent,-1,u'版本检查结果')
sizer = wx.BoxSizer(wx.VERTICAL)
txtctrl = wx.TextCtrl(self,-1,size=(300,200),style=wx.TE_MULTILINE|wx.TE_READONLY )
sizer.Add(txtctrl, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL,5)
txtctrl.SetValue(msg)
line = wx.StaticLine(self, -1, size=(20,-1), style=wx.LI_HORIZONTAL)
sizer.Add(line, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.RIGHT|wx.TOP, 5)
btnsizer = wx.StdDialogButtonSizer()
btn_ok = wx.Button(self,wx.ID_OK,label=u'确定')
btn_ok.SetDefault()
btnsizer.AddButton(btn_ok)
btn_download = wx.Button(self,wx.ID_APPLY,label=u'下载')
btnsizer.AddButton(btn_download)
btnsizer.Realize()
sizer.Add(btnsizer, 1, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
self.SetSizer(sizer)
sizer.Fit(self)
self.Bind(wx.EVT_BUTTON,self.OnOK,btn_ok)
self.Bind(wx.EVT_BUTTON,self.OnDown,btn_download)
self.SetTitle
def OnOK(self,event):
self.Destroy()
def OnDown(self,evt):
import webbrowser
webbrowser.open('http://code.google.com/p/litebook-project/downloads/list')
##class VerCheckDialog(wx.Dialog):
## def __init__(self,msg,url):
## #begin wxGlade: VerCheckDialog.__init__
## #kwds["style"] = wx.DEFAULT_DIALOG_STYLE
## wx.Dialog.__init__(self,None,-1)
## if url<>'':
## self.label_1 = hl.HyperLinkCtrl(self, wx.ID_ANY,msg,URL=url)
## else:
## self.label_1 = wx.StaticText(self, -1, msg)
## self.button_1 = wx.Button(self, -1, " OK ")
## self.Bind(wx.EVT_BUTTON,self.OnOK,self.button_1)
## self.__set_properties()
## self.__do_layout()
## # end wxGlade
##
## def __set_properties(self):
## # begin wxGlade: VerCheckDialog.__set_properties
## self.SetTitle(u"检查更新")
## # end wxGlade
##
## def __do_layout(self):
## # begin wxGlade: VerCheckDialog.__do_layout
## sizer_1 = wx.BoxSizer(wx.VERTICAL)
## sizer_2 = wx.BoxSizer(wx.VERTICAL)
## sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
## sizer_2_copy = wx.BoxSizer(wx.VERTICAL)
## sizer_3_copy = wx.BoxSizer(wx.HORIZONTAL)
## sizer_2_copy.Add((200, 40), 0, wx.EXPAND, 0)
## sizer_3_copy.Add((20, 20), 1, wx.EXPAND, 0)
## sizer_3_copy.Add(self.label_1, 0, 0, 0)
## sizer_3_copy.Add((20, 20), 1, wx.EXPAND, 0)
## sizer_2_copy.Add(sizer_3_copy, 1, wx.EXPAND, 0)
## sizer_1.Add(sizer_2_copy, 1, wx.EXPAND, 0)
## sizer_2.Add((200, 20), 0, wx.EXPAND, 0)
## sizer_3.Add((20, 20), 1, wx.EXPAND, 0)
## sizer_3.Add(self.button_1, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
## sizer_3.Add((20, 20), 1, wx.EXPAND, 0)
## sizer_2.Add(sizer_3, 1, wx.EXPAND, 0)
## sizer_2.Add((200, 20), 0, wx.EXPAND, 0)
## sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
## self.SetSizer(sizer_1)
## sizer_1.Fit(self)
## self.Layout()
## # end wxGlade
##
### end of class VerCheckDialog
## def OnOK(self,event):
## self.Destroy()
class FileHistoryDialog(wx.Dialog,wx.lib.mixins.listctrl.ColumnSorterMixin):
def __init__(self, *args, **kwds):
# begin wxGlade: FileHistory.__init__
kwds["style"] = wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.THICK_FRAME
wx.Dialog.__init__(self, *args, **kwds)
self.list_ctrl_1 = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
self.button_1 = wx.Button(self, -1, u"打开")
self.button_2 = wx.Button(self, -1, u"取消")
self.button_3 = wx.Button(self, -1, u"全部清空")
self.__set_properties()
self.__do_layout()
# end wxGlade
self.Bind(wx.EVT_BUTTON, self.OnLoadFile, self.button_1)
self.Bind(wx.EVT_BUTTON, self.OnCancell, self.button_2)
self.Bind(wx.EVT_BUTTON, self.clearHistory, self.button_3)
self.Bind(wx.EVT_LIST_ITEM_ACTIVATED,self.OnLoadFile,self.list_ctrl_1)
self.list_ctrl_1.Bind(wx.EVT_CHAR,self.OnKey)
self.list_ctrl_1.InsertColumn(0,u'文件名',width=300)
self.list_ctrl_1.InsertColumn(2,u'日期',width=120)
self.image_list=wx.ImageList(16,16,mask=False,initialCount=5)
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/up.png",wx.BITMAP_TYPE_ANY)
self.up=self.image_list.Add(bmp)
#self.file_icon_list["up"]=8
bmp=wx.Bitmap(GlobalConfig['IconDir']+u"/down.png",wx.BITMAP_TYPE_ANY)
self.dn=self.image_list.Add(bmp)
self.list_ctrl_1.AssignImageList(self.image_list,wx.IMAGE_LIST_SMALL)
#self.file_icon_list["down"]=9
self.itemDataMap={}
wx.lib.mixins.listctrl.ColumnSorterMixin.__init__(self,3)
self.filename=''
self.ftype=''
self.zfilename=''
self.load_history()
def __set_properties(self):
# begin wxGlade: FileHistory.__set_properties
self.SetTitle(u"已打开文件历史")
self.SetSize((700, 700))
# end wxGlade
def __do_layout(self):
# begin wxGlade: FileHistory.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_1.Add(self.list_ctrl_1, 8, wx.EXPAND, 0)
sizer_1.Add((450, 5), 0, 0, 0)
sizer_2.Add((20, 20), 0, 0, 0)
sizer_2.Add(self.button_1, 0, 0, 0)
sizer_2.Add((20, 20), 0, 0, 0)
sizer_2.Add(self.button_2, 0, 0, 0)
sizer_2.Add((20, 20), 0, 0, 0)
sizer_2.Add(self.button_3, 0, 0, 0)
sizer_2.Add((20, 20), 0, 0, 0)
sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
sizer_1.Add((20, 5), 0, 0, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
# end wxGlade
#unicode(filename)+"','"+ftype+"','"+unicode(zfile)+"',"+str(time.time())
def load_history(self):
global SqlCur
SqlCur.execute("select * from book_history order by date desc")
for row in SqlCur:
filename=row[0]
ftype=row[1]
zfilename=row[2]
filedate=row[3]
filedate_data=filedate
filedate=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(filedate))
if ftype<>'normal':
filename=zfilename+"|"+filename
index=self.list_ctrl_1.InsertStringItem(sys.maxint,filename)
self.list_ctrl_1.SetStringItem(index,1,filedate)
self.list_ctrl_1.SetItemData(index,index)
self.itemDataMap[index]=(filename,filedate_data)
def GetSortImages(self):
return (self.dn,self.up)
def GetListCtrl(self):
return self.list_ctrl_1
def OnCancell(self, event):
self.Hide()
def clearHistory(self, event):
global SqlCon,SqlCur
dlg=wx.MessageDialog(self,u"此操作将清除所有已打开文件历史,是否继续?",u"清除已打开文件历史",wx.YES_NO|wx.NO_DEFAULT)
if dlg.ShowModal()==wx.ID_YES:
SqlCur.execute("delete from book_history")
SqlCon.commit()
self.list_ctrl_1.DeleteAllItems()
dlg.Destroy()
self.Hide()
def OnLoadFile(self, event):
filepath=self.list_ctrl_1.GetItemText(self.list_ctrl_1.GetFirstSelected())
if filepath.find("|")==-1:
fname=joinBookPath(filepath)
self.Parent.LoadFile((fname,))
else:
(zfilename,filename)=filepath.split('|',1)
zfilename=joinBookPath(zfilename)
self.Parent.LoadFile((filename,),'zip',zfilename)
self.Hide()
def OnKey(self,event):
key=event.GetKeyCode()
if key==wx.WXK_ESCAPE:
self.Hide()
else:
event.Skip()
# end of class FileHistory
class Search_Web_Dialog(wx.Dialog):
def __init__(self, *args, **kwds):
global SqlCur
# begin wxGlade: Search_Web_Dialog.__init__
kwds["style"] = wx.DEFAULT_DIALOG_STYLE
wx.Dialog.__init__(self, *args, **kwds)
weblist=[]
flist=glob.glob(cur_file_dir()+"/plugin/*.py")
for f in flist:
bname=os.path.basename(f)
weblist.append(bname[:-3])
weblist.insert(0,u'搜索所有网站')
self.sizer_1_staticbox = wx.StaticBox(self, -1, u"搜索小说网站")
self.label_2 = wx.StaticText(self, -1, u"关键字: ")
self.text_ctrl_2 = wx.TextCtrl(self, -1, "")
self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_WORDWRAP)
self.label_3 = wx.StaticText(self, -1, u"选择网站:")
self.choice_1 = wx.Choice(self, -1, choices=weblist)
self.button_3 = wx.Button(self, -1, u" 搜索 ")
self.button_4 = wx.Button(self, -1, u" 取消 ")
self.Bind(wx.EVT_BUTTON, self.OnOK, self.button_3)
self.Bind(wx.EVT_BUTTON, self.OnCancell, self.button_4)
self.text_ctrl_2.Bind(wx.EVT_CHAR,self.OnKey)
self.choice_1.Bind(wx.EVT_CHAR,self.OnKey)
self.Bind(wx.EVT_CHOICE, self.OnChosen, self.choice_1)
self.__set_properties()
self.__do_layout()
# end wxGlade
def __set_properties(self):
global GlobalConfig
# begin wxGlade: Search_Web_Dialog.__set_properties
self.SetTitle(u"搜索网站")
self.text_ctrl_2.SetMinSize((200, 35))
self.choice_1.SetMinSize((200, 35))
if GlobalConfig['lastweb']=='' or not os.path.exists(cur_file_dir()+"/plugin/"+GlobalConfig['lastweb']+'.py'):
self.choice_1.Select(0)
self.ShowDesc(self.choice_1.GetString(0))
else:
self.choice_1.SetStringSelection(GlobalConfig['lastweb'])
self.ShowDesc(GlobalConfig['lastweb'])
self.text_ctrl_2.SetValue(GlobalConfig['lastwebsearchkeyword'])
self.text_ctrl_1.SetMinSize((285, 84))
# end wxGlade
def __do_layout(self):
# begin wxGlade: Search_Web_Dialog.__do_layout
sizer_1 = wx.StaticBoxSizer(self.sizer_1_staticbox, wx.VERTICAL)
sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2.Add(self.label_2, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_2.Add(self.text_ctrl_2, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
sizer_3.Add(self.label_3, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_3.Add(self.choice_1, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_1.Add(sizer_3, 1, wx.EXPAND, 0)
sizer_1.Add(self.text_ctrl_1, 0, wx.EXPAND, 0)
#sizer_4.Add(self.button_3, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
#sizer_4.Add(self.button_4, 0, wx.ALL|wx.ALIGN_RIGHT, 5)
sizer_4.Add(self.button_3,0,wx.ALIGN_CENTER_VERTICAL,0)
sizer_4.Add(self.button_4,0,wx.ALIGN_CENTER_VERTICAL,0)
sizer_1.Add(sizer_4, 1, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
def ShowDesc(self,desc):
global PluginList
self.text_ctrl_1.SetValue(u'此插件无介绍。')
if desc<>u'搜索所有网站':
try:
self.text_ctrl_1.SetValue(PluginList[desc+'.py'].Description)
except:
pass
def OnChosen(self,event):
global lastweb
GlobalConfig['lastweb']=self.choice_1.GetString(event.GetInt())
self.ShowDesc(event.GetString())
def OnCancell(self, event):
self.Destroy()
def OnOK(self,event):
self.sitename=self.choice_1.GetString(self.choice_1.GetSelection())
self.keyword=self.text_ctrl_2.GetValue()
GlobalConfig['lastwebsearchkeyword']=self.keyword
self.Close()
def OnKey(self,event):
key=event.GetKeyCode()
if key==wx.WXK_ESCAPE:
self.Destroy()
else:
event.Skip()
class web_search_result_dialog(wx.Dialog):
def __init__(self, parent,sitename,keyword):
global PluginList
# begin wxGlade: web_search_result_dialog.__init__
#kwds["style"] = wx.DEFAULT_DIALOG_STYLE
wx.Dialog.__init__(self,parent,-1,style=wx.DEFAULT_DIALOG_STYLE)
self.list_ctrl_1 = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER|wx.LC_SINGLE_SEL)
self.list_ctrl_1.InsertColumn(0,u'书名',width=320)
self.list_ctrl_1.InsertColumn(1,u'作者')
self.list_ctrl_1.InsertColumn(2,u'状态')
self.list_ctrl_1.InsertColumn(3,u'大小')
self.list_ctrl_1.InsertColumn(4,u'最后更新')
self.list_ctrl_1.InsertColumn(5,u'网站')
self.button_1 = wx.Button(self, -1, u" 下载(后台) ")
self.button_2 = wx.Button(self, -1, u" 取消 ")
self.button_stream = wx.Button(self, -1, u" 边下载边看 ")
dlg = wx.ProgressDialog(u"搜索中",
u"搜索进行中...",
maximum = 100,
parent=self,
style =
wx.PD_SMOOTH
|wx.PD_AUTO_HIDE
)
self.rlist=[]
if sitename<>u'搜索所有网站':
self.rlist=None
self.rlist=PluginList[sitename+'.py'].GetSearchResults(keyword,useproxy=GlobalConfig['useproxy'],proxyserver=GlobalConfig['proxyserver'],proxyport=GlobalConfig['proxyport'],proxyuser=GlobalConfig['proxyuser'],proxypass=GlobalConfig['proxypass'])
if self.rlist != None:
for x in self.rlist:
x['sitename']=sitename
else:
sr=[]
flist=glob.glob(cur_file_dir()+"/plugin/*.py")
for x in range(len(flist)):
sr.append(-1)
i=0
crv=threading.Condition()
srm=[]
for f in flist:
bname=os.path.basename(f)
m=SearchThread(self,PluginList[bname],keyword,sr,i,crv)
srm.append(bname[:-3])
i+=1
isfinished=False
while isfinished<>True:
time.sleep(1)
isfinished=isfull(sr)
if isfinished==True: dlg.Update(100)
else:
dlg.Update(isfinished)
self.rlist=[]
i=0
for x in sr:
if x != None and x != -1:
for m in x:
m['sitename']=srm[i]
self.rlist+=x
i+=1
dlg.Update(100)
dlg.Destroy()
if self.rlist<>None:
i=0
for r in self.rlist:
for k in r.keys():
if r[k]==None:r[k]=''
index=self.list_ctrl_1.InsertStringItem(sys.maxint,r['bookname'])
self.list_ctrl_1.SetStringItem(index,1,r['authorname'])
self.list_ctrl_1.SetStringItem(index,2,r['bookstatus'])
self.list_ctrl_1.SetStringItem(index,3,r['booksize'])
self.list_ctrl_1.SetStringItem(index,4,r['lastupdatetime'])
self.list_ctrl_1.SetStringItem(index,5,r['sitename'])
self.list_ctrl_1.SetItemData(index,i)
i+=1
else:
dlg = wx.MessageDialog(self, u'搜索失败!',
u'出错了!',
wx.OK | wx.ICON_ERROR
)
dlg.ShowModal()
dlg.Destroy()
self.Destroy()
return None
self.Bind(wx.EVT_BUTTON, self.OnOK, self.button_1)
self.Bind(wx.EVT_BUTTON, self.OnCancell, self.button_2)
self.Bind(wx.EVT_BUTTON, self.OnStream, self.button_stream)
self.list_ctrl_1.Bind(wx.EVT_CHAR,self.OnKey)
self.__set_properties()
self.__do_layout()
# end wxGlade
def __set_properties(self):
# begin wxGlade: web_search_result_dialog.__set_properties
self.SetTitle(u"搜索结果")
self.list_ctrl_1.SetMinSize((709, 312))
# end wxGlade
def __do_layout(self):
# begin wxGlade: web_search_result_dialog.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_1.Add(self.list_ctrl_1, 1, wx.EXPAND, 0)
sizer_2.Add(self.button_1, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_2.Add(self.button_stream, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_2.Add(self.button_2, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_1.Add(sizer_2, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 5)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
def Download(self,item,mode='down'):
global PluginList
siten=self.list_ctrl_1.GetItem(item,5).GetText()
self.GetParent().WebDownloadManager.addTask(
{
'site':siten,
'bkname':self.list_ctrl_1.GetItem(item,0).GetText(),
'size':self.list_ctrl_1.GetItem(item,3).GetText(),
'url':self.rlist[self.list_ctrl_1.GetItemData(item)]['book_index_url'],
}
)
self.GetParent().DT=DownloadThread(self.GetParent(),
self.rlist[self.list_ctrl_1.GetItemData(item)]['book_index_url'],
PluginList[siten+'.py'],
self.list_ctrl_1.GetItemText(item),siten+'.py',
mode,
self.GetParent().WebDownloadManager.tasklist[self.rlist[self.list_ctrl_1.GetItemData(item)]['book_index_url']],
)
self.Destroy()
def OnStream(self,evt):
global OnScreenFileList
item=self.list_ctrl_1.GetNextSelected(-1)
if item==-1:
dlg = wx.MessageDialog(self, u'没有任何小说被选中!',
u'错误',
wx.OK | wx.ICON_ERROR
)
dlg.ShowModal()
dlg.Destroy()
return
self.GetParent().Menu103(None)
bkname=self.list_ctrl_1.GetItem(item,0).GetText()
OnScreenFileList=[]
OnScreenFileList.append((bkname,'',len(bkname)))
#change the title
self.GetParent().SetTitle(self.GetParent().title_str+' --- '+bkname)
self.GetParent().cur_catalog=None
self.GetParent().AllowUpdate = True
self.Download(item,'stream')
def OnOK(self, event):
item=self.list_ctrl_1.GetNextSelected(-1)
if item==-1:
dlg = wx.MessageDialog(self, u'没有任何小说被选中!',
u'错误',
wx.OK | wx.ICON_ERROR
)
dlg.ShowModal()
dlg.Destroy()
return
self.Download(item)
def OnCancell(self, event):
self.Destroy()
def OnKey(self,event):
key=event.GetKeyCode()
if key==wx.WXK_ESCAPE:
self.Destroy()
else:
event.Skip()
class WebSubscrDialog(wx.Dialog):
def __init__(self, parent):
global PluginList
wx.Dialog.__init__(self,parent,-1,pos=(100,-1),style=wx.DEFAULT_DIALOG_STYLE)
self.list_ctrl_1 = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
self.list_ctrl_1.InsertColumn(0,u'书名',width=200)
self.list_ctrl_1.InsertColumn(1,u'状态')
self.list_ctrl_1.InsertColumn(2,u'网址')
self.list_ctrl_1.InsertColumn(3,u'现有最后章名')
self.list_ctrl_1.InsertColumn(4,u'现有章数')
self.list_ctrl_1.InsertColumn(5,u'最后更新时间')
self.list_ctrl_1.InsertColumn(6,u'本地路径')
self.button_1 = wx.Button(self, -1, u" 更新 ")
self.button_2 = wx.Button(self, -1, u" 取消 ")
self.button_del = wx.Button(self, -1, u" 删除 ")
self.button_read = wx.Button(self, -1, u" 阅读 ")
self.button_selall = wx.Button(self, -1, u" 全选 ")
self.tasklist={}
self.sublist={}
self.Bind(wx.EVT_BUTTON, self.OnUpdate, self.button_1)
self.Bind(wx.EVT_BUTTON, self.OnCancell, self.button_2)
self.Bind(wx.EVT_BUTTON, self.OnDel, self.button_del)
self.Bind(wx.EVT_BUTTON, self.OnRead, self.button_read)
self.Bind(wx.EVT_BUTTON, self.OnSelAll, self.button_selall)
self.Bind(wx.EVT_CLOSE,self.OnCancell)
self.Bind(EVT_UPD,self.UpdateFinish)
self.Bind(wx.EVT_ACTIVATE,self.OnWinAct)
self.list_ctrl_1.Bind(wx.EVT_CHAR,self.OnKey)
self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActive, self.list_ctrl_1)
self.__set_properties()
self.__do_layout()
def __set_properties(self):
global SqlCur,SqlCon
self.SetTitle(u"管理订阅")
self.list_ctrl_1.SetMinSize((1000, 312))
def __do_layout(self):
# begin wxGlade: web_search_result_dialog.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_1.Add(self.list_ctrl_1, 1, wx.EXPAND, 0)
sizer_2.Add(self.button_selall, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_2.Add(self.button_1, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_2.Add(self.button_del, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_2.Add(self.button_read, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_2.Add(self.button_2, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_1.Add(sizer_2, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 5)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
def OnSelAll(self,evt):
item=-1
while True:
item=self.list_ctrl_1.GetNextItem(item)
if item==-1:return
self.list_ctrl_1.Select(item)
def OnItemActive(self,evt):
item=evt.GetIndex()
url=self.list_ctrl_1.GetItem(item,2).GetText()
self.GetParent().LoadFile([self.sublist[url]['save_path'],])
self.Hide()
def OnRead(self,evt):
item=-1
item=self.list_ctrl_1.GetNextSelected(item)
if item == -1: return
url=self.list_ctrl_1.GetItem(item,2).GetText()
self.GetParent().LoadFile([self.sublist[url]['save_path'],])
self.Hide()
def OnDel(self,evt):
global SqlCur,SqlCon
item=-1
while True:
item=self.list_ctrl_1.GetNextSelected(item)
if item == -1: return
bkname=self.list_ctrl_1.GetItem(item,0).GetText()
dlg=wx.MessageDialog(self,u"确定要删除订阅:"+bkname+u"?",
u"删除订阅确认",
style=wx.YES_NO|wx.NO_DEFAULT|wx.ICON_QUESTION)
if dlg.ShowModal()==wx.ID_YES:
url=self.list_ctrl_1.GetItem(item,2).GetText()
del self.sublist[url]
if url in self.tasklist.keys():
del self.tasklist[url]
self.list_ctrl_1.DeleteItem(item)
sqlstr="delete from subscr where index_url='%s'" % url
SqlCur.execute(sqlstr)
SqlCon.commit
def updateList(self):
global SqlCur
SqlCur.execute("select * from subscr")
dblist=[]
for row in SqlCur:
if row[1] not in self.sublist.keys():
bookname=row[0]
index_url=row[1]
lc_name=row[2]
lc_date=row[3]
chapter_count=row[4]
save_path=row[5]
if os.path.dirname(save_path) == '':
save_path=os.path.join(GlobalConfig['defaultsavedir'],save_path)
plugin_name=row[6]
self.sublist[index_url]={'bookname':bookname,'last_chapter':lc_name,
'last_update':lc_date,'save_path':save_path,
'plugin_name':plugin_name,
'ccount':chapter_count
}
index=self.list_ctrl_1.InsertStringItem(sys.maxint,bookname)
self.list_ctrl_1.SetStringItem(index,2,index_url)
self.list_ctrl_1.SetStringItem(index,3,lc_name)
self.list_ctrl_1.SetStringItem(index,4,str(chapter_count))
self.list_ctrl_1.SetStringItem(index,5,lc_date)
self.list_ctrl_1.SetStringItem(index,6,save_path)
self.list_ctrl_1.SetColumnWidth(3,wx.LIST_AUTOSIZE)
self.list_ctrl_1.SetColumnWidth(4,wx.LIST_AUTOSIZE_USEHEADER)
self.list_ctrl_1.SetColumnWidth(5,wx.LIST_AUTOSIZE)
def loadDB(self):
global SqlCur
SqlCur.execute("select * from subscr")
self.sublist.clear()
for row in SqlCur:
bookname=row[0]
index_url=row[1]
lc_name=row[2]
lc_date=row[3]
chapter_count=row[4]
save_path=row[5]
plugin_name=row[6]
self.sublist[index_url]={'bookname':bookname,'last_chapter':lc_name,
'last_update':lc_date,'save_path':save_path,
'plugin_name':plugin_name,
'ccount':chapter_count
}
index=self.list_ctrl_1.InsertStringItem(sys.maxint,bookname)
self.list_ctrl_1.SetStringItem(index,2,index_url)
self.list_ctrl_1.SetStringItem(index,3,lc_name)
self.list_ctrl_1.SetStringItem(index,4,str(chapter_count))
self.list_ctrl_1.SetStringItem(index,5,lc_date)
self.list_ctrl_1.SetStringItem(index,6,save_path)
#self.list_ctrl_1.SetItemData(index,plugin_name)
#self.itemDataMap[index]=(filename,filedate_data)
def OnUpdate(self, event):
global PluginList
item=-1
while True:
item=self.list_ctrl_1.GetNextSelected(item)
if item == -1: return
url=self.list_ctrl_1.GetItem(item,2).GetText()
bkname=self.list_ctrl_1.GetItem(item,0).GetText()
if url in self.tasklist.keys():
dlg=wx.MessageDialog(self,bkname+u"正在更新中.",u'注意',
style=wx.OK|wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
continue
self.tasklist[url]=UpdateThread(self,url,
PluginList[self.sublist[url]['plugin_name']]
,self.sublist[url]['bookname'],
self.sublist[url]['plugin_name'],
self.sublist[url]['ccount']
)
self.list_ctrl_1.SetStringItem(item,1,u'更新中')
self.list_ctrl_1.Refresh()
def UpdateItem(self,index,newstate,url):
"""
update the list labels of given item
"""
global SqlCur,SqlCon
self.list_ctrl_1.SetStringItem(index,0,newstate['bookname'])
self.list_ctrl_1.SetStringItem(index,2,url)
self.list_ctrl_1.SetStringItem(index,3,newstate['last_chapter'])
self.list_ctrl_1.SetStringItem(index,4,str(newstate['ccount']))
self.list_ctrl_1.SetStringItem(index,5,newstate['last_update'])
self.list_ctrl_1.SetStringItem(index,6,newstate['save_path'])
sqlstr="update subscr set bookname='%s',last_chapter_name='%s', \
last_update='%s',chapter_count=%s where index_url='%s' " % \
(newstate['bookname'],newstate['last_chapter'],
newstate['last_update'],newstate['ccount'],url)
SqlCur.execute(sqlstr)
SqlCon.commit()
def UpdateFinish(self,evt):
item=-1
bkstate=evt.bookstate
if bkstate['index_url'] in self.tasklist.keys():
del self.tasklist[bkstate['index_url']]
while True:
item=self.list_ctrl_1.GetNextItem(item)
if item==-1:break
if self.list_ctrl_1.GetItem(item,2).GetText()==bkstate['index_url']:
break
if item==-1:
return False #corresponding task is not found in the list
if evt.status != 'ok':
self.list_ctrl_1.SetStringItem(item,1,u'更新失败')
return False
elif evt.bk=='':
self.list_ctrl_1.SetStringItem(item,1,u'没有更新')
self.sublist[bkstate['index_url']]['last_update']=datetime.today().strftime('%y-%m-%d %H:%M')
else:
self.list_ctrl_1.SetStringItem(item,1,u'新增%s章' % bkstate['chapter_count'])
self.sublist[bkstate['index_url']]['last_chapter']=bkstate['last_chapter_name']
self.sublist[bkstate['index_url']]['ccount']+=bkstate['chapter_count']
self.sublist[bkstate['index_url']]['last_update']=datetime.today().strftime('%y-%m-%d %H:%M')
encoding=DetectFileCoding(self.sublist[bkstate['index_url']]['save_path'])
fp=codecs.open(self.sublist[bkstate['index_url']]['save_path'],encoding=encoding,mode='a')
fp.write(evt.bk)
fp.close()
self.UpdateItem(item,self.sublist[bkstate['index_url']],bkstate['index_url'])
def OnWinAct(self,evt):
if evt.GetActive():
self.updateList()
def OnCancell(self, event):
self.Hide()
def OnKey(self,event):
key=event.GetKeyCode()
if key==wx.WXK_ESCAPE:
self.Hide()
else:
event.Skip()
class UpdateThread:
def __init__(self,win,url,plugin,bookname,plugin_name=None,last_chcount=0):
self.win=win
self.url=url
self.plugin=plugin
self.plugin_name=plugin_name
self.bookname=bookname
self.last_chcount=last_chcount
#self.running=True
thread.start_new_thread(self.run, ())
## def stop(self):
## self.running=False
def run(self):
evt2=DownloadUpdateAlert(Value='',FieldNum=3)
try:
self.bk,bkstate=self.plugin.GetBook(self.url,bkname=self.bookname,
win=self.win,evt=evt2,
useproxy=GlobalConfig['useproxy'],
proxyserver=GlobalConfig['proxyserver'],
proxyport=GlobalConfig['proxyport'],
proxyuser=GlobalConfig['proxyuser'],
proxypass=GlobalConfig['proxypass'],
concurrent=GlobalConfig['numberofthreads'],
mode='update',
last_chapter_count=self.last_chcount
)
except:
self.bk=None
bkstate={'index_url':url}
if self.bk<>None:
evt1=UpdateEvt(name=self.bookname,status='ok',
bk=self.bk,bookstate=bkstate,
plugin_name=self.plugin_name,
)
else:
evt1=UpdateEvt(name=self.bookname,status='nok',bookstate=bkstate)
wx.PostEvent(self.win,evt1)
class DownloadThread:
def __init__(self,win,url,plugin,bookname,plugin_name=None,mode='down',
control=None):
self.win=win
self.url=url
self.plugin=plugin
self.plugin_name=plugin_name
self.bookname=bookname
self.mode=mode
self.control=control
#self.running=True
thread.start_new_thread(self.run, ())
## def stop(self):
## self.running=False
def run(self):
evt2=DownloadUpdateAlert(Value='',url=self.url)
if self.mode=='stream':
self.win.streamID+=1
evt3=UpdateValueEvt(value='',sid=self.win.streamID)
else:
evt3=None
self.bk,bkstate=self.plugin.GetBook(self.url,bkname=self.bookname,
win=self.win,evt=evt2,
useproxy=GlobalConfig['useproxy'],
proxyserver=GlobalConfig['proxyserver'],
proxyport=GlobalConfig['proxyport'],
proxyuser=GlobalConfig['proxyuser'],
proxypass=GlobalConfig['proxypass'],
concurrent=GlobalConfig['numberofthreads'],
dmode=self.mode,
sevt=evt3,
control=self.control,
)
if self.bk<>None:
evt1=DownloadFinishedAlert(name=self.bookname,status='ok',bk=self.bk,bookstate=bkstate,plugin_name=self.plugin_name)
else:
evt1=DownloadFinishedAlert(name=self.bookname,status='nok')
wx.PostEvent(self.win,evt1)
class SearchThread(threading.Thread):
def __init__(self,win,plugin,keyword,sr,i,cv):
threading.Thread.__init__(self,group=None, target=None, name=None, args=(), kwargs={})
self.win=win
self.plugin=plugin
self.keyword=keyword
self.sr=sr
self.i=i
self.cv=cv
self.start()
def run(self):
global GlobalConfig
self.cv.acquire()
self.sr[self.i]=self.plugin.GetSearchResults(self.keyword,useproxy=GlobalConfig['useproxy'],proxyserver=GlobalConfig['proxyserver'],proxyport=GlobalConfig['proxyport'],proxyuser=GlobalConfig['proxyuser'],proxypass=GlobalConfig['proxypass'])
self.cv.release()
class MyChoiceDialog(wx.Dialog):
def __init__(self, parent,msg='',title='',mychoices=[],default=0):
# begin wxGlade: MyChoiceDialog.__init__
wx.Dialog.__init__(self,parent,-1,style=wx.DEFAULT_DIALOG_STYLE)
self.sizer_1_staticbox = wx.StaticBox(self, -1, u"选择")
self.label_1 = wx.StaticText(self, -1, msg)
self.choice_1 = wx.Choice(self, -1, choices=mychoices)
self.button_1 = wx.Button(self, -1, u"确定")
self.button_2 = wx.Button(self, -1, u"取消")
self.checkbox_subscr = wx.CheckBox(self, -1, u"加入订阅")
self.Bind(wx.EVT_BUTTON, self.OnOK, self.button_1)
self.Bind(wx.EVT_BUTTON, self.OnCancell, self.button_2)
self.Bind(wx.EVT_CHOICE,self.OnChoice,self.choice_1)
self.choice_1.Bind(wx.EVT_CHAR,self.OnKey)
self.choice_1.Select(default)
if default==0:
self.checkbox_subscr.SetValue(False)
self.checkbox_subscr.Disable()
self.tit=title
self.__set_properties()
self.__do_layout()
# end wxGlade
def __set_properties(self):
# begin wxGlade: MyChoiceDialog.__set_properties
self.SetTitle(self.tit)
# end wxGlade
def __do_layout(self):
# begin wxGlade: MyChoiceDialog.__do_layout
sizer_1 = wx.StaticBoxSizer(self.sizer_1_staticbox, wx.VERTICAL)
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_1.Add(self.label_1, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 5)
sizer_1.Add(self.choice_1, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_1.Add(self.checkbox_subscr, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_2.Add(self.button_1, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_2.Add(self.button_2, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_1.Add(sizer_2, 1, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
# end wxGlade
def OnCancell(self, event):
self.Hide()
def OnOK(self,event):
self.sitename=self.choice_1.GetString(self.choice_1.GetSelection())
self.chosen=self.choice_1.GetStringSelection()
self.subscr=self.checkbox_subscr.GetValue()
self.Hide()
def OnChoice(self,evt):
if self.choice_1.GetStringSelection() == u'另存为...':
self.checkbox_subscr.Enable()
else:
self.checkbox_subscr.SetValue(False)
self.checkbox_subscr.Disable()
def OnKey(self,event):
key=event.GetKeyCode()
if key==wx.WXK_ESCAPE:
self.Destroy()
else:
event.Skip()
class NewOptionDialog(wx.Dialog):
def __init__(self, parent):
# begin wxGlade: NewOptionDialog.__init__
#kwds["style"] = wx.DEFAULT_DIALOG_STYLE
wx.Dialog.__init__(self, parent=parent,title=u'选项对话框',pos=(0,0))
self.notebook_1 = wx.Notebook(self, -1, style=0)
self.notebook_1_pane_4 = wx.Panel(self.notebook_1, -1)
self.notebook_1_pane_3 = wx.Panel(self.notebook_1, -1)
self.notebook_1_pane_2 = wx.Panel(self.notebook_1, -1)
self.notebook_1_pane_ltbnet = wx.Panel(self.notebook_1, -1)
self.staticbox_ltbnet = wx.StaticBox(self.notebook_1_pane_ltbnet, -1, u"LTBNET设置")
self.notebook_1_pane_1 = wx.ScrolledWindow(self.notebook_1, -1, style=wx.TAB_TRAVERSAL)
self.sizer_5_staticbox = wx.StaticBox(self.notebook_1_pane_1, -1, u"显示主题")
self.sizer_6_staticbox = wx.StaticBox(self.notebook_1_pane_1, -1, u"显示模式")
self.sizer_9_staticbox = wx.StaticBox(self.notebook_1_pane_1, -1, u"背景色或图片背景")
self.sizer_13_staticbox = wx.StaticBox(self.notebook_1_pane_1, -1, u"字体")
self.sizer_14_staticbox = wx.StaticBox(self.notebook_1_pane_1, -1, u"下划线")
self.sizer_16_staticbox = wx.StaticBox(self.notebook_1_pane_1, -1, u"间距设置")
self.sizer_2_staticbox = wx.StaticBox(self.notebook_1_pane_2, -1, u"启动设置")
self.sizer_8_staticbox = wx.StaticBox(self.notebook_1_pane_2, -1, u"时间间隔")
self.sizer_25_staticbox = wx.StaticBox(self.notebook_1_pane_2, -1, u"其他")
self.sizer_weball_staticbox = wx.StaticBox(self.notebook_1_pane_2, -1, u"Web服务器")
self.sizer_32_staticbox = wx.StaticBox(self.notebook_1_pane_3, -1, u"下载")
self.sizer_36_staticbox = wx.StaticBox(self.notebook_1_pane_3, -1, u"代理服务器")
self.sizer_15_staticbox = wx.StaticBox(self.notebook_1_pane_1, -1, u"显示效果预览")
self.sizer_26_staticbox = wx.StaticBox(self.notebook_1_pane_4, -1, u"按键方案")
self.sizer_27_staticbox = wx.StaticBox(self.notebook_1_pane_4, -1, u"双击修改,右键增加删除")
self.text_ctrl_3 = liteview.LiteView(self.notebook_1_pane_1, -1, "")
self.combo_box_1 = wx.ComboBox(self.notebook_1_pane_1, -1, choices=[], style=wx.CB_DROPDOWN|wx.CB_READONLY)
self.button_1 = wx.Button(self.notebook_1_pane_1, -1, u"另存为")
self.button_2 = wx.Button(self.notebook_1_pane_1, -1, u"删除")
self.button_theme_import = wx.Button(self.notebook_1_pane_1, -1, u"导入")
self.button_theme_export = wx.Button(self.notebook_1_pane_1, -1, u"导出")
self.label_1 = wx.StaticText(self.notebook_1_pane_1, -1, u"选择显示模式:")
self.combo_box_2 = wx.ComboBox(self.notebook_1_pane_1, -1, choices=[u"纸张模式", u"书本模式", u"竖排书本模式"], style=wx.CB_DROPDOWN|wx.CB_READONLY)
self.checkbox_vbookpunc = wx.CheckBox(self.notebook_1_pane_1, -1, label=u'竖排书本下无标点')
self.label_3 = wx.StaticText(self.notebook_1_pane_1, -1, u"选择背景图片:")
self.text_ctrl_2 = wx.TextCtrl(self.notebook_1_pane_1, -1, "",style=wx.TE_READONLY)
self.button_3 = wx.Button(self.notebook_1_pane_1, -1, u"选择")
self.label_4 = wx.StaticText(self.notebook_1_pane_1, -1, u"背景图片排列方式:")
self.combo_box_3 = wx.ComboBox(self.notebook_1_pane_1, -1, choices=[u"平铺", u"居中"], style=wx.CB_DROPDOWN|wx.CB_READONLY)
self.label_5 = wx.StaticText(self.notebook_1_pane_1, -1, u"选择背景色或背景图片:")
self.combo_box_4 = wx.ComboBox(self.notebook_1_pane_1, -1, choices=[u"使用背景图片", u"使用背景色"], style=wx.CB_DROPDOWN|wx.CB_DROPDOWN|wx.CB_READONLY)
self.button_4 = wx.Button(self.notebook_1_pane_1, -1, u"选择背景色")
self.button_5 = wx.Button(self.notebook_1_pane_1, -1, u"选择字体")
self.button_6 = wx.Button(self.notebook_1_pane_1, -1, u"字体颜色")
self.label_6 = wx.StaticText(self.notebook_1_pane_1, -1, u"下划线样式")
self.combo_box_5 = wx.ComboBox(self.notebook_1_pane_1, -1, choices=[u"不使用下划线", u"实线", u"虚线", u"长虚线", u"点虚线"], style=wx.CB_DROPDOWN|wx.CB_DROPDOWN|wx.CB_READONLY)
self.button_7 = wx.Button(self.notebook_1_pane_1, -1, u"下划线颜色")
self.label_7 = wx.StaticText(self.notebook_1_pane_1, -1, u"纸张模式页边距:")
self.spin_ctrl_1 = wx.SpinCtrl(self.notebook_1_pane_1, -1, "", min=0, max=100)
self.label_8 = wx.StaticText(self.notebook_1_pane_1, -1, u"书本模式页边距:")
self.spin_ctrl_2 = wx.SpinCtrl(self.notebook_1_pane_1, -1, "", min=0, max=100)
self.label_9 = wx.StaticText(self.notebook_1_pane_1, -1, u"竖排书本模式页边距:")
self.spin_ctrl_3 = wx.SpinCtrl(self.notebook_1_pane_1, -1, "", min=0, max=100)
self.label_10 = wx.StaticText(self.notebook_1_pane_1, -1, u"(竖排)书本模式页中距:")
self.spin_ctrl_4 = wx.SpinCtrl(self.notebook_1_pane_1, -1, "", min=0, max=100)
self.label_11 = wx.StaticText(self.notebook_1_pane_1, -1, u"行间距:")
self.spin_ctrl_5 = wx.SpinCtrl(self.notebook_1_pane_1, -1, "", min=0, max=100)
self.label_12 = wx.StaticText(self.notebook_1_pane_1, -1, u"竖排书本行间距:")
self.spin_ctrl_6 = wx.SpinCtrl(self.notebook_1_pane_1, -1, "", min=0, max=100)
self.checkbox_1 = wx.CheckBox(self.notebook_1_pane_2, -1, u"启动时自动载入上次阅读文件")
self.checkbox_2 = wx.CheckBox(self.notebook_1_pane_2, -1, u"启动时检查版本更新")
self.label_13 = wx.StaticText(self.notebook_1_pane_2, -1, u"自动翻页间隔(秒):")
self.spin_ctrl_8 = wx.SpinCtrl(self.notebook_1_pane_2, -1, "", min=0, max=100)
self.label_14 = wx.StaticText(self.notebook_1_pane_2, -1, u"连续阅读提醒时间(分钟):")
self.spin_ctrl_9 = wx.SpinCtrl(self.notebook_1_pane_2, -1, "", min=0, max=100)
self.checkbox_3 = wx.CheckBox(self.notebook_1_pane_2, -1, u"是否启用ESC作为老板键")
self.checkbox_4 = wx.CheckBox(self.notebook_1_pane_2, -1, u"是否在文件选择侧边栏中预览文件内容")
self.checkbox_5 = wx.CheckBox(self.notebook_1_pane_2, -1, u"是否只在文件选择侧边栏中只显示支持的文件类型")
self.label_15 = wx.StaticText(self.notebook_1_pane_2, -1, u"最大曾经打开文件菜单数:")
self.spin_ctrl_10 = wx.SpinCtrl(self.notebook_1_pane_2, -1, "", min=0, max=100)
self.checkbox_webserver = wx.CheckBox(self.notebook_1_pane_2, -1, u"启动时运行Web服务器")
self.label_webport = wx.StaticText(self.notebook_1_pane_2, -1, u"Web服务器端口:")
self.spin_ctrl_webport = wx.SpinCtrl(self.notebook_1_pane_2, -1, "8000", min=1, max=65535)
self.label_webroot = wx.StaticText(self.notebook_1_pane_2, -1, u"共享根目录:")
self.text_ctrl_webroot = wx.TextCtrl(self.notebook_1_pane_2, -1, "", style=wx.TE_READONLY)
self.button_webroot = wx.Button(self.notebook_1_pane_2, -1, u"选择")
self.label_redconf = wx.StaticText(self.notebook_1_pane_2, -1, u"配置文件目录:")
self.text_ctrl_redconf = wx.TextCtrl(self.notebook_1_pane_2, -1, "", style=wx.TE_READONLY)
self.button_redconf = wx.Button(self.notebook_1_pane_2, -1, u"选择")
self.button_migrate = wx.Button(self.notebook_1_pane_2, -1, u"迁移配置")
self.label_bookdirprefix = wx.StaticText(self.notebook_1_pane_2, -1, u"存书目录:")
self.text_ctrl_bookdirprefix = wx.TextCtrl(self.notebook_1_pane_2, -1, "", style=wx.TE_READONLY)
self.button_bookdirprefix = wx.Button(self.notebook_1_pane_2, -1, u"选择")
self.label_MDNS = wx.StaticText(self.notebook_1_pane_2, -1, u"绑定的网络接口:")
self.combo_box_MDNS = wx.ComboBox(self.notebook_1_pane_2, -1, choices=[], style=wx.CB_DROPDOWN | wx.CB_READONLY)
self.label_16 = wx.StaticText(self.notebook_1_pane_3, -1, u"下载完毕后的缺省动作:")
self.combo_box_6 = wx.ComboBox(self.notebook_1_pane_3, -1, choices=[u"直接阅读", u"另存为文件", u"直接保存在缺省目录下"], style=wx.CB_DROPDOWN|wx.CB_DROPDOWN|wx.CB_READONLY)
self.label_17 = wx.StaticText(self.notebook_1_pane_3, -1, u"保存的缺省目录:")
self.label_ltbroot = wx.StaticText(self.notebook_1_pane_ltbnet, -1, u"LTBNET共享目录:")
self.text_ctrl_1 = wx.TextCtrl(self.notebook_1_pane_3, -1, "",style=wx.TE_READONLY)
self.text_ctrl_ltbroot = wx.TextCtrl(self.notebook_1_pane_ltbnet, -1, "", size=(200,-1))
self.label_ltbport = wx.StaticText(self.notebook_1_pane_ltbnet, -1, u"LTBNET端口(重启litebook后生效):")
self.spin_ctrl_ltbport = wx.SpinCtrl(self.notebook_1_pane_ltbnet, -1, "", min=1, max=65536)
self.checkbox_upnp = wx.CheckBox(self.notebook_1_pane_ltbnet, -1, u"是否在启动时使用UPNP添加端口映射")
self.checkbox_ltbnet = wx.CheckBox(self.notebook_1_pane_ltbnet, -1, u"是否启用LTBNET(重启litebook后生效)")
self.button_12 = wx.Button(self.notebook_1_pane_3, -1, u"选择")
self.button_ltbroot = wx.Button(self.notebook_1_pane_ltbnet, -1, u"选择")
self.label_18 = wx.StaticText(self.notebook_1_pane_3, -1, u"同时下载的线程个数(需插件支持;不能超过50):")
self.spin_ctrl_11 = wx.SpinCtrl(self.notebook_1_pane_3, -1, "20", min=1, max=50)
self.checkbox_6 = wx.CheckBox(self.notebook_1_pane_3, -1, u"启用代理服务器")
self.label_19 = wx.StaticText(self.notebook_1_pane_3, -1, u"代理服务器地址:")
self.text_ctrl_4 = wx.TextCtrl(self.notebook_1_pane_3, -1, "")
self.label_20 = wx.StaticText(self.notebook_1_pane_3, -1, u"代理服务器端口:")
self.spin_ctrl_12 = wx.SpinCtrl(self.notebook_1_pane_3, -1, "", min=1, max=65536)
self.label_21 = wx.StaticText(self.notebook_1_pane_3, -1, u"用户名:")
self.text_ctrl_5 = wx.TextCtrl(self.notebook_1_pane_3, -1, "")
self.label_22 = wx.StaticText(self.notebook_1_pane_3, -1, u"密码:")
self.text_ctrl_6 = wx.TextCtrl(self.notebook_1_pane_3, -1, "", style=wx.TE_PASSWORD)
self.combo_box_7 = wx.ComboBox(self.notebook_1_pane_4, -1, choices=[], style=wx.CB_DROPDOWN)
self.button_Key_Save = wx.Button(self.notebook_1_pane_4, -1, u"另存为")
self.button_Key_Del = wx.Button(self.notebook_1_pane_4, -1, u"删除")
self.button_key_import = wx.Button(self.notebook_1_pane_4, -1, u"导入")
self.button_key_export = wx.Button(self.notebook_1_pane_4, -1, u"导出")
self.grid_1 = keygrid.KeyConfigGrid(self.notebook_1_pane_4)
self.button_10 = wx.Button(self, -1, u"确定")
self.button_11 = wx.Button(self, -1, u"取消")
#绑定事件处理
self.Bind(wx.EVT_COMBOBOX,self.OnThemeSelect,self.combo_box_1)
self.Bind(wx.EVT_COMBOBOX,self.OnKeySelect,self.combo_box_7)
self.Bind(wx.EVT_COMBOBOX,self.OnShowmodeSelect,self.combo_box_2)
self.Bind(wx.EVT_COMBOBOX,self.OnBGlayoutSelect,self.combo_box_3)
self.Bind(wx.EVT_COMBOBOX,self.OnBGSet,self.combo_box_4)
self.Bind(wx.EVT_COMBOBOX,self.OnSelULS,self.combo_box_5)
self.Bind(wx.EVT_BUTTON,self.OnChoseWebRoot,self.button_webroot)
self.Bind(wx.EVT_BUTTON,self.OnCancell,self.button_11)
self.Bind(wx.EVT_BUTTON,self.OnDelTheme,self.button_2)
self.Bind(wx.EVT_BUTTON,self.OnSaveTheme,self.button_1)
self.Bind(wx.EVT_BUTTON,self.OnSelectBG,self.button_3)
self.Bind(wx.EVT_BUTTON,self.OnSelFont,self.button_5)
self.Bind(wx.EVT_BUTTON,self.OnSelFColor,self.button_6)
self.Bind(wx.EVT_BUTTON,self.OnSelectBGColor,self.button_4)
self.Bind(wx.EVT_BUTTON,self.OnSelectULColor,self.button_7)
self.Bind(wx.EVT_BUTTON,self.SelectDir,self.button_12)
self.Bind(wx.EVT_BUTTON,self.OnOK,self.button_10)
self.Bind(wx.EVT_BUTTON,self.OnDelKey,self.button_Key_Del)
self.Bind(wx.EVT_BUTTON,self.OnSaveKey,self.button_Key_Save)
self.Bind(wx.EVT_BUTTON,self.OnImportKey,self.button_key_import)
self.Bind(wx.EVT_BUTTON,self.OnExportKey,self.button_key_export)
self.Bind(wx.EVT_BUTTON,self.OnExportTheme,self.button_theme_export)
self.Bind(wx.EVT_BUTTON,self.OnImportTheme,self.button_theme_import)
self.Bind(wx.EVT_BUTTON,self.OnSelRedConf,self.button_redconf)
self.Bind(wx.EVT_BUTTON,self.migrateConf,self.button_migrate)
self.Bind(wx.EVT_BUTTON,self.OnSelBookDirPrefix,self.button_bookdirprefix)
self.Bind(wx.EVT_SPINCTRL,self.OnUpdateSpace,self.spin_ctrl_1)
self.Bind(wx.EVT_SPINCTRL,self.OnUpdateSpace,self.spin_ctrl_2)
self.Bind(wx.EVT_SPINCTRL,self.OnUpdateSpace,self.spin_ctrl_3)
self.Bind(wx.EVT_SPINCTRL,self.OnUpdateSpace,self.spin_ctrl_4)
self.Bind(wx.EVT_SPINCTRL,self.OnUpdateSpace,self.spin_ctrl_5)
self.Bind(wx.EVT_SPINCTRL,self.OnUpdateSpace,self.spin_ctrl_6)
self.__set_properties()
self.__do_layout()
# end wxGlade
def __set_properties(self):
global GlobalConfig,FullVersion
# begin wxGlade: NewOptionDialog.__set_properties
self.SetTitle(u"选项对话框")
self.SetSize((600, 500))
self.text_ctrl_3.SetSize((450,300))
self.combo_box_2.SetSelection(-1)
self.text_ctrl_2.SetMinSize((300, -1))
self.combo_box_3.SetSelection(-1)
self.combo_box_4.SetSelection(-1)
self.combo_box_5.SetSelection(0)
self.notebook_1_pane_1.SetScrollRate(10, 10)
self.combo_box_6.SetSelection(-1)
self.text_ctrl_1.SetMinSize((150, -1))
self.text_ctrl_4.SetMinSize((200, -1))
self.spin_ctrl_11.SetMinSize((100,-1))
self.text_ctrl_webroot.SetMinSize((200, -1))
self.text_ctrl_redconf.SetMinSize((200,-1))
self.text_ctrl_bookdirprefix.SetMinSize((200,-1))
self.label_MDNS.SetToolTipString(u"选择WEB服务器及mDNS所绑定的网络接口,缺省情况下系统会自动选择WLAN接口")
#set preview area to current setting
self.text_ctrl_3.SetShowMode(GlobalConfig['showmode'])
if GlobalConfig['backgroundimg']<>'' and GlobalConfig['backgroundimg']<>None:
self.text_ctrl_3.SetImgBackground(GlobalConfig['backgroundimg'],GlobalConfig['backgroundimglayout'])
else:
self.text_ctrl_3.SetBackgroundColour(GlobalConfig['CurBColor'])
self.text_ctrl_3.SetFColor(GlobalConfig['CurFColor'])
self.text_ctrl_3.SetFont(GlobalConfig['CurFont'])
self.text_ctrl_3.SetUnderline(GlobalConfig['underline'],GlobalConfig['underlinestyle'],GlobalConfig['underlinecolor'])
self.text_ctrl_3.SetSpace(GlobalConfig['pagemargin'],GlobalConfig['bookmargin'],GlobalConfig['vbookmargin'],GlobalConfig['centralmargin'],GlobalConfig['linespace'],GlobalConfig['vlinespace'])
self.text_ctrl_3.SetValue(u"《老子》八十一章\n\n 1.道可道,非常道。名可名,非常名。无名天地之始。有名万物之母。故常无欲以观其妙。常有欲以观其徼。此两者同出而异名,同谓之玄。玄之又玄,众妙之门。\n\n 2.天下皆知美之为美,斯恶矣;皆知善之为善,斯不善已。故有无相生,难易相成,长短相形,高下相倾,音声相和,前後相随。是以圣人处无为之事,行不言之教。万物作焉而不辞。生而不有,为而不恃,功成而弗居。夫唯弗居,是以不去。\n\n 3.不尚贤, 使民不争。不贵难得之货,使民不为盗。不见可欲,使民心不乱。是以圣人之治,虚其心,实其腹,弱其志,强其骨;常使民无知、无欲,使夫智者不敢为也。为无为,则无不治。\n\n 4.道冲而用之,或不盈。渊兮似万物之宗。解其纷,和其光,同其尘,湛兮似或存。吾不知谁之子,象帝之先。\n\n 5.天地不仁,以万物为刍狗。圣人不仁,以百姓为刍狗。天地之间,其犹橐迭乎?虚而不屈,动而愈出。多言数穷,不如守中。")
#set initial value for display tab
self.combo_box_1.Append(u'当前设置')
for x in ThemeList:
self.combo_box_1.Append(x['name'])
self.combo_box_1.Select(0)
if GlobalConfig['showmode']=='paper':
self.combo_box_2.Select(0)
else:
if GlobalConfig['showmode']=='book': self.combo_box_2.Select(1)
else:
if GlobalConfig['showmode']=='vbook': self.combo_box_2.Select(2)
if GlobalConfig['backgroundimg']<>'' and GlobalConfig['backgroundimg']<>None:
self.combo_box_4.Select(0)
self.text_ctrl_2.SetValue(GlobalConfig['backgroundimg'])
if GlobalConfig['backgroundimglayout']=='tile':
self.combo_box_3.Select(0)
else:
self.combo_box_3.Select(1)
else:
self.combo_box_4.Select(1)
self.text_ctrl_2.Disable()
self.button_3.Disable()
self.combo_box_3.Disable()
self.checkbox_vbookpunc.SetValue(not GlobalConfig['vbookpunc'])
if GlobalConfig['underline']==False:
self.combo_box_5.Select(0)
else:
if GlobalConfig['underlinestyle']==wx.SOLID: self.combo_box_5.Select(1)
else:
if GlobalConfig['underlinestyle']==wx.DOT: self.combo_box_5.Select(2)
else:
if GlobalConfig['underlinestyle']==wx.LONG_DASH: self.combo_box_5.Select(3)
else:
if GlobalConfig['underlinestyle']==wx.DOT_DASH: self.combo_box_5.Select(4)
self.spin_ctrl_1.SetValue(GlobalConfig['pagemargin'])
self.spin_ctrl_2.SetValue(GlobalConfig['bookmargin'])
self.spin_ctrl_3.SetValue(GlobalConfig['vbookmargin'])
self.spin_ctrl_4.SetValue(GlobalConfig['centralmargin'])
self.spin_ctrl_5.SetValue(GlobalConfig['linespace'])
self.spin_ctrl_6.SetValue(GlobalConfig['vlinespace'])
#set initial value for control tab
self.checkbox_1.SetValue(GlobalConfig['LoadLastFile'])
self.checkbox_3.SetValue(GlobalConfig['EnableESC'])
self.text_ctrl_redconf.SetValue(GlobalConfig['redConfDir'])
self.text_ctrl_bookdirprefix.SetValue(GlobalConfig['BookDirPrefix'])
if MYOS != 'Windows':
self.checkbox_3.Disable()
self.checkbox_4.SetValue(GlobalConfig['EnableSidebarPreview'])
self.spin_ctrl_8.SetValue(GlobalConfig['AutoScrollInterval']/1000)
self.spin_ctrl_9.SetValue(GlobalConfig['RemindInterval'])
self.checkbox_2.SetValue(GlobalConfig['VerCheckOnStartup'])
self.checkbox_5.SetValue(not GlobalConfig['ShowAllFileInSidebar'])
self.spin_ctrl_10.SetValue(GlobalConfig['MaxOpenedFiles'])
#set inital value for download tab
self.combo_box_6.Select(GlobalConfig['DAUDF'])
self.checkbox_6.SetValue(GlobalConfig['useproxy'])
self.text_ctrl_4.SetValue(unicode(GlobalConfig['proxyserver']))
self.spin_ctrl_12.SetValue(GlobalConfig['proxyport'])
self.text_ctrl_5.SetValue(unicode(GlobalConfig['proxyuser']))
self.text_ctrl_6.SetValue(unicode(GlobalConfig['proxypass']))
self.spin_ctrl_11.SetValue(GlobalConfig['numberofthreads'])
self.text_ctrl_1.SetValue(unicode(GlobalConfig['defaultsavedir']))
#load the initial value for keyconfig tab
for kconfig in KeyConfigList:
if kconfig[0]<>'last':
self.combo_box_7.Append(kconfig[0])
else:
self.combo_box_7.Append(u'当前设置')
self.combo_box_7.Select(0)
self.grid_1.Load(KeyConfigList[0])
#set the initial value for web server
self.checkbox_webserver.SetValue(GlobalConfig['RunWebserverAtStartup'])
self.spin_ctrl_webport.SetValue(int(GlobalConfig['ServerPort']))
self.text_ctrl_webroot.SetValue(GlobalConfig['ShareRoot'])
#set the inital value for mDNS interface
ip_int_name_list=[]
if FullVersion==True:
if platform.system() == 'Linux':
bus = dbus.SystemBus()
proxy = bus.get_object("org.freedesktop.NetworkManager",
"/org/freedesktop/NetworkManager")
manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager")
# Get device-specific state
devices = manager.GetDevices()
for d in devices:
dev_proxy = bus.get_object("org.freedesktop.NetworkManager", d)
prop_iface = dbus.Interface(dev_proxy, "org.freedesktop.DBus.Properties")
# Get the device's current state and interface name
state = prop_iface.Get("org.freedesktop.NetworkManager.Device", "State")
name = prop_iface.Get("org.freedesktop.NetworkManager.Device", "Interface")
ip_int_name_list.append(name)
elif platform.system() == 'Darwin':
for ifname in netifaces.interfaces(): #return addr of 1st network interface
if ifname != 'lo0':
ip_int_name_list.append(ifname)
self.combo_box_MDNS.Append(u"自动检测")
self.combo_box_MDNS.AppendItems(ip_int_name_list)
if GlobalConfig['mDNS_interface']=='AUTO':
self.combo_box_MDNS.SetStringSelection(u'自动检测')
else:
self.combo_box_MDNS.SetStringSelection(GlobalConfig['mDNS_interface'])
#set initial value for LTBNET
self.spin_ctrl_ltbport.SetValue(GlobalConfig['LTBNETPort'])
self.text_ctrl_ltbroot.SetValue(unicode(GlobalConfig['LTBNETRoot']))
self.checkbox_upnp.SetValue(GlobalConfig['RunUPNPAtStartup'])
self.checkbox_ltbnet.SetValue(GlobalConfig['EnableLTBNET'])
# end wxGlade
def __do_layout(self):
# begin wxGlade: NewOptionDialog.__do_layout
sizer_3 = wx.BoxSizer(wx.VERTICAL)
sizer_30 = wx.BoxSizer(wx.HORIZONTAL)
sizer_7 = wx.BoxSizer(wx.VERTICAL)
sizer_26 = wx.StaticBoxSizer(self.sizer_26_staticbox, wx.HORIZONTAL)
sizer_27 = wx.StaticBoxSizer(self.sizer_27_staticbox, wx.HORIZONTAL)
sizer_31 = wx.BoxSizer(wx.VERTICAL)
sizer_36 = wx.StaticBoxSizer(self.sizer_36_staticbox, wx.VERTICAL)
sizer_40 = wx.BoxSizer(wx.HORIZONTAL)
sizer_39 = wx.BoxSizer(wx.HORIZONTAL)
sizer_38 = wx.BoxSizer(wx.HORIZONTAL)
sizer_37 = wx.BoxSizer(wx.HORIZONTAL)
sizer_32 = wx.StaticBoxSizer(self.sizer_32_staticbox, wx.VERTICAL)
sizer_35 = wx.BoxSizer(wx.HORIZONTAL)
sizer_34 = wx.BoxSizer(wx.HORIZONTAL)
sizer_33 = wx.BoxSizer(wx.HORIZONTAL)
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_weball = wx.StaticBoxSizer(self.sizer_weball_staticbox, wx.VERTICAL)
sizer_web3 = wx.BoxSizer(wx.HORIZONTAL)
sizer_redconf = wx.BoxSizer(wx.HORIZONTAL)
sizer_web2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_MDNS = wx.BoxSizer(wx.HORIZONTAL)
sizer_25 = wx.StaticBoxSizer(self.sizer_25_staticbox, wx.VERTICAL)
sizer_29 = wx.BoxSizer(wx.HORIZONTAL)
sizer_8 = wx.StaticBoxSizer(self.sizer_8_staticbox, wx.VERTICAL)
sizer_24 = wx.BoxSizer(wx.HORIZONTAL)
sizer_23 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2 = wx.StaticBoxSizer(self.sizer_2_staticbox, wx.VERTICAL)
sizer_4 = wx.BoxSizer(wx.VERTICAL)
sizer_16 = wx.StaticBoxSizer(self.sizer_16_staticbox, wx.VERTICAL)
sizer_22 = wx.BoxSizer(wx.HORIZONTAL)
sizer_21 = wx.BoxSizer(wx.HORIZONTAL)
sizer_20 = wx.BoxSizer(wx.HORIZONTAL)
sizer_19 = wx.BoxSizer(wx.HORIZONTAL)
sizer_18 = wx.BoxSizer(wx.HORIZONTAL)
sizer_17 = wx.BoxSizer(wx.HORIZONTAL)
sizer_14 = wx.StaticBoxSizer(self.sizer_14_staticbox, wx.HORIZONTAL)
sizer_13 = wx.StaticBoxSizer(self.sizer_13_staticbox, wx.HORIZONTAL)
sizer_9 = wx.StaticBoxSizer(self.sizer_9_staticbox, wx.VERTICAL)
sizer_12 = wx.BoxSizer(wx.HORIZONTAL)
sizer_11 = wx.BoxSizer(wx.HORIZONTAL)
sizer_10 = wx.BoxSizer(wx.HORIZONTAL)
sizer_6 = wx.StaticBoxSizer(self.sizer_6_staticbox, wx.HORIZONTAL)
sizer_5 = wx.StaticBoxSizer(self.sizer_5_staticbox, wx.HORIZONTAL)
sizer_15 = wx.StaticBoxSizer(self.sizer_15_staticbox, wx.HORIZONTAL)
sizer_15.Add(self.text_ctrl_3, 1, wx.EXPAND, 0)
sizer_4.Add(sizer_15, 1, wx.EXPAND, 0)
sizer_5.Add(self.combo_box_1, 0, 0, 0)
sizer_5.Add(self.button_1, 0, 0, 0)
sizer_5.Add(self.button_2, 0, 0, 0)
sizer_5.Add(self.button_theme_export, 0, 0, 0)
sizer_5.Add(self.button_theme_import, 0, 0, 0)
sizer_4.Add(sizer_5, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 0)
sizer_6.Add(self.label_1, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
sizer_6.Add(self.combo_box_2, 1, wx.ALIGN_CENTRE|wx.ALL, 5)
sizer_6.Add(self.checkbox_vbookpunc, 2, wx.ALIGN_LEFT|wx.ALL, 5)
sizer_4.Add(sizer_6, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 0)
sizer_10.Add(self.label_3, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_10.Add(self.text_ctrl_2, 0, 0, 0)
sizer_10.Add(self.button_3, 0, 0, 0)
sizer_9.Add(sizer_10, 1, wx.EXPAND, 0)
sizer_11.Add(self.label_4, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_11.Add(self.combo_box_3, 0, 0, 0)
sizer_9.Add(sizer_11, 1, wx.EXPAND, 0)
sizer_12.Add(self.label_5, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_12.Add(self.combo_box_4, 0, 0, 0)
sizer_12.Add(self.button_4, 0, 0, 0)
sizer_9.Add(sizer_12, 1, wx.EXPAND, 0)
sizer_4.Add(sizer_9, 0, wx.EXPAND, 0)
sizer_13.Add(self.button_5, 0, 0, 0)
sizer_13.Add(self.button_6, 0, 0, 0)
sizer_4.Add(sizer_13, 0, wx.EXPAND, 0)
sizer_14.Add(self.label_6, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_14.Add(self.combo_box_5, 0, 0, 0)
sizer_14.Add(self.button_7, 0, 0, 0)
sizer_4.Add(sizer_14, 0, wx.EXPAND, 0)
sizer_17.Add(self.label_7, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_17.Add(self.spin_ctrl_1, 0, 0, 0)
sizer_16.Add(sizer_17, 1, wx.EXPAND, 0)
sizer_18.Add(self.label_8, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_18.Add(self.spin_ctrl_2, 0, 0, 0)
sizer_16.Add(sizer_18, 1, wx.EXPAND, 0)
sizer_19.Add(self.label_9, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_19.Add(self.spin_ctrl_3, 0, 0, 0)
sizer_16.Add(sizer_19, 1, wx.EXPAND, 0)
sizer_20.Add(self.label_10, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_20.Add(self.spin_ctrl_4, 0, 0, 0)
sizer_16.Add(sizer_20, 1, wx.EXPAND, 0)
sizer_21.Add(self.label_11, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_21.Add(self.spin_ctrl_5, 0, 0, 0)
sizer_16.Add(sizer_21, 1, wx.EXPAND, 0)
sizer_22.Add(self.label_12, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_22.Add(self.spin_ctrl_6, 0, 0, 0)
sizer_16.Add(sizer_22, 1, wx.EXPAND, 0)
sizer_4.Add(sizer_16, 0, wx.EXPAND, 0)
self.notebook_1_pane_1.SetSizer(sizer_4)
sizer_2.Add(self.checkbox_1, 0, 0, 0)
sizer_2.Add(self.checkbox_2, 0, 0, 0)
sizer_redconf.Add(self.label_redconf,0,0,0)
sizer_redconf.Add(self.text_ctrl_redconf,0,0,0)
sizer_redconf.Add(self.button_redconf,0,0,0)
sizer_redconf.Add(self.button_migrate,0,0,0)
sizer_2.Add(sizer_redconf,0,wx.EXPAND,0)
sizer_bookdirprefix = wx.BoxSizer(wx.HORIZONTAL)
sizer_bookdirprefix.Add(self.label_bookdirprefix,0,0,0)
sizer_bookdirprefix.Add(self.text_ctrl_bookdirprefix,0,0,0)
sizer_bookdirprefix.Add(self.button_bookdirprefix,0,0,0)
sizer_2.Add(sizer_bookdirprefix,0,wx.EXPAND,0)
sizer_1.Add(sizer_2, 0, wx.EXPAND, 0)
sizer_23.Add(self.label_13, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_23.Add(self.spin_ctrl_8, 0, 0, 0)
sizer_8.Add(sizer_23, 1, wx.EXPAND, 0)
sizer_24.Add(self.label_14, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_24.Add(self.spin_ctrl_9, 0, 0, 0)
sizer_8.Add(sizer_24, 1, wx.EXPAND, 0)
sizer_1.Add(sizer_8, 0, wx.EXPAND, 0)
sizer_25.Add(self.checkbox_3, 0, 0, 0)
sizer_25.Add(self.checkbox_4, 0, 0, 0)
sizer_25.Add(self.checkbox_5, 0, 0, 0)
sizer_29.Add(self.label_15, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_29.Add(self.spin_ctrl_10, 0, 0, 0)
sizer_25.Add(sizer_29, 1, wx.EXPAND, 0)
sizer_1.Add(sizer_25, 0, wx.EXPAND, 0)
sizer_weball.Add(self.checkbox_webserver, 0, 0, 0)
sizer_web2.Add(self.label_webport, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_web2.Add(self.spin_ctrl_webport, 0, 0, 0)
sizer_weball.Add(sizer_web2, 0, wx.EXPAND, 0)
sizer_web3.Add(self.label_webroot, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_web3.Add(self.text_ctrl_webroot, 0, 0, 0)
sizer_web3.Add(self.button_webroot, 0, 0, 0)
sizer_weball.Add(sizer_web3, 0, wx.EXPAND, 0)
sizer_MDNS.Add(self.label_MDNS, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_MDNS.Add(self.combo_box_MDNS, 0, 0, 0)
sizer_weball.Add(sizer_MDNS, 0, wx.EXPAND, 0)
sizer_1.Add(sizer_weball, 0, wx.EXPAND, 0)
self.notebook_1_pane_2.SetSizer(sizer_1)
sizer_33.Add(self.label_16, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_33.Add(self.combo_box_6, 0, 0, 0)
sizer_32.Add(sizer_33, 1, wx.EXPAND, 0)
sizer_34.Add(self.label_17, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_34.Add(self.text_ctrl_1, 0, 0, 0)
sizer_34.Add(self.button_12, 0, 0, 0)
sizer_32.Add(sizer_34, 1, wx.EXPAND, 0)
sizer_35.Add(self.label_18, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_35.Add(self.spin_ctrl_11, 0, 0, 0)
sizer_32.Add(sizer_35, 1, wx.EXPAND, 0)
sizer_31.Add(sizer_32, 0, wx.EXPAND, 0)
sizer_36.Add(self.checkbox_6, 0, 0, 0)
sizer_37.Add(self.label_19, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_37.Add(self.text_ctrl_4, 0, 0, 0)
sizer_36.Add(sizer_37, 1, wx.EXPAND, 0)
sizer_38.Add(self.label_20, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_38.Add(self.spin_ctrl_12, 0, 0, 0)
sizer_36.Add(sizer_38, 1, wx.EXPAND, 0)
sizer_39.Add(self.label_21, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_39.Add(self.text_ctrl_5, 0, 0, 0)
sizer_36.Add(sizer_39, 1, wx.EXPAND, 0)
sizer_40.Add(self.label_22, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_40.Add(self.text_ctrl_6, 0, 0, 0)
sizer_36.Add(sizer_40, 1, wx.EXPAND, 0)
sizer_31.Add(sizer_36, 0, wx.EXPAND, 0)
self.notebook_1_pane_3.SetSizer(sizer_31)
sizer_26.Add(self.combo_box_7, 0, 0, 0)
sizer_26.Add(self.button_Key_Save, 0, 0, 0)
sizer_26.Add(self.button_Key_Del, 0, 0, 0)
sizer_26.Add(self.button_key_export, 0, 0, 0)
sizer_26.Add(self.button_key_import, 0, 0, 0)
sizer_7.Add(sizer_26, 0, wx.EXPAND, 0)
sizer_27.Add(self.grid_1,1,wx.EXPAND,0)
#sizer_7.Add(self.grid_1, 1, wx.EXPAND, 0)
sizer_7.Add(sizer_27, 1, wx.EXPAND, 0)
self.notebook_1_pane_4.SetSizer(sizer_7)
#LTBNET
sizer_ltbnet_all = wx.BoxSizer(wx.VERTICAL)
sizer_ltbnet = wx.StaticBoxSizer(self.staticbox_ltbnet, wx.VERTICAL)
sizer_ltbnet.Add(self.checkbox_ltbnet,0,wx.EXPAND,0)
sizer_ltbnet.Add(self.checkbox_upnp,0,wx.EXPAND,0)
sizer_ltbroot = wx.BoxSizer(wx.HORIZONTAL)
sizer_ltbroot.Add(self.label_ltbroot, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_ltbroot.Add(self.text_ctrl_ltbroot, 0, 0, 0)
sizer_ltbroot.Add(self.button_ltbroot, 0, 0, 0)
sizer_ltbnet.Add(sizer_ltbroot,0,wx.EXPAND,0)
sizer_ltbport = wx.BoxSizer(wx.HORIZONTAL)
sizer_ltbport.Add(self.label_ltbport,0,wx.ALIGN_CENTER_VERTICAL,0)
sizer_ltbport.Add(self.spin_ctrl_ltbport,0,0,0)
sizer_ltbnet.Add(sizer_ltbport,0,wx.EXPAND,0)
## sizer_upnp = wx.BoxSizer(wx.HORIZONTAL)
## sizer_upnp.Add(self.checkbox_upnp,0,wx.ALIGN_CENTER_VERTICAL,0)
## sizer_ltbnet.Add(sizer_upnp,0,wx.EXPAND,0)
#sizer_32.Add(sizer_ltbroot, 1, wx.EXPAND, 0)
#sizer_ltbnet_all.Add(sizer_ltbnet,0,wx.EXPAND,0)
self.notebook_1_pane_ltbnet.SetSizer(sizer_ltbnet)
self.notebook_1.AddPage(self.notebook_1_pane_1, u"显示设置")
self.notebook_1.AddPage(self.notebook_1_pane_2, u"控制设置")
self.notebook_1.AddPage(self.notebook_1_pane_3, u"下载设置")
self.notebook_1.AddPage(self.notebook_1_pane_4, u"按键设置")
self.notebook_1.AddPage(self.notebook_1_pane_ltbnet, u"LTBNET设置")
sizer_3.Add(self.notebook_1, 1, wx.EXPAND, 0)
sizer_30.Add((100, 10), 1, wx.EXPAND, 0)
sizer_30.Add(self.button_10, 0, 0, 0)
sizer_30.Add((20, 10), 1, wx.EXPAND, 0)
sizer_30.Add(self.button_11, 0, 0, 0)
sizer_30.Add((50, 10), 1, wx.EXPAND, 0)
sizer_3.Add(sizer_30, 0, wx.EXPAND, 0)
self.SetSizer(sizer_3)
self.Layout()
# end wxGlade
def migrateConf(self,evt):
"""
Copy conf files from current path to the new path
"""
global GlobalConfig
newconfdir=self.text_ctrl_redconf.GetValue()
err=False
if os.access(newconfdir,os.R_OK|os.W_OK):
try:
shutil.copy(GlobalConfig['path_list']['bookdb'],newconfdir)
shutil.copy(GlobalConfig['path_list']['conf'],newconfdir)
shutil.copy(GlobalConfig['path_list']['key_conf'],newconfdir)
except Exception as inst:
err=True
errmsg=str(inst)
else:
err=True
errmsg=u'新的目录:'+newconfdir+u' 无法读写'
if err:
dlg = wx.MessageDialog(None, errmsg,u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
else:
dlg = wx.MessageDialog(None, u"配置文件已经成功拷贝到新目录 "+newconfdir,
u"成功!",wx.OK|wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
def OnSelBookDirPrefix(self,evt):
global GlobalConfig
if GlobalConfig['BookDirPrefix'] == '':
cur_path=''
else:
cur_path=GlobalConfig['redConfDir']
fdlg=wx.DirDialog(self,u"请选择存书目录:",cur_path)
if fdlg.ShowModal()==wx.ID_OK:
rdir=fdlg.GetPath()
if os.path.isdir(rdir):
self.text_ctrl_bookdirprefix.SetValue(rdir)
else:
dlg = wx.MessageDialog(None, rdir+u' 不是一个合法的目录',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
fdlg.Destroy()
def OnSelRedConf(self,evt):
global GlobalConfig
if GlobalConfig['redConfDir'] == None:
cur_path=''
else:
cur_path=GlobalConfig['redConfDir']
fdlg=wx.DirDialog(self,u"请选择配置文件目录:",cur_path)
if fdlg.ShowModal()==wx.ID_OK:
rdir=fdlg.GetPath()
if os.path.isdir(rdir):
self.text_ctrl_redconf.SetValue(rdir)
else:
dlg = wx.MessageDialog(None, rdir+u' 不是一个合法的目录',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
fdlg.Destroy()
def OnChoseWebRoot(self,evt):
global GlobalConfig
fdlg=wx.DirDialog(self,u"请选择共享目录:",GlobalConfig['ShareRoot'])
if fdlg.ShowModal()==wx.ID_OK:
rdir=fdlg.GetPath()
if os.path.isdir(rdir):
self.text_ctrl_webroot.SetValue(rdir)
else:
dlg = wx.MessageDialog(None, rdir+u' 不是一个合法的目录',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
fdlg.Destroy()
def OnCancell(self,event):
self.Destroy()
def OnOK(self,event):
global ThemeList,GlobalConfig,KeyConfigList,KeyMenuList
GlobalConfig['vbookpunc'] = not self.checkbox_vbookpunc.GetValue()
GlobalConfig['CurFont']=self.text_ctrl_3.GetFont()
GlobalConfig['CurFColor']=self.text_ctrl_3.GetFColor()
GlobalConfig['CurBColor']=self.text_ctrl_3.GetBackgroundColour()
if self.combo_box_4.GetSelection()==0:
if self.text_ctrl_3.bg_img_path<>None and self.text_ctrl_3.bg_img_path<>'':
if os.path.dirname(AnyToUnicode(self.text_ctrl_3.bg_img_path))==cur_file_dir()+u'/background':
GlobalConfig['backgroundimg']=os.path.basename(self.text_ctrl_3.bg_img_path)
else:
GlobalConfig['backgroundimg']=self.text_ctrl_3.bg_img_path
else:
GlobalConfig['backgroundimg']=None
GlobalConfig['showmode']=self.text_ctrl_3.show_mode
GlobalConfig['backgroundimglayout']=self.text_ctrl_3.bg_style
GlobalConfig['underline']=self.text_ctrl_3.under_line
GlobalConfig['underlinestyle']=self.text_ctrl_3.under_line_style
GlobalConfig['underlinecolor']=self.text_ctrl_3.under_line_color
GlobalConfig['pagemargin']=self.text_ctrl_3.pagemargin
GlobalConfig['bookmargin']=self.text_ctrl_3.bookmargin
GlobalConfig['vbookmargin']=self.text_ctrl_3.vbookmargin
GlobalConfig['centralmargin']=self.text_ctrl_3.centralmargin
GlobalConfig['linespace']=self.text_ctrl_3.linespace
GlobalConfig['vlinespace']=self.text_ctrl_3.vlinespace
GlobalConfig['LoadLastFile']=self.checkbox_1.GetValue()
GlobalConfig['redConfDir']=self.text_ctrl_redconf.GetValue()
GlobalConfig['BookDirPrefix']=self.text_ctrl_bookdirprefix.GetValue()
GlobalConfig['EnableESC']=self.checkbox_3.GetValue()
GlobalConfig['VerCheckOnStartup']=self.checkbox_2.GetValue()
if GlobalConfig['ShowAllFileInSidebar']==self.checkbox_5.GetValue():
self.GetParent().UpdateSidebar=True
GlobalConfig['ShowAllFileInSidebar']=not self.checkbox_5.GetValue()
if MYOS == 'Windows':
if GlobalConfig['EnableESC']:
self.GetParent().RegisterHotKey(1,0,wx.WXK_ESCAPE)
self.GetParent().Bind(wx.EVT_HOTKEY,self.GetParent().OnESC)
else:
self.GetParent().UnregisterHotKey(1)
self.GetParent().Unbind(wx.EVT_HOTKEY)
GlobalConfig['EnableSidebarPreview']=self.checkbox_4.GetValue()
try:
GlobalConfig['AutoScrollInterval']=float(self.spin_ctrl_8.GetValue())*1000
except:
GlobalConfig['AutoScrollInterval']=12000
try:
GlobalConfig['RemindInterval']=abs(int(self.spin_ctrl_9.GetValue()))
except:
GlobalConfig['RemindInterval']=60
try:
GlobalConfig['MaxOpenedFiles']=abs(int(self.spin_ctrl_10.GetValue()))
except:
GlobalConfig['MaxOpenedFiles']=5
GlobalConfig['DAUDF']=self.combo_box_6.GetSelection()
GlobalConfig['useproxy']=self.checkbox_6.GetValue()
GlobalConfig['proxyserver']=self.text_ctrl_4.GetValue()
try:
GlobalConfig['proxyport']=int(self.spin_ctrl_12.GetValue())
except:
GlobalConfig['proxyport']=0
GlobalConfig['proxyuser']=self.text_ctrl_5.GetValue()
GlobalConfig['proxypass']=self.text_ctrl_6.GetValue()
try:
GlobalConfig['numberofthreads']=int(self.spin_ctrl_11.GetValue())
except:
GlobalConfig['numberofthreads']=1
if GlobalConfig['numberofthreads']<=0 or GlobalConfig['numberofthreads']>50:
GlobalConfig['numberofthreads']=1
if not os.path.exists(self.text_ctrl_1.GetValue()):
GlobalConfig['defaultsavedir']=''
else:
GlobalConfig['defaultsavedir']=self.text_ctrl_1.GetValue()
if GlobalConfig['defaultsavedir']=='' and GlobalConfig['DAUDF']==2:
dlg = wx.MessageDialog(self, u'请指定正确的缺省保存目录!',
u'出错了!',
wx.OK | wx.ICON_ERROR
)
dlg.ShowModal()
dlg.Destroy()
return
#save key config
for x in KeyConfigList:
if x[0]=='last':
KeyConfigList.remove(x)
break
kconfig=[]
kconfig.append(('last'))
rs=self.grid_1.GetNumberRows()
if rs>0:
i=0
while i<rs:
kconfig.append((self.grid_1.GetCellValue(i,0),self.grid_1.GetCellValue(i,1)))
i+=1
KeyConfigList.insert(0,kconfig)
i=1
tl=len(kconfig)
#KeyMenuList={}
while i<tl:
KeyMenuList[kconfig[i][0]]=keygrid.str2menu(kconfig[i][1])
i+=1
self.GetParent().ResetMenu()
#save web server related config
GlobalConfig['ShareRoot']=self.text_ctrl_webroot.GetValue()
GlobalConfig['ServerPort']=int(self.spin_ctrl_webport.GetValue())
GlobalConfig['RunWebserverAtStartup']=self.checkbox_webserver.GetValue()
m_int=self.combo_box_MDNS.GetValue()
if m_int==u'自动检测':
GlobalConfig['mDNS_interface']="AUTO"
else:
GlobalConfig['mDNS_interface']=m_int
#save LTBNET config
GlobalConfig['LTBNETPort'] = self.spin_ctrl_ltbport.GetValue()
GlobalConfig['LTBNETRoot'] = self.text_ctrl_ltbroot.GetValue()
GlobalConfig['RunUPNPAtStartup'] = self.checkbox_upnp.GetValue()
GlobalConfig['EnableLTBNET'] = self.checkbox_ltbnet.GetValue()
self.Destroy()
def OnDelKey(self,evt):
global KeyConfigList
name=self.combo_box_7.GetValue()
if name==u'当前设置':
dlg = wx.MessageDialog(self, u'你不能删除这个方案!',u"错误",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return
for x in KeyConfigList:
if x[0]==name:
KeyConfigList.remove(x)
break
self.combo_box_7.Clear()
for t in KeyConfigList:
if t[0]=='last':self.combo_box_7.Append(u'当前设置')
else:
self.combo_box_7.Append(t[0])
self.combo_box_7.SetSelection(0)
def OnDelTheme(self,event):
global ThemeList
name=self.combo_box_1.GetValue()
if self.combo_box_1.GetSelection()==0:
dlg = wx.MessageDialog(self, u'你不能删除这个方案!',u"错误",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return
i=0
n=len(ThemeList)
while i<n:
if ThemeList[i]['name']==name:
ThemeList.__delitem__(i)
break
i+=1
self.combo_box_1.Clear()
self.combo_box_1.Append(u'当前设置')
for t in ThemeList:
self.combo_box_1.Append(t['name'])
self.combo_box_1.SetSelection(0)
self.OnThemeSelect(None)
def OnSaveKey(self,evt):
global KeyConfigList
kconfig=[]
kconfig.append((''))
tlist=[]
for k in KeyConfigList:
if k[0]<>'last':
tlist.append(k[0])
while kconfig[0]=='':
dlg = ComboDialog.ComboDialog(
self,tlist,u'输入方案名',u'输入或选择方案名' )
if dlg.ShowModal() == wx.ID_OK:
kconfig[0]=dlg.GetValue().strip()
dlg.Destroy()
else:
dlg.Destroy()
return
for t in KeyConfigList:
if t[0]==kconfig[0]:
dlg = wx.MessageDialog(self, u'已经有叫这个名字的显示方案了,你确定要覆盖原有方案吗?',u"提示!",wx.YES_NO|wx.ICON_QUESTION)
if dlg.ShowModal()==wx.ID_NO:
dlg.Destroy()
return
else:
KeyConfigList.remove(t)
rs=self.grid_1.GetNumberRows()
if rs>0:
i=0
while i<rs:
kconfig.append((self.grid_1.GetCellValue(i,0),self.grid_1.GetCellValue(i,1)))
i+=1
if kconfig[0]=='last':
KeyConfigList.insert(0,kconfig)
else:
KeyConfigList.append(kconfig)
self.combo_box_7.Clear()
for t in KeyConfigList:
if t[0]=='last':self.combo_box_7.Append(u'当前设置')
else:
self.combo_box_7.Append(t[0])
self.combo_box_7.SetSelection(self.combo_box_7.GetCount()-1)
def OnSaveTheme(self,event):
global ThemeList
l={}
l['name']=''
tlist=[]
for t in ThemeList:
tlist.append(t['name'])
while l['name']=='':
dlg = ComboDialog.ComboDialog(
self,tlist,u'输入主题名',u'输入或选择主题名' )
if dlg.ShowModal() == wx.ID_OK:
l['name']=dlg.GetValue().strip()
dlg.Destroy()
else:
dlg.Destroy()
return
for t in ThemeList:
if t['name']==l['name']:
dlg = wx.MessageDialog(self, u'已经有叫这个名字的显示方案了,你确定要覆盖原有方案吗?',u"提示!",wx.YES_NO|wx.ICON_QUESTION)
if dlg.ShowModal()==wx.ID_NO:
dlg.Destroy()
return
else:
ThemeList.remove(t)
l['font']=self.text_ctrl_3.GetFont()
l['fcolor']=self.text_ctrl_3.GetFColor()
l['bcolor']=self.text_ctrl_3.GetBackgroundColour()
l['config']=unicode(l['font'].GetPointSize())+u'|'+unicode(l['font'].GetFamily())+u'|'+unicode(l['font'].GetStyle())+u'|'+unicode(l['font'].GetWeight())+u'|'+unicode(l['font'].GetUnderlined())+u'|'+l['font'].GetFaceName()+u'|'+unicode(l['font'].GetDefaultEncoding())+u'|'+unicode(l['fcolor'])+u'|'+unicode(l['bcolor'])
r=self.text_ctrl_3.GetConfig()
l['backgroundimg']=r['backgroundimg']
if r['backgroundimg']<>None and r['backgroundimg']<>'':
if os.path.dirname(r['backgroundimg'])==cur_file_dir()+u'/background':
l['backgroundimg']=os.path.basename(r['backgroundimg'])
else:
l['backgroundimg']=r['backgroundimg']
l['showmode']=r['showmode']
l['backgroundimglayout']=r['backgroundimglayout']
l['underline']=r['underline']
l['underlinestyle']=r['underlinestyle']
l['underlinecolor']=r['underlinecolor']
l['pagemargin']=r['pagemargin']
l['bookmargin']=r['bookmargin']
l['vbookmargin']=r['vbookmargin']
l['centralmargin']=r['centralmargin']
l['linespace']=r['linespace']
l['vlinespace']=r['vlinespace']
l['config']+=u'|'+unicode(l['backgroundimg'])
l['config']+=u'|'+unicode(l['showmode'])
l['config']+=u'|'+unicode(l['backgroundimglayout'])
l['config']+=u'|'+unicode(l['underline'])
l['config']+=u'|'+unicode(l['underlinestyle'])
l['config']+=u'|'+unicode(l['underlinecolor'])
l['config']+=u'|'+unicode(l['pagemargin'])
l['config']+=u'|'+unicode(l['bookmargin'])
l['config']+=u'|'+unicode(l['vbookmargin'])
l['config']+=u'|'+unicode(l['centralmargin'])
l['config']+=u'|'+unicode(l['linespace'])
l['config']+=u'|'+unicode(l['vlinespace'])
l['config']+=u'|'+unicode(l['name'])
ThemeList.append(l)
self.combo_box_1.Clear()
self.combo_box_1.Append(u'当前设置')
for t in ThemeList:
self.combo_box_1.Append(t['name'])
self.combo_box_1.SetSelection(self.combo_box_1.GetCount()-1)
def OnShowmodeSelect(self,evt):
id=evt.GetInt()
modes=['paper','book','vbook']
self.text_ctrl_3.SetShowMode(modes[id])
self.text_ctrl_3.ReDraw()
def OnBGlayoutSelect(self,evt):
id=evt.GetInt()
layouts=['tile','center']
self.text_ctrl_3.SetImgBackground(self.text_ctrl_2.GetValue(),layouts[id])
self.text_ctrl_3.ReDraw()
def OnBGSet(self,evt):
id=evt.GetInt()
layouts=['tile','center']
if id==0:
self.text_ctrl_2.Enable()
self.button_3.Enable()
self.combo_box_3.Enable()
if self.text_ctrl_2.GetValue()<>'':
self.text_ctrl_3.SetImgBackground(self.text_ctrl_2.GetValue(),layouts[self.combo_box_3.GetSelection()])
self.text_ctrl_3.ReDraw()
else:
self.text_ctrl_3.SetImgBackground('')
self.text_ctrl_2.Clear()
self.text_ctrl_2.Disable()
self.button_3.Disable()
self.combo_box_3.Disable()
def OnSelectBGColor(self,evt):
dlg = wx.ColourDialog(self)
dlg.GetColourData().SetChooseFull(True)
if dlg.ShowModal() == wx.ID_OK:
data = dlg.GetColourData()
if self.combo_box_4.GetSelection()==1:
self.text_ctrl_3.SetImgBackground('')
self.text_ctrl_3.SetBackgroundColour(data.GetColour())
self.text_ctrl_3.ReDraw()
dlg.Destroy()
def OnSelectULColor(self,evt):
dlg = wx.ColourDialog(self)
dlg.GetColourData().SetChooseFull(True)
if dlg.ShowModal() == wx.ID_OK:
data = dlg.GetColourData()
self.text_ctrl_3.SetUnderline(color=data.GetColour())
self.text_ctrl_3.ReDraw()
dlg.Destroy()
def OnSelFont(self,event):
global GlobalConfig
data=wx.FontData()
data.SetInitialFont(self.text_ctrl_3.GetFont())
data.SetColour(self.text_ctrl_3.GetForegroundColour())
data.EnableEffects(False)
dlg = wx.FontDialog(self, data)
if dlg.ShowModal() == wx.ID_OK:
ft=dlg.GetFontData().GetChosenFont()
self.text_ctrl_3.SetFont(ft)
self.text_ctrl_3.ReDraw()
dlg.Destroy()
def OnSelFColor(self,event):
global GlobalConfig
dlg = wx.ColourDialog(self)
dlg.GetColourData().SetChooseFull(True)
if dlg.ShowModal() == wx.ID_OK:
data = dlg.GetColourData()
self.text_ctrl_3.SetFColor(data.GetColour())
self.text_ctrl_3.ReDraw()
dlg.Destroy()
def OnSelectBG(self,evt):
wildcard = u"所有图片文件|*.gif;*.bmp;*.png;*.tif;*.tiff;*.jpg;*.jpeg;*.tif;*.tiff|" \
"JPG (*.jpg,*.jpeg)|*.jpg;*.jpeg|" \
"GIF (*.gif)|*.gif|" \
"BMP (*.bmp)|*.bmp|" \
"PNG (*.png)|*.png|" \
"TIF (*.tif,*.tiff)|*.tif;*.tiff|" \
"All files (*.*)|*.*"
defaultpath=os.path.dirname(self.text_ctrl_2.GetValue())
if defaultpath=='':
defaultpath=cur_file_dir()+u'/background'
dlg = wx.FileDialog(
self, message=u"选择背景图片",
defaultDir=defaultpath,
defaultFile="",
wildcard=wildcard,
style=wx.OPEN | wx.FD_FILE_MUST_EXIST
)
dlg.ShowModal()
rpath=dlg.GetPath()
if rpath<>None and rpath<>'':
if os.path.dirname(AnyToUnicode(rpath))==cur_file_dir()+u'/background':
rpath=os.path.basename(rpath)
self.text_ctrl_2.SetValue(rpath)
self.text_ctrl_3.SetImgBackground(rpath)
self.text_ctrl_3.ReDraw()
dlg.Destroy()
def OnSelULS(self,evt):
id=evt.GetInt()
uls=[None,wx.SOLID,wx.DOT,wx.LONG_DASH,wx.DOT_DASH]
if id==0:
self.text_ctrl_3.SetUnderline(False)
else:
self.text_ctrl_3.SetUnderline(True,uls[id])
self.text_ctrl_3.ReDraw()
def AlignSetting(self):
sms={'paper':0,'book':1,'vbook':2}
self.combo_box_2.SetSelection(sms[self.text_ctrl_3.show_mode])
if self.text_ctrl_3.bg_img==None:
self.text_ctrl_2.SetValue('')
else:
self.text_ctrl_2.SetValue(self.text_ctrl_3.bg_img_path)
layouts={'tile':0,'center':1}
self.combo_box_3.SetSelection(layouts[self.text_ctrl_3.bg_style])
if self.text_ctrl_3.bg_img_path<>None and self.text_ctrl_3.bg_img_path<>'':
self.combo_box_4.SetSelection(0)
self.text_ctrl_2.Enable()
self.button_3.Enable()
self.combo_box_3.Enable()
else:
self.combo_box_4.SetSelection(1)
uls={wx.SOLID:1,wx.DOT:2,wx.LONG_DASH:3,wx.SHORT_DASH:3,wx.DOT_DASH:4}
if self.text_ctrl_3.under_line==False: self.combo_box_5.SetSelection(0)
else:
self.combo_box_5.SetSelection(uls[self.text_ctrl_3.under_line_style])
self.spin_ctrl_1.SetValue(self.text_ctrl_3.pagemargin)
self.spin_ctrl_2.SetValue(self.text_ctrl_3.bookmargin)
self.spin_ctrl_3.SetValue(self.text_ctrl_3.vbookmargin)
self.spin_ctrl_4.SetValue(self.text_ctrl_3.centralmargin)
self.spin_ctrl_5.SetValue(self.text_ctrl_3.linespace)
self.spin_ctrl_6.SetValue(self.text_ctrl_3.vlinespace)
def OnKeySelect(self,evt=None):
global KeyConfigList
if evt<>None:
id=evt.GetInt()
else:
id=self.combo_box_7.GetSelection()
self.grid_1.Load(KeyConfigList[id])
def OnThemeSelect(self,evt=None):
global ThemeList
if evt<>None:
id=evt.GetInt()
else:
id=self.combo_box_1.GetSelection()
if id==0:
self.text_ctrl_3.SetShowMode(GlobalConfig['showmode'])
if GlobalConfig['backgroundimg']<>'' and GlobalConfig['backgroundimg']<>None:
self.text_ctrl_3.SetImgBackground(GlobalConfig['backgroundimg'],GlobalConfig['backgroundimglayout'])
else:
self.text_ctrl_3.SetImgBackground(None)
self.text_ctrl_3.SetBackgroundColour(GlobalConfig['CurBColor'])
self.text_ctrl_3.SetFColor(GlobalConfig['CurFColor'])
self.text_ctrl_3.SetFont(GlobalConfig['CurFont'])
self.text_ctrl_3.SetUnderline(GlobalConfig['underline'],GlobalConfig['underlinestyle'],GlobalConfig['underlinecolor'])
self.text_ctrl_3.SetSpace(GlobalConfig['pagemargin'],GlobalConfig['bookmargin'],GlobalConfig['vbookmargin'],GlobalConfig['centralmargin'],GlobalConfig['linespace'],GlobalConfig['vlinespace'])
self.text_ctrl_3.SetValue(u"《老子》八十一章\n\n 1.道可道,非常道。名可名,非常名。无名天地之始。有名万物之母。故常无欲以观其妙。常有欲以观其徼。此两者同出而异名,同谓之玄。玄之又玄,众妙之门。\n\n 2.天下皆知美之为美,斯恶矣;皆知善之为善,斯不善已。故有无相生,难易相成,长短相形,高下相倾,音声相和,前後相随。是以圣人处无为之事,行不言之教。万物作焉而不辞。生而不有,为而不恃,功成而弗居。夫唯弗居,是以不去。\n\n 3.不尚贤, 使民不争。不贵难得之货,使民不为盗。不见可欲,使民心不乱。是以圣人之治,虚其心,实其腹,弱其志,强其骨;常使民无知、无欲,使夫智者不敢为也。为无为,则无不治。\n\n 4.道冲而用之,或不盈。渊兮似万物之宗。解其纷,和其光,同其尘,湛兮似或存。吾不知谁之子,象帝之先。\n\n 5.天地不仁,以万物为刍狗。圣人不仁,以百姓为刍狗。天地之间,其犹橐迭乎?虚而不屈,动而愈出。多言数穷,不如守中。")
else:
id-=1
self.text_ctrl_3.SetShowMode(ThemeList[id]['showmode'])
if ThemeList[id]['backgroundimg']<>'' and ThemeList[id]['backgroundimg']<>None:
self.text_ctrl_3.SetImgBackground(ThemeList[id]['backgroundimg'],ThemeList[id]['backgroundimglayout'])
else:
self.text_ctrl_3.SetImgBackground(None)
self.text_ctrl_3.SetBackgroundColour(ThemeList[id]['bcolor'])
self.text_ctrl_3.SetFColor(ThemeList[id]['fcolor'])
self.text_ctrl_3.SetFont(ThemeList[id]['font'])
self.text_ctrl_3.SetUnderline(ThemeList[id]['underline'],ThemeList[id]['underlinestyle'],GlobalConfig['underlinecolor'])
self.text_ctrl_3.SetSpace(ThemeList[id]['pagemargin'],ThemeList[id]['bookmargin'],GlobalConfig['vbookmargin'],GlobalConfig['centralmargin'],GlobalConfig['linespace'],GlobalConfig['vlinespace'])
self.text_ctrl_3.ReDraw()
self.AlignSetting()
def SelectDir(self,event):
dlg = wx.DirDialog(self, u"请选择目录:",defaultPath=GlobalConfig['LastDir'],
style=wx.DD_DEFAULT_STYLE
)
if dlg.ShowModal() == wx.ID_OK:
self.text_ctrl_1.SetValue(dlg.GetPath())
dlg.Destroy()
def OnUpdateSpace(self,evt):
lvalue=evt.GetInt()
lid=evt.GetEventObject()
## print lid
## print self.spin_ctrl_2.GetId()
if lid==self.spin_ctrl_1:self.text_ctrl_3.SetSpace(lvalue)
if lid==self.spin_ctrl_2:
self.text_ctrl_3.SetSpace(bookmargin=lvalue)
if lid==self.spin_ctrl_3:self.text_ctrl_3.SetSpace(vbookmargin=lvalue)
if lid==self.spin_ctrl_4:self.text_ctrl_3.SetSpace(centralmargin=lvalue)
if lid==self.spin_ctrl_5:self.text_ctrl_3.SetSpace(linespace=lvalue)
if lid==self.spin_ctrl_6:self.text_ctrl_3.SetSpace(vlinespace=lvalue)
self.text_ctrl_3.ReDraw()
def OnExportKey(self,evt):
global KeyConfigList
clist=[]
for k in KeyConfigList:
if k[0]=='last':
clist.append(u'当前设置')
else:
clist.append(k[0])
edlg=CheckDialog(self,u'导出按键配置方案',clist)
edlg.ShowModal()
rlist=edlg.GetChecks()
if len(rlist)>0:
wildcard = u"所有文件 (*.*)|*.*|"
dlg = wx.FileDialog(
self, message=u"导出为...", defaultDir=GlobalConfig['LastDir'],
defaultFile="", wildcard=wildcard, style=wx.SAVE | wx.FD_OVERWRITE_PROMPT
)
if dlg.ShowModal() == wx.ID_OK:
config=MyConfig()
for r in rlist:
config.add_section(KeyConfigList[r][0])
i=1
kl=len(KeyConfigList[r])
cstr={}
while i<kl:
if KeyConfigList[r][i][0] not in cstr:
cstr[KeyConfigList[r][i][0]]=KeyConfigList[r][i][1]
else:
cstr[KeyConfigList[r][i][0]]+="&&"+KeyConfigList[r][i][1]
i+=1
for key,val in cstr.items():
config.set(KeyConfigList[r][0],unicode(key),val)
try:
ConfigFile=codecs.open(dlg.GetPath(),encoding='utf-8',mode='w')
config.write(ConfigFile)
ConfigFile.close()
except:
dlg = wx.MessageDialog(None, u'导出文件错误!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
return False
dlg.Destroy()
def OnImportKey(self,evt):
global GlobalConfig,KeyConfigList
wildcard = u"所有文件 (*.*)|*.*"
dlg = wx.FileDialog(
self, message=u"选择要导入的文件:",
defaultDir=GlobalConfig['LastDir'],
defaultFile="",
wildcard=wildcard,
style=wx.OPEN | wx.CHANGE_DIR
)
if dlg.ShowModal() == wx.ID_OK:
flist=dlg.GetPath()
config=MyConfig()
try:
ffp=codecs.open(flist,encoding='utf-8',mode='r')
config.readfp(ffp)
except:
dlg = wx.MessageDialog(self, u'这不是一个合法的配置文件!',
u'出错了!',
wx.OK | wx.ICON_ERROR
)
dlg.ShowModal()
dlg.Destroy()
return
secs=config.sections()
## if 'last' in secs:
## secs[secs.index('last')]=u'导入的当前配置'
kname_list=[]
for k in KeyConfigList:
kname_list.append(k[0])
cdlg=CheckDialog(self,u'选择要导入的配置...',secs)
cdlg.ShowModal()
rlist=cdlg.GetChecks()
if len(rlist)<=0:return
tname=''
for r in rlist:
if secs[r]=='last':
tname=u'导入的当前配置'
else:
tname=secs[r]
if tname in kname_list:
dlg=wx.MessageDialog(self,secs[r]+u" 已有同名配置方案,是否继续?",u"导入",wx.YES_NO|wx.NO_DEFAULT)
if dlg.ShowModal()==wx.ID_NO:
dlg.Destroy()
continue
else:
KeyConfigList.__delitem__(kname_list.index(secs[r]))
kconfig=[]
kconfig.append(tname)
for f,v in keygrid.LB2_func_list.items():
try:
cstr=config.get(secs[r],f)
cstr_list=cstr.split('&&')
for cs in cstr_list:
kconfig.append((f,cs))
except:
kconfig.append((f,v))
KeyConfigList.append(kconfig)
cur_str=self.combo_box_7.GetStringSelection()
self.combo_box_7.Clear()
for t in KeyConfigList:
if t[0]=='last':self.combo_box_7.Append(u'当前设置')
else:
self.combo_box_7.Append(t[0])
self.combo_box_7.SetStringSelection(cur_str)
def OnExportTheme(self,evt):
global ThemeList,GlobalConfig
clist=[]
clist.append(u'当前设置')
for t in ThemeList:
clist.append(t['name'])
edlg=CheckDialog(self,u'导出显示方案',clist)
edlg.ShowModal()
rlist=edlg.GetChecks()
if len(rlist)>0:
wildcard = u"litebook2显示配置文件 (*.lbt)|*.lbt|"
dlg = wx.FileDialog(
self, message=u"导出为...", defaultDir=GlobalConfig['LastDir'],
defaultFile="", wildcard=wildcard, style=wx.SAVE | wx.FD_OVERWRITE_PROMPT
)
if dlg.ShowModal() == wx.ID_OK:
config=MyConfig()
config.add_section('Appearance')
img_file_list=[]
if 0 in rlist:
ft=GlobalConfig['CurFont']
save_str=unicode(ft.GetPointSize())+u'|'+unicode(ft.GetFamily())+u'|'+unicode(ft.GetStyle())+u'|'+unicode(ft.GetWeight())+u'|'+unicode(ft.GetUnderlined())+u'|'+ft.GetFaceName()+u'|'+unicode(ft.GetDefaultEncoding())+u'|'+unicode(GlobalConfig['CurFColor'])+u'|'+unicode(GlobalConfig['CurBColor'])
save_str+=u'|'+unicode(os.path.basename(GlobalConfig['backgroundimg']))
img_file_list.append[GlobalConfig['backgroundimg']]
save_str+=u'|'+unicode(GlobalConfig['showmode'])
save_str+=u'|'+unicode(GlobalConfig['backgroundimglayout'])
save_str+=u'|'+unicode(GlobalConfig['underline'])
save_str+=u'|'+unicode(GlobalConfig['underlinestyle'])
save_str+=u'|'+unicode(GlobalConfig['underlinecolor'])
save_str+=u'|'+unicode(GlobalConfig['pagemargin'])
save_str+=u'|'+unicode(GlobalConfig['bookmargin'])
save_str+=u'|'+unicode(GlobalConfig['vbookmargin'])
save_str+=u'|'+unicode(GlobalConfig['centralmargin'])
save_str+=u'|'+unicode(GlobalConfig['linespace'])
save_str+=u'|'+unicode(GlobalConfig['vlinespace'])
config.set('Appearance','last',save_str)
rlist.remove(0)
for r in rlist:
f=ThemeList[r-1]['config'].split('|')
f[9]=os.path.basename(f[9])
save_str=''
for x in f:
save_str=save_str+x+'|'
save_str=save_str[:-1]
config.set('Appearance',ThemeList[r-1]['name'],save_str)
img_file_list.append(ThemeList[r-1]['backgroundimg'])
try:
tmp_ini_name=cur_file_dir()+u'/litebook_tmp/'+'/_tmp_ltb_thm_export.ini'
ConfigFile=codecs.open(tmp_ini_name,encoding='utf-8',mode='w')
config.write(ConfigFile)
ConfigFile.close()
except:
dlg = wx.MessageDialog(None, u'导出失败!',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
save_name=dlg.GetPath()
if save_name[-4:]<>'.lbt':
save_name+=u'.lbt'
export_file=zipfile.ZipFile(save_name,'w')
export_file.write(cur_file_dir()+u'/litebook_tmp/'+'/_tmp_ltb_thm_export.ini','LB_Display_theme.ini')
for img in img_file_list:
if isinstance(img,unicode):
img=img.encode('gbk')
fpath=img
if fpath<>'' and fpath<>None:
if img.find('/')==-1:
fpath=cur_file_dir()+'/background/'+img
try:
export_file.write(fpath,os.path.basename(fpath))
except:
dlg = wx.MessageDialog(None, u'无法导出 '+fpath,u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
try:
os.remove(save_name)
except:
return
return
export_file.close()
def OnImportTheme(self,evt):
global GlobalConfig,ThemeList
wildcard = u"litebook2显示配置文件 (*.lbt)|*.lbt|" \
u"所有文件 (*.*)|*.*"
dlg = wx.FileDialog(
self, message=u"选择要导入的文件:",
defaultDir=GlobalConfig['LastDir'],
defaultFile="",
wildcard=wildcard,
style=wx.OPEN | wx.CHANGE_DIR
)
if dlg.ShowModal() == wx.ID_OK:
flist=dlg.GetPath()
try:
importf=zipfile.ZipFile(flist)
fnamelist=importf.namelist()
for fname in fnamelist:
if fname.find("..")<>-1 or fname.find("/")<>-1:
raise
importf.extractall(cur_file_dir()+u'/litebook_tmp/')
config=MyConfig()
ffp=codecs.open(cur_file_dir()+u'/litebook_tmp/LB_Display_theme.ini',encoding='utf-8',mode='r')
config.readfp(ffp)
if not config.has_section('Appearance'):raise
except:
dlg = wx.MessageDialog(self, u'这不是一个合法的配置文件!',
u'出错了!',
wx.OK | wx.ICON_ERROR
)
dlg.ShowModal()
dlg.Destroy()
return
ft_list=config.items('Appearance')
clist=[]
for f in ft_list:
clist.append(f[0])
cdlg=CheckDialog(self,u'选择要导入的显示配置',clist)
cdlg.ShowModal()
cdlg.Destroy()
rlist=cdlg.GetChecks()
cur_nlist=[]
for t in ThemeList:
cur_nlist.append(t['name'])
for r in rlist:
if clist[r]=='last':
tname=u'导入的当前配置'
else:
tname=clist[r]
f=ft_list[r][1].split('|')
if len(f)<>21: raise
try:
l={}
l['font']=wx.Font(int(f[0]),int(f[1]),int(f[2]),int(f[3]),eval(f[4]),f[5],int(f[6]))
l['fcolor']=eval(f[7])
l['bcolor']=eval(f[8])
if f[9]<>'None' and f[9]<>'':
l['backgroundimg']=f[9]
if f[9] in fnamelist:
shutil.copyfile(cur_file_dir()+u'/litebook_tmp/'+"/"+f[9],cur_file_dir()+'/background/'+f[9])
else:
dlg = wx.MessageDialog(self, u'在导入的文件中未找到'+f[9],
u'出错了!',
wx.OK | wx.ICON_ERROR
)
dlg.ShowModal()
dlg.Destroy()
return
else:
l['backgroundimg']=None
l['showmode']=f[10]
l['backgroundimglayout']=f[11]
l['underline']=eval(f[12])
l['underlinestyle']=int(f[13])
l['underlinecolor']=f[14]
l['pagemargin']=int(f[15])
l['bookmargin']=int(f[16])
l['vbookmargin']=int(f[17])
l['centralmargin']=int(f[18])
l['linespace']=int(f[19])
l['vlinespace']=int(f[20])
l['name']=tname
l['config']=ft_list[r][1]
except:
dlg = wx.MessageDialog(self, tname+u'不是一个合法的配置方案!',
u'出错了!',
wx.OK | wx.ICON_ERROR
)
dlg.ShowModal()
dlg.Destroy()
continue
if tname in cur_nlist:
dlg=wx.MessageDialog(self,tname+u" 已有同名配置方案,是否继续?",u"导入",wx.YES_NO|wx.NO_DEFAULT)
if dlg.ShowModal()==wx.ID_NO:
dlg.Destroy()
continue
else:
ThemeList.__delitem__(cur_nlist.index(tname))
ThemeList.append(l)
cur_str=self.combo_box_1.GetStringSelection()
self.combo_box_1.Clear()
self.combo_box_1.Append(u'当前设置')
for t in ThemeList:
self.combo_box_1.Append(t['name'])
self.combo_box_1.SetStringSelection(cur_str)
# end of class NewOptionDialog
class CheckDialog(wx.Dialog):
def __init__(self, parent,title='',clist=[]):
# begin wxGlade: CheckDialog.__init__
wx.Dialog.__init__(self,parent,-1,style=wx.DEFAULT_DIALOG_STYLE)
self.list_box_1 = wx.CheckListBox(self, -1, choices=[])
self.button_1 = wx.Button(self, -1, u"确定")
self.button_2 = wx.Button(self, -1, u"取消")
self.selections=[]
self.Bind(wx.EVT_BUTTON, self.OnOK, self.button_1)
self.Bind(wx.EVT_BUTTON, self.OnCancell, self.button_2)
self.list_box_1.Set(clist)
self.SetTitle(title)
self.__do_layout()
# end wxGlade
def __do_layout(self):
# begin wxGlade: CheckDialog.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_1.Add(self.list_box_1, 0, wx.EXPAND, 0)
sizer_2.Add(self.button_1, 0, 0, 0)
sizer_2.Add(self.button_2, 0, 0, 0)
sizer_1.Add(sizer_2, 0, wx.EXPAND, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
# end wxGlade
def OnCancell(self,evt):
self.Destroy()
def OnOK(self,evt):
n=self.list_box_1.GetCount()
i=0
while i<n:
if self.list_box_1.IsChecked(i):
self.selections.append(i)
i+=1
self.Close()
def GetChecks(self):
return self.selections
# end of class CheckDialog
class SliderDialog(wx.Dialog):
def __init__(self, parent,val,inpos=(-1,-1)):
global MYOS
# begin wxGlade: MyDialog.__init__
#kwds["style"] = wx.RESIZE_BORDER|wx.THICK_FRAME
wx.Dialog.__init__(self,parent, pos=inpos,style=wx.CLOSE_BOX|wx.THICK_FRAME)
self.sizer_1_staticbox = wx.StaticBox(self, -1, u"当前进度")
self.slider_1 = wx.Slider(self, -1, val, 0, 100, style=wx.SL_LABELS)
self.fristtime=True
if MYOS == 'Windows':
self.slider_1.Bind(wx.EVT_KEY_UP,self.OnChar)
self.slider_1.Bind(wx.EVT_KILL_FOCUS,self.Closeme)
else:
self.Bind(wx.EVT_KEY_UP,self.OnChar)
self.Bind(wx.EVT_KILL_FOCUS,self.Closeme)
self.slider_1.Bind(wx.EVT_SCROLL,self.OnScroll)
self.Bind(wx.EVT_CLOSE,self.Closeme)
self.slider_1.Bind(wx.EVT_KILL_FOCUS,self.Closeme)
self.__set_properties()
self.__do_layout()
self.win=self.GetParent()
if MYOS != 'Windows':
self.SetFocus()
# end wxGlade
def __set_properties(self):
# begin wxGlade: MyDialog.__set_properties
# end wxGlade
self.SetTransparent(220)
self.slider_1.SetLineSize(1)
def __do_layout(self):
# begin wxGlade: MyDialog.__do_layout
sizer_1 = wx.StaticBoxSizer(self.sizer_1_staticbox, wx.VERTICAL)
sizer_1.Add(self.slider_1, 0, wx.EXPAND, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
# end wxGlade
self.SetSize((200,-1))
# end of class MyDialog
def Closeme(self,evt=None):
self.Destroy()
self.win.slider=None
return
##
## def ToTop(self,evt):
## self.win.text_ctrl_1.ScrollTop()
##
## def ToBottom(self,evt):
## self.win.text_ctrl_1.ScrollBottom()
def OnScroll(self,evt):
tval=self.slider_1.GetValue()
if tval<>100:
tpos=int(float(self.win.text_ctrl_1.ValueCharCount)*(float(tval)/100.0))
self.win.text_ctrl_1.JumpTo(tpos)
else:
self.win.text_ctrl_1.ScrollBottom()
def OnChar(self,evt):
global KeyConfigList
for k in KeyConfigList:
if k[0]=='last':
break
keystr=keygrid.key2str(evt)
for f in k:
if f[0]==u'显示进度条':
break
key=evt.GetKeyCode()
if self.fristtime and keystr==f[1]:
self.fristtime=False
return
if key==wx.WXK_ESCAPE or keystr==f[1]:
self.Closeme()
else:
evt.Skip()
def fadein(self):
t=100
while t<250:
self.SetTransparent(t)
self.Show()
time.sleep(0.01)
t+=15
class cnsort:
#use the code from henrysting@gmail.com, change a little bit
def __init__(self):
global MYOS
# 建立拼音辞典
self.dic_py = dict()
try:
f_py = open(cur_file_dir()+'/py.dat',"r")
f_bh = open(cur_file_dir()+'/bh.dat',"r")
except:
return None
content_py = f_py.read()
lines_py = content_py.split('\n')
n=len(lines_py)
for i in range(0,n-1):
word_py, mean_py = lines_py[i].split('\t', 1)#将line用\t进行分割,最多分一次变成两块,保存到word和mean中去
self.dic_py[word_py]=mean_py
f_py.close()
#建立笔画辞典
self.dic_bh = dict()
content_bh = f_bh.read()
lines_bh = content_bh.split('\n')
n=len(lines_bh)
for i in range(0,n-1):
word_bh, mean_bh = lines_bh[i].split('\t', 1)#将line用\t进行分割,最多分一次变成两块,保存到word和mean中去
self.dic_bh[word_bh]=mean_bh
f_bh.close()
# 辞典查找函数
def searchdict(self,dic,uchar):
if isinstance(uchar, str):
uchar = unicode(uchar,'utf-8')
if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
value=dic.get(uchar.encode('utf-8'))
if value == None:
value = '*'
else:
value = uchar
if isinstance(value,str):
return value.decode('gbk')
else:
return value
#比较单个字符
def comp_char_PY(self,A,B):
if A==B:
return -1
pyA=self.searchdict(self.dic_py,A)
pyB=self.searchdict(self.dic_py,B)
if pyA > pyB:
return 1
elif pyA < pyB:
return 0
else:
bhA=eval(self.searchdict(self.dic_bh,A))
bhB=eval(self.searchdict(self.dic_bh,B))
if bhA > bhB:
return 1
elif bhA < bhB:
return 0
else:
return False
#比较字符串
def comp_char(self,A,B):
charA = A.decode("utf-8")
charB = B.decode("utf-8")
n=min(len(charA),len(charB))
i=0
while i < n:
dd=self.comp_char_PY(charA[i],charB[i])
if dd == -1:
i=i+1
if i==n:
dd=len(charA)>len(charB)
else:
break
return dd
# 排序函数
def cnsort(self,nline):
n = len(nline)
lines="\n".join(nline)
for i in range(1, n): # 插入法
tmp = nline[i]
j = i
while j > 0 and self.comp_char(nline[j-1],tmp):
nline[j] = nline[j-1]
j -= 1
nline[j] = tmp
return nline
## # 将一个字符串转换成一个含每个字拼音的list,字符串中的连续的ASCII会按原样放在一个值内
## def strToPYL(istr):
## global dic_py
## if isinstance(istr,str):
## istr=istr.decode('gbk')
## istr=istr.encode('utf-8')
## istr=istr.decode('utf-8')
## else:
## if isinstance(istr,unicode):
## istr=istr.encode('utf-8')
## istr=istr.decode('utf-8')
## else:
## return None
## lastasic=False
## py_list=[]
## for ichr in istr:
## if ord(ichr)<=255:
## if lastasic:
## py_list[len(py_list)-1]+=ichr
## else:
## py_list.append(ichr)
## lastasic=True
## else:
## py_list.append(searchdict(dic_py,ichr)[:-1])
## lastasic=False
## return py_list
# 将一个字符串转换成一个含每个字拼音的list,字符串中的连续的ASCII会按原样放在一个值内
def strToPYS(self,istr):
if isinstance(istr,str):
istr=istr.decode('gbk')
istr=istr.encode('utf-8')
istr=istr.decode('utf-8')
else:
if isinstance(istr,unicode):
istr=istr.encode('utf-8')
istr=istr.decode('utf-8')
else:
return None
rstr=''
for ichr in istr:
if ord(ichr)<=255:rstr+=ichr
else:
rstr+=self.searchdict(self.dic_py,ichr)[:-1]
return rstr
class Convert_EPUB_Dialog(wx.Dialog):
def __init__(self, parent,outfile,title,author):
# begin wxGlade: Search_Web_Dialog.__init__
wx.Dialog.__init__(self, parent=parent)
self.outfile=outfile
self.title=title
self.author=author
self.sizer_3_staticbox = wx.StaticBox(self, -1, u"输出")
self.sizer_1_staticbox = wx.StaticBox(self, -1, u"转换为EPUB文件")
self.sizer_2_staticbox = wx.StaticBox(self, -1, "")
self.radio_box_1 = wx.RadioBox(self, -1, u"章节划分方式:", choices=[u"自动", u"按照字数"], majorDimension=2, style=wx.RA_SPECIFY_COLS)
self.label_zishu = wx.StaticText(self, -1, u"字数:")
self.text_ctrl_zishu = wx.TextCtrl(self, -1, "")
self.label_13 = wx.StaticText(self, -1, u"书名:")
self.text_ctrl_2 = wx.TextCtrl(self, -1, "")
self.label_author = wx.StaticText(self, -1, u"作者:")
self.text_ctrl_author = wx.TextCtrl(self, -1, "")
self.label_author_copy = wx.StaticText(self, -1, u"输出文件:")
self.text_ctrl_3 = wx.TextCtrl(self, -1, "")
self.button_1 = wx.Button(self, -1, u"另存为")
self.button_3 = wx.Button(self, -1, u" 确定 ")
self.button_4 = wx.Button(self, -1, u" 取消 ")
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_RADIOBOX, self.OnChose, self.radio_box_1)
self.Bind(wx.EVT_BUTTON, self.OnSaveas, self.button_1)
self.Bind(wx.EVT_BUTTON, self.OnOK, self.button_3)
self.Bind(wx.EVT_BUTTON, self.OnCancell, self.button_4)
self.Bind(wx.EVT_TEXT,self.onChangeName,self.text_ctrl_2)
# end wxGlade
def __set_properties(self):
# begin wxGlade: Search_Web_Dialog.__set_properties
self.SetTitle(u"文件转换")
self.radio_box_1.SetSelection(0)
self.text_ctrl_zishu.SetValue('10000')
self.text_ctrl_zishu.Enable(False)
self.text_ctrl_3.SetMinSize((200, -1))
# end wxGlade
self.text_ctrl_author.SetValue(self.author)
self.text_ctrl_2.SetValue(self.title)
self.text_ctrl_3.SetValue(os.path.abspath(GlobalConfig['ShareRoot']+os.sep+self.outfile+u".epub"))
def __do_layout(self):
# begin wxGlade: Search_Web_Dialog.__do_layout
sizer_1 = wx.StaticBoxSizer(self.sizer_1_staticbox, wx.VERTICAL)
sizer_4 = wx.BoxSizer(wx.HORIZONTAL)
sizer_3 = wx.StaticBoxSizer(self.sizer_3_staticbox, wx.VERTICAL)
sizer_author = wx.BoxSizer(wx.HORIZONTAL)
sizer_23 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2 = wx.StaticBoxSizer(self.sizer_2_staticbox, wx.VERTICAL)
sizer_zishu = wx.BoxSizer(wx.HORIZONTAL)
sizer_2.Add(self.radio_box_1, 0, 0, 0)
sizer_zishu.Add(self.label_zishu, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_zishu.Add(self.text_ctrl_zishu, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_2.Add(sizer_zishu, 0, wx.EXPAND, 0)
sizer_1.Add(sizer_2, 0, wx.EXPAND, 0)
sizer_23.Add(self.label_13, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_23.Add(self.text_ctrl_2, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_1.Add(sizer_23, 0, wx.EXPAND, 0)
sizer_author.Add(self.label_author, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_author.Add(self.text_ctrl_author, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_1.Add(sizer_author, 0, wx.EXPAND, 0)
sizer_3.Add(self.label_author_copy, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_3.Add(self.text_ctrl_3, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_3.Add(self.button_1, 0, wx.ALIGN_CENTER_VERTICAL, 0)
sizer_1.Add(sizer_3, 0, wx.EXPAND, 0)
sizer_4.Add(self.button_3, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
sizer_4.Add(self.button_4, 0, wx.ALL|wx.ALIGN_RIGHT|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_1.Add(sizer_4, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
# end wxGlade
def onChangeName(self,evt):
newtit=self.text_ctrl_2.GetValue().strip()
self.text_ctrl_3.SetValue(os.path.abspath(GlobalConfig['ShareRoot']+os.sep+newtit+u".epub"))
def OnChose(self, event): # wxGlade: Search_Web_Dialog.<event_handler>
if event.GetInt()==1:
if event.IsChecked():
self.text_ctrl_zishu.Enable()
else:
self.text_ctrl_zishu.Disable()
event.Skip()
def OnSaveas(self, event): # wxGlade: Search_Web_Dialog.<event_handler>
wildcard = u"EPUB 电子书 (*.epub)|*.epub|" \
"All files (*.*)|*.*"
dlg = wx.FileDialog(
self, message=u"另存为", defaultDir=GlobalConfig['ShareRoot'],
defaultFile=self.title, wildcard=wildcard, style=wx.SAVE
)
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
self.text_ctrl_3.SetValue(path)
def OnOK(self, event): # wxGlade: Search_Web_Dialog.<event_handler>
good=True
self.divide_method=self.radio_box_1.GetSelection()
if self.divide_method==1:
try:
self.zishu=int(self.text_ctrl_zishu.GetValue())
except:
good=False
if good:
if self.zishu<10000:good=False
if not good:
dlg = wx.MessageDialog(self, u'字数必须大于等于10000!',
u'出错了!',
wx.OK | wx.ICON_ERROR
)
dlg.ShowModal()
dlg.Destroy()
return
elif self.divide_method==0: self.zishu=10000
outfile=self.text_ctrl_3.GetValue()
if os.path.isdir(os.path.dirname(outfile)) and outfile[-5:].lower()=='.epub' and os.access(os.path.dirname(outfile),os.W_OK|os.R_OK):
if os.path.exists(outfile):
dlg = wx.MessageDialog(self, u'已经有叫这个名字的文件,你确定要覆盖原有文件吗?',u"提示!",wx.YES_NO|wx.ICON_QUESTION)
if dlg.ShowModal()==wx.ID_NO:
dlg.Destroy()
return
if outfile[-5:].lower()=='.epub':
outfile=outfile[:-5]
self.outfile=outfile
else:
dlg = wx.MessageDialog(self, u'输出的文件名或路径非法!',
u'出错了!',
wx.OK | wx.ICON_ERROR
)
dlg.ShowModal()
dlg.Destroy()
return
self.title=self.text_ctrl_2.GetValue()
self.author=self.text_ctrl_author.GetValue()
self.id='OK'
self.Close()
def OnCancell(self, event):
self.id=''
self.Destroy()
class FileDrop(wx.FileDropTarget):
def __init__(self, window):
wx.FileDropTarget.__init__(self)
self.window = window
def OnDropFiles(self, x, y, filenames):
self.window.Menu103(None)
for fname in filenames:
sufix=fname.lower()[-4:]
if sufix=='.rar' or sufix=='.zip':
dlg=ZipFileDialog(self.window,fname)
dlg.ShowModal()
if dlg.selected_files<>[]:
self.window.LoadFile(dlg.selected_files,'zip',fname,openmethod='append')
dlg.Destroy()
else:
dlg.Destroy()
else:
self.window.LoadFile(filenames,openmethod='append')
if FullVersion:
class LBHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Simple HTTP request handler with GET and HEAD commands.
This serves files from the current directory and any of its
subdirectories. The MIME type for files is determined by
calling the .guess_type() method.
The GET and HEAD requests are identical except that the HEAD
request omits the actual contents of the file.
"""
__version__ = "0.1"
__all__ = ["LBHTTPRequestHandler"]
server_version = "SimpleHTTP/" +__version__
prefixpath=None
def log_request(self,code=1,size=0):
pass
def log_error(self,*args, **kwds):
pass
def setup(self):
global GlobalConfig
BaseHTTPServer.BaseHTTPRequestHandler.setup(self)
self.prefixpath=GlobalConfig['ShareRoot']
def do_GET(self):
"""Serve a GET request."""
f = self.send_head()
if f:
self.copyfile(f, self.wfile)
f.close()
def do_HEAD(self):
"""Serve a HEAD request."""
f = self.send_head()
if f:
f.close()
def send_head(self):
"""Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied
to the outputfile by the caller unless the command was HEAD,
and must be closed by the caller under all circumstances), or
None, in which case the caller has nothing further to do.
"""
path = self.translate_path(self.path)
f = None
if os.path.isdir(path):
if not self.path.endswith('/'):
# redirect browser - doing basically what apache does
self.send_response(301)
self.send_header("Location", self.path + "/")
self.end_headers()
return None
for index in "index.html", "index.htm":
index = os.path.join(path, index)
if os.path.exists(index):
path = index
break
else:
return self.list_directory(path)
ctype = self.guess_type(path)
try:
# Always read in binary mode. Opening files in text mode may cause
# newline translations, making the actual size of the content
# transmitted *less* than the content-length!
f = open(path, 'rb')
except IOError:
self.send_error(404,"File not found")
return None
self.send_response(200)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
self.send_header("Content-Length", str(fs[6]))
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.end_headers()
return f
def list_directory(self, path):
client_addr = self.client_address[0]
if myup.checkLocalIP(client_addr)==False:
return
try:
browser=unicode(self.headers['user-agent'])
except:
browser=u'unknown'
f = StringIO()
if browser.find(u'Stanza')<>-1:
#if the browser is Stanza
flist=glob.glob(self.prefixpath+os.sep+"*.epub")
## fp=open('test.xml','r')
## buf=fp.read()
xml_header=u"""<?xml version='1.0' encoding='utf-8'?>
<feed xmlns:dc="http://purl.org/dc/terms/" xmlns:opds="http://opds-spec.org/2010/catalog" xmlns="http://www.w3.org/2005/Atom">
<title>LiteBook书库</title>
<author>
<name>LiteBook.Author</name>
<uri>http://code.google.com/p/litebook-project/</uri>
</author>
"""
xml_header=xml_header.encode('utf-8')
f.write(xml_header)
for fname in flist:
## if not isinstance(fname,unicode):
## fname=fname.decode('gbk')
f.write(" <entry>\n")
if not isinstance(fname,unicode): fname=fname.decode('gbk')
fname=fname.encode('utf-8')
bname=os.path.basename(fname)
f.write("<title>"+bname[:-4]+'</title>\n')
f.write('<author>\n<name>unknown</name></author>\n')
cont=u'<content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml">标签:General Fiction<br/></div></content>'
cont=cont.encode('utf-8')
f.write(cont+'\n')
burl="<link href='/"+bname+"' type='application/epub+zip'/>\n"
burl=urllib.quote('/'+bname)
f.write("<link href='"+burl+"' type='application/epub+zip'/>\n")
f.write(" </entry>\n")
f.write('</feed>')
length = f.tell()
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "application/atom+xml")
self.send_header("Content-Length", str(length))
self.end_headers()
else:
msg=u"""<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>LItebook共享书库</title>
</head>
<body>
<h2>LiteBook 共享图书列表:</h2>
<ul>"""
msg=msg.encode('utf-8')
f.write(msg)
flist=glob.glob(self.prefixpath+os.sep+"*.*")
for fname in flist:
if not isinstance(fname,unicode): fname=fname.decode('gbk')
fname=fname.encode('utf-8')
bname=os.path.basename(fname)
burl=urllib.quote('/'+bname)
f.write("<li><a href='"+burl+"'>"+bname+"</a></li>\n")
d=datetime(2000,1,1)
ds=unicode(d.now())
end=u"</ul>注:本列表由litebook自动生成于"+ds+"</body></html>"
end=end.encode('utf-8')
f.write(end)
length=f.tell()
f.seek(0)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Content-Length", str(length))
self.end_headers()
return f
def translate_path(self, path):
"""Translate a /-separated PATH to the local filename syntax.
Components that mean special things to the local file system
(e.g. drive or directory names) are ignored. (XXX They should
probably be diagnosed.)
- add prefix_path support; added by Hu Jun 2011-03-13
"""
# abandon query parameters
path = path.split('?',1)[0]
path = path.split('#',1)[0]
path = posixpath.normpath(urllib.unquote(path))
path=path.decode('utf-8')
words = path.split('/')
words = filter(None, words)
path=self.prefixpath
for word in words:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if word in (os.curdir, os.pardir): continue
path = os.path.join(path, word)
return path
def copyfile(self, source, outputfile):
"""Copy all data between two file objects.
The SOURCE argument is a file object open for reading
(or anything with a read() method) and the DESTINATION
argument is a file object open for writing (or
anything with a write() method).
The only reason for overriding this would be to change
the block size or perhaps to replace newlines by CRLF
-- note however that this the default server uses this
to copy binary data as well.
"""
if not 'Range' in self.headers:
shutil.copyfileobj(source, outputfile)
else:#this is to support Range Get
(startpos,endpos)=self.headers['Range'][6:].split('-')
if startpos=='':startpos=0
else:
startpos=int(startpos)
if endpos=='':
endpos=os.fstat(source.fileno()).st_size
else:
endpos=int(endpos)
source.seek(startpos)
ins=source.read(endpos-startpos)
outputfile.write(ins)
source.close()
outputfile.close()
def guess_type(self, path):
"""Guess the type of a file.
Argument is a PATH (a filename).
Return value is a string of the form type/subtype,
usable for a MIME Content-type header.
The default implementation looks the file's extension
up in the table self.extensions_map, using application/octet-stream
as a default; however it would be permissible (if
slow) to look inside the data to make a better guess.
"""
base, ext = posixpath.splitext(path)
if ext in self.extensions_map:
return self.extensions_map[ext]
ext = ext.lower()
if ext in self.extensions_map:
return self.extensions_map[ext]
else:
return self.extensions_map['']
## if not mimetypes.inited:
## mimetypes.init() # try to read system mime.types
## extensions_map = mimetypes.types_map.copy()
extensions_map={}
extensions_map.update({
'': 'application/octet-stream', # Default
'.py': 'text/plain',
'.c': 'text/plain',
'.h': 'text/plain',
'.epub': 'application/epub+zip'
})
class ThreadedLBServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
class ThreadAddUPNPMapping(threading.Thread):
def __init__(self,win):
threading.Thread.__init__(self)
self.win=win
def run(self):
global GlobalConfig
#add UPNP mapping
ml=[
{'port':GlobalConfig['ServerPort'],'proto':'TCP','desc':"LITEBOOK"},
{'port':GlobalConfig['LTBNETPort'],'proto':'UDP','desc':"LITEBOOK"},
]
r=False
try:
r=myup.changePortMapping(ml,'add')
except Exception as inst:
print inst
r=False
pass
if r==False:
evt=AlertMsgEvt(txt=u'UPNP端口映射设置失败!请手动设置宽带路由器并添加相应的端口映射。')
else:
evt=AlertMsgEvt(txt=u'UPNP端口映射设置完成')
wx.PostEvent(self.win, evt)
evt = UpdateStatusBarEvent(FieldNum = 3, Value =u'')
wx.PostEvent(self.win, evt)
return
class ThreadChkPort(threading.Thread):
def __init__(self,win,alertOnOpen=True):
threading.Thread.__init__(self)
self.win=win
self.aOO=alertOnOpen
def run(self):
global GlobalConfig
for x in range(30):
time.sleep(1)
try:
pstatus=GlobalConfig['kadp_ctrl'].PortStatus(False)
except:
continue
if pstatus==-1:
evt=AlertMsgEvt(txt=u'LTBNET端口未打开!请设置宽带路由器并添加相应的端口映射。')
wx.PostEvent(self.win, evt)
evt = UpdateStatusBarEvent(FieldNum = 3, Value =u'')
wx.PostEvent(self.win, evt)
return
elif pstatus==1:
if self.aOO==True:
evt=AlertMsgEvt(txt=u'LTBNET端口已打开!')
wx.PostEvent(self.win, evt)
evt = UpdateStatusBarEvent(FieldNum = 3, Value =u'')
wx.PostEvent(self.win, evt)
return
evt=AlertMsgEvt(txt=u'LTBNET端口未打开!请设置宽带路由器并添加相应的端口映射。')
wx.PostEvent(self.win, evt)
evt = UpdateStatusBarEvent(FieldNum = 3, Value =u'')
wx.PostEvent(self.win, evt)
return
def redirectConfPath():
"""
return path of redirection config file as unicode
"""
if MYOS == 'Windows':
return os.environ['APPDATA'].decode(SYSENC)+u"\\litebook_red.ini"
else:
return unicode(os.environ['HOME'],SYSENC)+u"/.litebook_red.ini"
def readRedConf():
"""
This func is to return a conf path, include pathes all litebook conf
"""
global GlobalConfig
GlobalConfig['redConfDir']=''
GlobalConfig['path_list']=None
config = MyConfig()
try:
ffp=codecs.open(redirectConfPath(),encoding='utf-8',mode='r')
config.readfp(ffp)
except Exception as inst:
return False
try:
confPath=config.get('settings','confdir').strip()
if not os.path.isdir(confPath):
return False
GlobalConfig['redConfDir']=confPath
path_list={}
path_list['cache_dir']=confPath+os.sep+u"cache"
path_list['bookdb']=confPath+os.sep+u"litebook.bookdb"
path_list['log']=confPath+os.sep+u"litebook.log"
path_list['conf']=confPath+os.sep+u"litebook.ini"
path_list['key_conf']=confPath+os.sep+u"litebook_key.ini"
GlobalConfig['path_list']=path_list
return path_list
except Exception as inst:
return False
def writeRedConf():
"""
Write new redirct conf dir into config
"""
global GlobalConfig
if isinstance(GlobalConfig['redConfDir'],str) or isinstance(GlobalConfig['redConfDir'],unicode):
if os.path.isdir(GlobalConfig['redConfDir']):
config = MyConfig()
config.add_section('settings')
config.set('settings','confdir',GlobalConfig['redConfDir'])
ConfigFile=codecs.open(redirectConfPath(),encoding='utf-8',mode='w')
config.write(ConfigFile)
ConfigFile.close()
def loadDefaultConfPath():
"""
load default conf path list into GloablConfig
"""
global GlobalConfig
GlobalConfig['path_list']={}
if MYOS == 'Windows':
GlobalConfig['path_list']['cache_dir']=os.environ['USERPROFILE'].decode(SYSENC)+u"\\litebook\\cache"
GlobalConfig['path_list']['bookdb']=os.environ['APPDATA'].decode(SYSENC)+u"\\litebook.bookdb"
GlobalConfig['path_list']['conf']=os.environ['APPDATA'].decode(SYSENC)+u"\\litebook.ini"
GlobalConfig['path_list']['key_conf']=os.environ['APPDATA'].decode(SYSENC)+u"\\litebook_key.ini"
else:
GlobalConfig['path_list']['cache_dir']=unicode(os.environ['HOME'],SYSENC)+u"/litebook/cache"
GlobalConfig['path_list']['bookdb']=unicode(os.environ['HOME'],SYSENC)+u"/.litebook.bookdb"
GlobalConfig['path_list']['conf']=unicode(os.environ['HOME'],SYSENC)+u"/.litebook.ini"
GlobalConfig['path_list']['key_conf']=unicode(os.environ['HOME'],SYSENC)+u"/.litebook_key.ini"
if __name__ == "__main__":
path_list=readRedConf()
if path_list == False:
loadDefaultConfPath()
cache_dir=GlobalConfig['path_list']['cache_dir']
if not os.path.isdir(cache_dir):
os.makedirs(cache_dir)
bookdb_dir=GlobalConfig['path_list']['bookdb']
try:
SqlCon = sqlite3.connect(bookdb_dir)
except:
print bookdb_dir+u" is not a sqlite file!"
SqlCur=SqlCon.cursor()
found=True
sqlstr="select name from sqlite_master where type='table' and name='book_history'"
try:
SqlCur.execute(sqlstr)
except:
found=False
if SqlCur.fetchall() == []:
found=False
if found==False:
sqlstr = """CREATE TABLE `book_history` (
`name` varchar(512) NOT NULL,
`type` varchar(20) NOT NULL,
`zfile` varchar(512) default NULL,
`date` float unsigned NOT NULL
) ;
"""
SqlCur.execute(sqlstr)
sqlstr="select name from sqlite_master where type='table' and name='subscr'"
found=True
try:
SqlCur.execute(sqlstr)
except:
found=False
if SqlCur.fetchall() == []:
found=False
if found == False:
sqlstr = """
CREATE TABLE `subscr` (
`bookname` varchar(512) NOT NULL,
`index_url` varchar(512) PRIMARY KEY,
`last_chapter_name` varchar(512) default NULL,
`last_update` varchar(128) NOT NULL,
`chapter_count` int unsigned NOT NULL,
`save_path` varchar(512) NOT NULL,
`plugin_name` varchar(128) NOT NULL
) ;
"""
SqlCon.execute(sqlstr)
if MYOS == 'Windows':
logfilename=os.environ['APPDATA'].decode(SYSENC)+u"\\litebook.log"
else:
logfilename=unicode(os.environ['HOME'],SYSENC)+u"/.litebook.log"
app = wx.App(False,logfilename)
#app = wx.PySimpleApp(0)
fname=None
if MYOS != 'Windows':
if len(sys.argv)>1:
if sys.argv[1]=='-reset':
print u"此操作将把当前配置恢复为缺省配置,可以解决某些启动问题,但是会覆盖当前设置,是否继续?(Y/n)"
inc=raw_input()
if inc=='Y':
try:
os.remove(unicode(os.environ['HOME'],SYSENC)+u"/.litebook_key.ini")
os.remove(unicode(os.environ['HOME'],SYSENC)+u"/.litebook.ini")
except:
pass
elif sys.argv[1]!='-full':
fname=sys.argv[1]
fname=os.path.abspath(fname)
else:
if len(sys.argv)>2:
fname=sys.argv[2]
fname=os.path.abspath(fname)
if fname!=None:
if not os.path.exists(fname):
print fname,u'不存在!'
sys.exit()
else:
if len(sys.argv)>1:
if sys.argv[1].lower()=='-reset':
dlg=wx.MessageDialog(None,u"此操作将把当前配置恢复为缺省配置,可以解决某些启动问题,但是会覆盖当前设置,是否继续?",u"恢复到LiteBook的缺省设置",wx.YES_NO|wx.NO_DEFAULT)
if dlg.ShowModal()==wx.ID_YES:
try:
os.remove(os.environ['APPDATA'].decode(SYSENC)+u"\\litebook.ini")
os.remove(os.environ['APPDATA'].decode(SYSENC)+u"\\litebook_key.ini")
except:
pass
elif sys.argv[1]!='-full':
fname=sys.argv[1]
fname=os.path.abspath(fname)
else:
if len(sys.argv)>2:
fname=sys.argv[2]
fname=os.path.abspath(fname)
if fname!=None:
if not os.path.exists(fname):
dlg = wx.MessageDialog(None,fname+u' 不存在',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
sys.exit()
readConfigFile()
#create share_root if it doesn't exist
if not os.path.isdir(GlobalConfig['ShareRoot']):
os.makedirs(GlobalConfig['ShareRoot'])
readKeyConfig()
readPlugin()
if GlobalConfig['InstallDefaultConfig']:InstallDefaultConfig()
#wx.InitAllImageHandlers()
if fname != None:
fname = fname.decode(SYSENC) #convert to unicode
frame_1 = MyFrame(None,fname)
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,254
|
hujun-open/litebook
|
refs/heads/master
|
/UnRAR2/__init__.py
|
# Copyright (c) 2003-2005 Jimmy Retzlaff, 2008 Konstantin Yegupov
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
pyUnRAR2 is a ctypes based wrapper around the free UnRAR.dll.
It is an modified version of Jimmy Retzlaff's pyUnRAR - more simple,
stable and foolproof.
Notice that it has INCOMPATIBLE interface.
It enables reading and unpacking of archives created with the
RAR/WinRAR archivers. There is a low-level interface which is very
similar to the C interface provided by UnRAR. There is also a
higher level interface which makes some common operations easier.
"""
__version__ = '0.99.2'
try:
WindowsError
in_windows = True
except NameError:
in_windows = False
if in_windows:
from windows import RarFileImplementation
else:
from unix import RarFileImplementation
import fnmatch, time, weakref
class RarInfo(object):
"""Represents a file header in an archive. Don't instantiate directly.
Use only to obtain information about file.
YOU CANNOT EXTRACT FILE CONTENTS USING THIS OBJECT.
USE METHODS OF RarFile CLASS INSTEAD.
Properties:
index - index of file within the archive
filename - name of the file in the archive including path (if any)
datetime - file date/time as a struct_time suitable for time.strftime
isdir - True if the file is a directory
size - size in bytes of the uncompressed file
comment - comment associated with the file
Note - this is not currently intended to be a Python file-like object.
"""
def __init__(self, rarfile, data):
self.rarfile = weakref.proxy(rarfile)
self.index = data['index']
self.filename = data['filename']
self.isdir = data['isdir']
self.size = data['size']
self.datetime = data['datetime']
self.comment = data['comment']
def __str__(self):
try :
arcName = self.rarfile.archiveName
except ReferenceError:
arcName = "[ARCHIVE_NO_LONGER_LOADED]"
return '<RarInfo "%s" in "%s">' % (self.filename, arcName)
class RarFile(RarFileImplementation):
def __init__(self, archiveName, password=None):
"""Instantiate the archive.
archiveName is the name of the RAR file.
password is used to decrypt the files in the archive.
Properties:
comment - comment associated with the archive
>>> print RarFile('test.rar').comment
This is a test.
"""
self.archiveName = archiveName
RarFileImplementation.init(self, password)
def __del__(self):
self.destruct()
def infoiter(self):
"""Iterate over all the files in the archive, generating RarInfos.
>>> import os
>>> for fileInArchive in RarFile('test.rar').infoiter():
... print os.path.split(fileInArchive.filename)[-1],
... print fileInArchive.isdir,
... print fileInArchive.size,
... print fileInArchive.comment,
... print tuple(fileInArchive.datetime)[0:5],
... print time.strftime('%a, %d %b %Y %H:%M', fileInArchive.datetime)
test True 0 None (2003, 6, 30, 1, 59) Mon, 30 Jun 2003 01:59
test.txt False 20 None (2003, 6, 30, 2, 1) Mon, 30 Jun 2003 02:01
this.py False 1030 None (2002, 2, 8, 16, 47) Fri, 08 Feb 2002 16:47
"""
for params in RarFileImplementation.infoiter(self):
yield RarInfo(self, params)
def infolist(self):
"""Return a list of RarInfos, descripting the contents of the archive."""
return list(self.infoiter())
def read_files(self, condition='*'):
"""Read specific files from archive into memory.
If "condition" is a list of numbers, then return files which have those positions in infolist.
If "condition" is a string, then it is treated as a wildcard for names of files to extract.
If "condition" is a function, it is treated as a callback function, which accepts a RarInfo object
and returns boolean True (extract) or False (skip).
If "condition" is omitted, all files are returned.
Returns list of tuples (RarInfo info, str contents)
"""
checker = condition2checker(condition)
return RarFileImplementation.read_files(self, checker)
def extract(self, condition='*', path='.', withSubpath=True, overwrite=True):
"""Extract specific files from archive to disk.
If "condition" is a list of numbers, then extract files which have those positions in infolist.
If "condition" is a string, then it is treated as a wildcard for names of files to extract.
If "condition" is a function, it is treated as a callback function, which accepts a RarInfo object
and returns either boolean True (extract) or boolean False (skip).
DEPRECATED: If "condition" callback returns string (only supported for Windows) -
that string will be used as a new name to save the file under.
If "condition" is omitted, all files are extracted.
"path" is a directory to extract to
"withSubpath" flag denotes whether files are extracted with their full path in the archive.
"overwrite" flag denotes whether extracted files will overwrite old ones. Defaults to true.
Returns list of RarInfos for extracted files."""
checker = condition2checker(condition)
return RarFileImplementation.extract(self, checker, path, withSubpath, overwrite)
def condition2checker(condition):
"""Converts different condition types to callback"""
if type(condition) in [str, unicode]:
def smatcher(info):
if condition.find('[')<>-1 and condition.find(']')<>-1:
if info.filename==condition:return True
else:return False
else:
return fnmatch.fnmatch(info.filename, condition)
return smatcher
elif type(condition) in [list, tuple] and type(condition[0]) in [int, long]:
def imatcher(info):
return info.index in condition
return imatcher
elif callable(condition):
return condition
else:
raise TypeError
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,255
|
hujun-open/litebook
|
refs/heads/master
|
/keygrid.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This is a grid based class used to configure keymap
import wx
import wx.grid as gridlib
import string
# begin wxGlade: extracode
# end wxGlade
KeyMap = {
wx.WXK_BACK : "WXK_BACK",
wx.WXK_TAB : "WXK_TAB",
wx.WXK_RETURN : "WXK_RETURN",
wx.WXK_ESCAPE : "WXK_ESCAPE",
wx.WXK_SPACE : "WXK_SPACE",
wx.WXK_DELETE : "WXK_DELETE",
wx.WXK_START : "WXK_START",
wx.WXK_LBUTTON : "WXK_LBUTTON",
wx.WXK_RBUTTON : "WXK_RBUTTON",
wx.WXK_CANCEL : "WXK_CANCEL",
wx.WXK_MBUTTON : "WXK_MBUTTON",
wx.WXK_CLEAR : "WXK_CLEAR",
wx.WXK_SHIFT : "WXK_SHIFT",
wx.WXK_ALT : "WXK_ALT",
wx.WXK_CONTROL : "WXK_CONTROL",
wx.WXK_MENU : "WXK_MENU",
wx.WXK_PAUSE : "WXK_PAUSE",
wx.WXK_CAPITAL : "WXK_CAPITAL",
#wx.WXK_PRIOR : "WXK_PRIOR",
#wx.WXK_NEXT : "WXK_NEXT",
wx.WXK_END : "WXK_END",
wx.WXK_HOME : "WXK_HOME",
wx.WXK_LEFT : "WXK_LEFT",
wx.WXK_UP : "WXK_UP",
wx.WXK_RIGHT : "WXK_RIGHT",
wx.WXK_DOWN : "WXK_DOWN",
wx.WXK_SELECT : "WXK_SELECT",
wx.WXK_PRINT : "WXK_PRINT",
wx.WXK_EXECUTE : "WXK_EXECUTE",
wx.WXK_SNAPSHOT : "WXK_SNAPSHOT",
wx.WXK_INSERT : "WXK_INSERT",
wx.WXK_HELP : "WXK_HELP",
wx.WXK_NUMPAD0 : "WXK_NUMPAD0",
wx.WXK_NUMPAD1 : "WXK_NUMPAD1",
wx.WXK_NUMPAD2 : "WXK_NUMPAD2",
wx.WXK_NUMPAD3 : "WXK_NUMPAD3",
wx.WXK_NUMPAD4 : "WXK_NUMPAD4",
wx.WXK_NUMPAD5 : "WXK_NUMPAD5",
wx.WXK_NUMPAD6 : "WXK_NUMPAD6",
wx.WXK_NUMPAD7 : "WXK_NUMPAD7",
wx.WXK_NUMPAD8 : "WXK_NUMPAD8",
wx.WXK_NUMPAD9 : "WXK_NUMPAD9",
wx.WXK_MULTIPLY : "WXK_MULTIPLY",
wx.WXK_ADD : "WXK_ADD",
wx.WXK_SEPARATOR : "WXK_SEPARATOR",
wx.WXK_SUBTRACT : "WXK_SUBTRACT",
wx.WXK_DECIMAL : "WXK_DECIMAL",
wx.WXK_DIVIDE : "WXK_DIVIDE",
wx.WXK_F1 : "WXK_F1",
wx.WXK_F2 : "WXK_F2",
wx.WXK_F3 : "WXK_F3",
wx.WXK_F4 : "WXK_F4",
wx.WXK_F5 : "WXK_F5",
wx.WXK_F6 : "WXK_F6",
wx.WXK_F7 : "WXK_F7",
wx.WXK_F8 : "WXK_F8",
wx.WXK_F9 : "WXK_F9",
wx.WXK_F10 : "WXK_F10",
wx.WXK_F11 : "WXK_F11",
wx.WXK_F12 : "WXK_F12",
wx.WXK_F13 : "WXK_F13",
wx.WXK_F14 : "WXK_F14",
wx.WXK_F15 : "WXK_F15",
wx.WXK_F16 : "WXK_F16",
wx.WXK_F17 : "WXK_F17",
wx.WXK_F18 : "WXK_F18",
wx.WXK_F19 : "WXK_F19",
wx.WXK_F20 : "WXK_F20",
wx.WXK_F21 : "WXK_F21",
wx.WXK_F22 : "WXK_F22",
wx.WXK_F23 : "WXK_F23",
wx.WXK_F24 : "WXK_F24",
wx.WXK_NUMLOCK : "WXK_NUMLOCK",
wx.WXK_SCROLL : "WXK_SCROLL",
wx.WXK_PAGEUP : "WXK_PAGEUP",
wx.WXK_PAGEDOWN : "WXK_PAGEDOWN",
wx.WXK_NUMPAD_SPACE : "WXK_NUMPAD_SPACE",
wx.WXK_NUMPAD_TAB : "WXK_NUMPAD_TAB",
wx.WXK_NUMPAD_ENTER : "WXK_NUMPAD_ENTER",
wx.WXK_NUMPAD_F1 : "WXK_NUMPAD_F1",
wx.WXK_NUMPAD_F2 : "WXK_NUMPAD_F2",
wx.WXK_NUMPAD_F3 : "WXK_NUMPAD_F3",
wx.WXK_NUMPAD_F4 : "WXK_NUMPAD_F4",
wx.WXK_NUMPAD_HOME : "WXK_NUMPAD_HOME",
wx.WXK_NUMPAD_LEFT : "WXK_NUMPAD_LEFT",
wx.WXK_NUMPAD_UP : "WXK_NUMPAD_UP",
wx.WXK_NUMPAD_RIGHT : "WXK_NUMPAD_RIGHT",
wx.WXK_NUMPAD_DOWN : "WXK_NUMPAD_DOWN",
#wx.WXK_NUMPAD_PRIOR : "WXK_NUMPAD_PRIOR",
wx.WXK_NUMPAD_PAGEUP : "WXK_NUMPAD_PAGEUP",
#wx.WXK_NUMPAD_NEXT : "WXK_NUMPAD_NEXT",
wx.WXK_NUMPAD_PAGEDOWN : "WXK_NUMPAD_PAGEDOWN",
wx.WXK_NUMPAD_END : "WXK_NUMPAD_END",
wx.WXK_NUMPAD_BEGIN : "WXK_NUMPAD_BEGIN",
wx.WXK_NUMPAD_INSERT : "WXK_NUMPAD_INSERT",
wx.WXK_NUMPAD_DELETE : "WXK_NUMPAD_DELETE",
wx.WXK_NUMPAD_EQUAL : "WXK_NUMPAD_EQUAL",
wx.WXK_NUMPAD_MULTIPLY : "WXK_NUMPAD_MULTIPLY",
wx.WXK_NUMPAD_ADD : "WXK_NUMPAD_ADD",
wx.WXK_NUMPAD_SEPARATOR : "WXK_NUMPAD_SEPARATOR",
wx.WXK_NUMPAD_SUBTRACT : "WXK_NUMPAD_SUBTRACT",
wx.WXK_NUMPAD_DECIMAL : "WXK_NUMPAD_DECIMAL",
wx.WXK_NUMPAD_DIVIDE : "WXK_NUMPAD_DIVIDE",
wx.WXK_WINDOWS_LEFT : "WXK_WINDOWS_LEFT",
wx.WXK_WINDOWS_RIGHT : "WXK_WINDOWS_RIGHT",
wx.WXK_WINDOWS_MENU : "WXK_WINDOWS_MENU",
wx.WXK_COMMAND : "WXK_COMMAND",
wx.WXK_SPECIAL1 : "WXK_SPECIAL1",
wx.WXK_SPECIAL2 : "WXK_SPECIAL2",
wx.WXK_SPECIAL3 : "WXK_SPECIAL3",
wx.WXK_SPECIAL4 : "WXK_SPECIAL4",
wx.WXK_SPECIAL5 : "WXK_SPECIAL5",
wx.WXK_SPECIAL6 : "WXK_SPECIAL6",
wx.WXK_SPECIAL7 : "WXK_SPECIAL7",
wx.WXK_SPECIAL8 : "WXK_SPECIAL8",
wx.WXK_SPECIAL9 : "WXK_SPECIAL9",
wx.WXK_SPECIAL10 : "WXK_SPECIAL10",
wx.WXK_SPECIAL11 : "WXK_SPECIAL11",
wx.WXK_SPECIAL12 : "WXK_SPECIAL12",
wx.WXK_SPECIAL13 : "WXK_SPECIAL13",
wx.WXK_SPECIAL14 : "WXK_SPECIAL14",
wx.WXK_SPECIAL15 : "WXK_SPECIAL15",
wx.WXK_SPECIAL16 : "WXK_SPECIAL16",
wx.WXK_SPECIAL17 : "WXK_SPECIAL17",
wx.WXK_SPECIAL18 : "WXK_SPECIAL18",
wx.WXK_SPECIAL19 : "WXK_SPECIAL19",
wx.WXK_SPECIAL2 : "WXK_SPECIAL2",
}
RKeyMap= {
"WXK_BACK":wx.WXK_BACK,
"WXK_TAB":wx.WXK_TAB,
"WXK_RETURN":wx.WXK_RETURN,
"WXK_ESCAPE":wx.WXK_ESCAPE,
"WXK_SPACE":wx.WXK_SPACE,
"WXK_DELETE":wx.WXK_DELETE,
"WXK_START":wx.WXK_START,
"WXK_LBUTTON":wx.WXK_LBUTTON,
"WXK_RBUTTON":wx.WXK_RBUTTON,
"WXK_CANCEL":wx.WXK_CANCEL,
"WXK_MBUTTON":wx.WXK_MBUTTON,
"WXK_CLEAR":wx.WXK_CLEAR,
"WXK_SHIFT":wx.WXK_SHIFT,
"WXK_ALT":wx.WXK_ALT,
"WXK_CONTROL":wx.WXK_CONTROL,
"WXK_MENU":wx.WXK_MENU,
"WXK_PAUSE":wx.WXK_PAUSE,
"WXK_CAPITAL":wx.WXK_CAPITAL,
# "WXK_PRIOR":wx.WXK_PRIOR,
# "WXK_NEXT":wx.WXK_NEXT,
"WXK_END":wx.WXK_END,
"WXK_HOME":wx.WXK_HOME,
"WXK_LEFT":wx.WXK_LEFT,
"WXK_UP":wx.WXK_UP,
"WXK_RIGHT":wx.WXK_RIGHT,
"WXK_DOWN":wx.WXK_DOWN,
"WXK_SELECT":wx.WXK_SELECT,
"WXK_PRINT":wx.WXK_PRINT,
"WXK_EXECUTE":wx.WXK_EXECUTE,
"WXK_SNAPSHOT":wx.WXK_SNAPSHOT,
"WXK_INSERT":wx.WXK_INSERT,
"WXK_HELP":wx.WXK_HELP,
"WXK_NUMPAD0":wx.WXK_NUMPAD0,
"WXK_NUMPAD1":wx.WXK_NUMPAD1,
"WXK_NUMPAD2":wx.WXK_NUMPAD2,
"WXK_NUMPAD3":wx.WXK_NUMPAD3,
"WXK_NUMPAD4":wx.WXK_NUMPAD4,
"WXK_NUMPAD5":wx.WXK_NUMPAD5,
"WXK_NUMPAD6":wx.WXK_NUMPAD6,
"WXK_NUMPAD7":wx.WXK_NUMPAD7,
"WXK_NUMPAD8":wx.WXK_NUMPAD8,
"WXK_NUMPAD9":wx.WXK_NUMPAD9,
"WXK_MULTIPLY":wx.WXK_MULTIPLY,
"WXK_ADD":wx.WXK_ADD,
"WXK_SEPARATOR":wx.WXK_SEPARATOR,
"WXK_SUBTRACT":wx.WXK_SUBTRACT,
"WXK_DECIMAL":wx.WXK_DECIMAL,
"WXK_DIVIDE":wx.WXK_DIVIDE,
"WXK_F1":wx.WXK_F1,
"WXK_F2":wx.WXK_F2,
"WXK_F3":wx.WXK_F3,
"WXK_F4":wx.WXK_F4,
"WXK_F5":wx.WXK_F5,
"WXK_F6":wx.WXK_F6,
"WXK_F7":wx.WXK_F7,
"WXK_F8":wx.WXK_F8,
"WXK_F9":wx.WXK_F9,
"WXK_F10":wx.WXK_F10,
"WXK_F11":wx.WXK_F11,
"WXK_F12":wx.WXK_F12,
"WXK_F13":wx.WXK_F13,
"WXK_F14":wx.WXK_F14,
"WXK_F15":wx.WXK_F15,
"WXK_F16":wx.WXK_F16,
"WXK_F17":wx.WXK_F17,
"WXK_F18":wx.WXK_F18,
"WXK_F19":wx.WXK_F19,
"WXK_F20":wx.WXK_F20,
"WXK_F21":wx.WXK_F21,
"WXK_F22":wx.WXK_F22,
"WXK_F23":wx.WXK_F23,
"WXK_F24":wx.WXK_F24,
"WXK_NUMLOCK":wx.WXK_NUMLOCK,
"WXK_SCROLL":wx.WXK_SCROLL,
"WXK_PAGEUP":wx.WXK_PAGEUP,
"WXK_PAGEDOWN":wx.WXK_PAGEDOWN,
"WXK_NUMPAD_SPACE":wx.WXK_NUMPAD_SPACE,
"WXK_NUMPAD_TAB":wx.WXK_NUMPAD_TAB,
"WXK_NUMPAD_ENTER":wx.WXK_NUMPAD_ENTER,
"WXK_NUMPAD_F1":wx.WXK_NUMPAD_F1,
"WXK_NUMPAD_F2":wx.WXK_NUMPAD_F2,
"WXK_NUMPAD_F3":wx.WXK_NUMPAD_F3,
"WXK_NUMPAD_F4":wx.WXK_NUMPAD_F4,
"WXK_NUMPAD_HOME":wx.WXK_NUMPAD_HOME,
"WXK_NUMPAD_LEFT":wx.WXK_NUMPAD_LEFT,
"WXK_NUMPAD_UP":wx.WXK_NUMPAD_UP,
"WXK_NUMPAD_RIGHT":wx.WXK_NUMPAD_RIGHT,
"WXK_NUMPAD_DOWN":wx.WXK_NUMPAD_DOWN,
# "WXK_NUMPAD_PRIOR":wx.WXK_NUMPAD_PRIOR,
"WXK_NUMPAD_PAGEUP":wx.WXK_NUMPAD_PAGEUP,
# "WXK_NUMPAD_NEXT":wx.WXK_NUMPAD_NEXT,
"WXK_NUMPAD_PAGEDOWN":wx.WXK_NUMPAD_PAGEDOWN,
"WXK_NUMPAD_END":wx.WXK_NUMPAD_END,
"WXK_NUMPAD_BEGIN":wx.WXK_NUMPAD_BEGIN,
"WXK_NUMPAD_INSERT":wx.WXK_NUMPAD_INSERT,
"WXK_NUMPAD_DELETE":wx.WXK_NUMPAD_DELETE,
"WXK_NUMPAD_EQUAL":wx.WXK_NUMPAD_EQUAL,
"WXK_NUMPAD_MULTIPLY":wx.WXK_NUMPAD_MULTIPLY,
"WXK_NUMPAD_ADD":wx.WXK_NUMPAD_ADD,
"WXK_NUMPAD_SEPARATOR":wx.WXK_NUMPAD_SEPARATOR,
"WXK_NUMPAD_SUBTRACT":wx.WXK_NUMPAD_SUBTRACT,
"WXK_NUMPAD_DECIMAL":wx.WXK_NUMPAD_DECIMAL,
"WXK_NUMPAD_DIVIDE":wx.WXK_NUMPAD_DIVIDE,
"WXK_WINDOWS_LEFT":wx.WXK_WINDOWS_LEFT,
"WXK_WINDOWS_RIGHT":wx.WXK_WINDOWS_RIGHT,
"WXK_WINDOWS_MENU":wx.WXK_WINDOWS_MENU,
"WXK_COMMAND":wx.WXK_COMMAND,
"WXK_SPECIAL1":wx.WXK_SPECIAL1,
"WXK_SPECIAL2":wx.WXK_SPECIAL2,
"WXK_SPECIAL3":wx.WXK_SPECIAL3,
"WXK_SPECIAL4":wx.WXK_SPECIAL4,
"WXK_SPECIAL5":wx.WXK_SPECIAL5,
"WXK_SPECIAL6":wx.WXK_SPECIAL6,
"WXK_SPECIAL7":wx.WXK_SPECIAL7,
"WXK_SPECIAL8":wx.WXK_SPECIAL8,
"WXK_SPECIAL9":wx.WXK_SPECIAL9,
"WXK_SPECIAL10":wx.WXK_SPECIAL10,
"WXK_SPECIAL11":wx.WXK_SPECIAL11,
"WXK_SPECIAL12":wx.WXK_SPECIAL12,
"WXK_SPECIAL13":wx.WXK_SPECIAL13,
"WXK_SPECIAL14":wx.WXK_SPECIAL14,
"WXK_SPECIAL15":wx.WXK_SPECIAL15,
"WXK_SPECIAL16":wx.WXK_SPECIAL16,
"WXK_SPECIAL17":wx.WXK_SPECIAL17,
"WXK_SPECIAL18":wx.WXK_SPECIAL18,
"WXK_SPECIAL19":wx.WXK_SPECIAL19,
"WXK_SPECIAL2":wx.WXK_SPECIAL2,
}
#func_list=[u'向上翻行',u'向下翻行',u'向上翻页',u'向下翻页',u'向上翻半页',u'向下翻半页',u'前进10%',u'后退10%',u'前进1%',u'后退1%',u'跳到首页',u'跳到结尾',u'文件列表',u'打开文件',u'另存为',u'关闭',u'上一个文件',u'下一个文件',u'搜索小说网站',u'搜索LTBNET',u'重新载入插件',u'选项',u'退出',u'拷贝',u'查找',u'查找下一个',u'查找上一个',u'替换',u'纸张显示模式',u'书本显示模式',u'竖排书本显示模式',u'显示工具栏',u'显示目录',u'全屏显示',u'显示文件侧边栏',u'自动翻页',u'智能分段',u'添加到收藏夹',u'整理收藏夹',u'简明帮助',u'版本更新内容',u'检查更新',u'关于',u'过滤HTML标记',u'切换为简体字',u'切换为繁体字',u'显示进度条',u'增大字体',u'减小字体',u'清空缓存',u'最小化',u'生成EPUB文件',u'启用WEB服务器',u'显示章节侧边栏',u'缩小工具栏',u'放大工具栏']
LB2_func_list={
u'向上翻行':'----+WXK_UP',
u'向下翻行':'----+WXK_DOWN',
u'向上翻页':'----+WXK_PAGEUP',
u'向上翻页':'----+WXK_LEFT',
u'向下翻页':'----+WXK_PAGEDOWN',
u'向下翻页':'----+WXK_RIGHT',
u'向下翻页':'----+WXK_SPACE',
u'向上翻半页':'----+","',
u'向下翻半页':'----+"."',
u'后退10%':'----+"["',
u'前进10%':'----+"]"',
u'后退1%':'----+"9"',
u'前进1%':'----+"0"',
u'跳到首页':'----+WXK_HOME',
u'跳到结尾':'----+WXK_END',
u'文件列表':'C---+"O"',
u'打开文件':'C---+"P"',
u'另存为':'C---+"S"',
u'关闭':'C---+"Z"',
u'上一个文件':'C---+"["',
u'下一个文件':'C---+"]"',
u'搜索小说网站':'-A--+"C"',
u'搜索LTBNET':'C---+"G"',
u'下载管理器':'C---+"D"',
u'重新载入插件':'C---+"R"',
u'选项':'-A--+"O"',
u'退出':'-A--+"X"',
u'拷贝':'C---+"C"',
u'查找':'C---+"F"',
u'替换':'C---+"H"',
u'查找下一个':'----+WXK_F3',
u'查找上一个':'----+WXK_F4',
u'纸张显示模式':'-A--+"M"',
u'书本显示模式':'-A--+"B"',
u'竖排书本显示模式':'-A--+"N"',
u'显示工具栏':'C---+"T"',
u'缩小工具栏':'C---+"-"',
u'放大工具栏':'C---+"="',
u'显示目录':'C---+"U"',
u'全屏显示':'C---+"I"',
u'显示文件侧边栏':'-A--+"D"',
u'显示章节侧边栏':'-A--+"J"',
u'自动翻页':'-A--+"T"',
u'智能分段':'-A--+"P"',
u'添加到收藏夹':'C---+"D"',
u'整理收藏夹':'C---+"M"',
u'简明帮助':'----+WXK_F1',
u'版本更新内容':'----+WXK_F2',
u'检查更新':'----+WXK_F5',
u'关于':'----+WXK_F6',
u'过滤HTML标记':'----+WXK_F9',
u'切换为简体字':'----+WXK_F7',
u'切换为繁体字':'----+WXK_F8',
u'显示进度条':'----+"Z"',
u'增大字体':'----+"="',
u'减小字体':'----+"-"',
u'清空缓存':'CA--+"Q"',
u'最小化':'----+WXK_ESCAPE',
u'生成EPUB文件':'C---+"E"',
u'启用WEB服务器':'-A--+"W"',
u'检测端口是否开启':'C---+"Q"',
u'使用UPNP添加端口映射':'C---+"I"',
u'管理订阅':'C---+"Y"',
u'WEB下载管理器':'C---+"W"',
u'跳转历史':'C---+"A"',
}
func_list = LB2_func_list.keys()
def str2menu(keystr):
mstr=' \t'
mod,keysub=keystr.split('+',1)
if mod[0]<>'-':mstr+='CTRL+'
if mod[1]<>'-':mstr+='ALT+'
if mod[2]<>'-':mstr+='SHIFT+'
if mod[3]<>'-':mstr+='META+'
if keysub[0]=='"':
mstr+=keysub[1]
else:
mstr+=keysub[4:]
return mstr
def str2key(keystr):
rkey={}
rkey['ALT']=False
rkey['CTRL']=False
rkey['SHIFT']=False
rkey['META']=False
rkey['KEY']=0
mod,keysub=keystr.split('+',1)
if mod[0]<>'-':rkey['CTRL']=True
if mod[1]<>'-':rkey['ALT']=True
if mod[2]<>'-':rkey['SHIFT']=True
if mod[3]<>'-':rkey['META']=True
if keysub[0]=='"':
rkey['KEY']=ord(keysub[1])
else:
rkey['KEY']=RKeyMap[keysub]
return rkey
def key2str(evt):
global KeyMap
keycode=evt.GetKeyCode()
modifiers = ""
for mod, ch in [(evt.ControlDown(), 'C'),
(evt.AltDown(), 'A'),
(evt.ShiftDown(), 'S'),
(evt.MetaDown(), 'M')]:
if mod:
modifiers += ch
else:
modifiers += '-'
keyname = KeyMap.get(keycode, None)
if keyname is None:
if keycode < 256:
if keycode == 0:
keyname = "NUL"
elif keycode < 27:
keyname = "\"%s\"" % chr(ord('A') + keycode-1).upper()
else:
keyname = "\"%s\"" % chr(keycode).upper()
else:
keyname = "(%s)" % keycode
return modifiers+"+"+keyname
class KeyConfigGrid(gridlib.Grid):
def __init__(self,parent):
gridlib.Grid.__init__(self,parent,name='OptionGrid')
self.curCol=None
self.curRow=None
self.startKey=False
self.startKeyCell=''
self.tRow=None
self.CreateGrid(0, 2)
self.SetColLabelValue(0, u"功能(双击修改)")
self.SetColLabelValue(1, u"按键(双击修改)")
# self.Bind(wx.EVT_CHAR,self.OnChar)
self.GetGridWindow().Bind(wx.EVT_CHAR,self.OnChar)
self.Bind(wx.EVT_KEY_UP,self.OnChar)
self.Bind(gridlib.EVT_GRID_CELL_LEFT_DCLICK,self.OnDClick)
self.Bind(gridlib.EVT_GRID_CELL_LEFT_CLICK,self.OnLClick)
self.Bind(gridlib.EVT_GRID_CELL_RIGHT_CLICK, self.Popmenu)
def OnLClick(self,evt):
if self.curCol<>None and self.startKey:
self.SetCellValue(self.curRow,self.curCol,self.startKeyCell)
evt.Skip()
## else:
## evt.Skip()
def OnDClick(self,evt):
col=evt.GetCol()
if self.curCol<>None and self.startKey:
self.SetCellValue(self.curRow,self.curCol,self.startKeyCell)
if col<>1:
evt.Skip()
return
r=evt.GetRow()
self.curCol=col
self.curRow=r
self.startKeyCell=self.GetCellValue(r,1)
self.SetCellValue(r,1,u'请按键...')
self.startKey=True
def Popmenu(self,evt):
if not hasattr(self,"popupID1"):
self.popupID1=wx.NewId()
self.popupID2=wx.NewId()
self.Bind(wx.EVT_MENU, self.OnDel, id=self.popupID1)
self.Bind(wx.EVT_MENU, self.OnAdd, id=self.popupID2)
self.tRow=evt.GetRow()
menu = wx.Menu()
item = wx.MenuItem(menu, self.popupID1,u"删除本行")
menu.AppendItem(item)
item = wx.MenuItem(menu, self.popupID2,u"新增一行")
menu.AppendItem(item)
self.PopupMenu(menu)
#menu.Destroy()
def OnDel(self,evt):
self.DeleteRows(self.tRow)
if self.GetNumberRows()==0:self.OnAdd(None)
def OnAdd(self,evt):
self.AppendLine(u'向下翻页','')
r=self.GetNumberRows()
self.SelectRow(r-1)
def OnChar(self,evt):
global key2str,str2key
if not self.startKey:
evt.Skip()
return
r=key2str(evt)
key=str2key(r)['KEY']
n=self.GetNumberRows()
i=0
while i<n:
if i<>self.curRow:
if self.GetCellValue(i,1)==r:
func_name=self.GetCellValue(i,0)
dlg = wx.MessageDialog(None, u'"'+func_name+u'" 已经使用了这个按键,请换一个',u"错误!",wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
self.SetCellValue(self.curRow,self.curCol,self.startKeyCell)
self.startKey=False
return
i+=1
self.SetCellValue(self.curRow,self.curCol,r)
evt.Skip(False)
evt.StopPropagation()
self.startKey=False
#self.AppendLine(u'上一个文件',r)
def AppendLine(self,func,key):
global func_list
if func not in func_list:return False
self.AppendRows()
r=self.GetNumberRows()
self.SetCellEditor(r-1,0,gridlib.GridCellChoiceEditor(func_list))
# cedit=KeyEditor()
# self.SetCellEditor(r-1,1,cedit)
# self.SetCellEditor(r-1,1,mycell())
self.SetCellValue(r-1,0,func)
self.SetCellValue(r-1,1,key)
self.SetReadOnly(r-1,1)
self.MakeCellVisible(r-1,0)
def Load(self,klist):
r=self.GetNumberRows()
if r>0:self.DeleteRows(0,r)
i=1
tl=len(klist)
while i<tl:
self.AppendLine(klist[i][0],klist[i][1])
i+=1
if tl==0:self.OnAdd(None)
if r==0:self.AutoSize()
self.MakeCellVisible(0,0)
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.grid_1 = KeyConfigGrid(self)
self.__set_properties()
self.__do_layout()
# end wxGlade
def __set_properties(self):
# begin wxGlade: MyFrame.__set_properties
self.SetTitle("frame_1")
self.grid_1.AppendLine(u'上一个文件','1')
self.grid_1.AppendLine(u'上一个文件','2')
self.grid_1.AppendLine(u'上一个文件','3')
# end wxGlade
def __do_layout(self):
# begin wxGlade: MyFrame.__do_layout
sizer_26 = wx.BoxSizer(wx.VERTICAL)
sizer_26.Add(self.grid_1, 1, wx.EXPAND, 0)
self.SetSizer(sizer_26)
sizer_26.Fit(self)
self.Layout()
# end wxGlade
# end of class MyFrame
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = MyFrame(None, -1, "")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,256
|
hujun-open/litebook
|
refs/heads/master
|
/UnRAR2/test_UnRAR2.py
|
import os, sys
import UnRAR2
from UnRAR2.rar_exceptions import *
def cleanup(dir='test'):
for path, dirs, files in os.walk(dir):
for fn in files:
os.remove(os.path.join(path, fn))
for dir in dirs:
os.removedirs(os.path.join(path, dir))
# reuse RarArchive object, en
cleanup()
rarc = UnRAR2.RarFile('test.rar')
rarc.infolist()
for info in rarc.infoiter():
saveinfo = info
assert (str(info)=="""<RarInfo "test" in "test.rar">""")
break
rarc.extract()
assert os.path.exists('test'+os.sep+'test.txt')
assert os.path.exists('test'+os.sep+'this.py')
del rarc
assert (str(saveinfo)=="""<RarInfo "test" in "[ARCHIVE_NO_LONGER_LOADED]">""")
cleanup()
# extract all the files in test.rar
cleanup()
UnRAR2.RarFile('test.rar').extract()
assert os.path.exists('test'+os.sep+'test.txt')
assert os.path.exists('test'+os.sep+'this.py')
cleanup()
# extract all the files in test.rar matching the wildcard *.txt
cleanup()
UnRAR2.RarFile('test.rar').extract('*.txt')
assert os.path.exists('test'+os.sep+'test.txt')
assert not os.path.exists('test'+os.sep+'this.py')
cleanup()
# check the name and size of each file, extracting small ones
cleanup()
archive = UnRAR2.RarFile('test.rar')
assert archive.comment == 'This is a test.'
archive.extract(lambda rarinfo: rarinfo.size <= 1024)
for rarinfo in archive.infoiter():
if rarinfo.size <= 1024 and not rarinfo.isdir:
assert rarinfo.size == os.stat(rarinfo.filename).st_size
assert file('test'+os.sep+'test.txt', 'rt').read() == 'This is only a test.'
assert not os.path.exists('test'+os.sep+'this.py')
cleanup()
# extract this.py, overriding it's destination
cleanup('test2')
archive = UnRAR2.RarFile('test.rar')
archive.extract('*.py', 'test2', False)
assert os.path.exists('test2'+os.sep+'this.py')
cleanup('test2')
# extract test.txt to memory
cleanup()
archive = UnRAR2.RarFile('test.rar')
entries = UnRAR2.RarFile('test.rar').read_files('*test.txt')
assert len(entries)==1
assert entries[0][0].filename.endswith('test.txt')
assert entries[0][1]=='This is only a test.'
# extract all the files in test.rar with overwriting
cleanup()
fo = open('test'+os.sep+'test.txt',"wt")
fo.write("blah")
fo.close()
UnRAR2.RarFile('test.rar').extract('*.txt')
assert open('test'+os.sep+'test.txt',"rt").read()!="blah"
cleanup()
# extract all the files in test.rar without overwriting
cleanup()
fo = open('test'+os.sep+'test.txt',"wt")
fo.write("blahblah")
fo.close()
UnRAR2.RarFile('test.rar').extract('*.txt', overwrite = False)
assert open('test'+os.sep+'test.txt',"rt").read()=="blahblah"
cleanup()
# list big file in an archive
list(UnRAR2.RarFile('test_nulls.rar').infoiter())
# extract files from an archive with protected files
cleanup()
UnRAR2.RarFile('test_protected_files.rar', password="protected").extract()
assert os.path.exists('test'+os.sep+'top_secret_xxx_file.txt')
cleanup()
errored = False
try:
UnRAR2.RarFile('test_protected_files.rar', password="proteqted").extract()
except IncorrectRARPassword:
errored = True
assert not os.path.exists('test'+os.sep+'top_secret_xxx_file.txt')
assert errored
cleanup()
# extract files from an archive with protected headers
cleanup()
UnRAR2.RarFile('test_protected_headers.rar', password="secret").extract()
assert os.path.exists('test'+os.sep+'top_secret_xxx_file.txt')
cleanup()
errored = False
try:
UnRAR2.RarFile('test_protected_headers.rar', password="seqret").extract()
except IncorrectRARPassword:
errored = True
assert not os.path.exists('test'+os.sep+'top_secret_xxx_file.txt')
assert errored
cleanup()
# make sure docstring examples are working
import doctest
doctest.testmod(UnRAR2)
# update documentation
import pydoc
pydoc.writedoc(UnRAR2)
# cleanup
try:
os.remove('__init__.pyc')
except:
pass
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,257
|
hujun-open/litebook
|
refs/heads/master
|
/liteview.py
|
#!/usr/bin/env py32
# -*- coding: utf-8 -*-
#
#
u"""LiteView is a read-only optimized wxpython text control, which provides
following features:
- 3 show modes: paper/book/vbook
- configurable: background(picture)/font/underline/margin
- render speed is almost independent of file size
Author: Hu Jun
update on 12/24/2010
- add scroll-line support
- fix a bug that cause 1.5 character over the right edge of line
Updated: 11/19/2010
- first beta,all major feature implemented
"""
#
#update on 2010.12.26
# fix a bug of breakline
#
#
#update on 2010.12.2
# fix a bug of resizing not working under linux
#
import platform
import sys
MYOS = platform.system()
if MYOS != 'Linux' and MYOS != 'Darwin' and MYOS != 'Windows':
print "This version of litebook only support Linux and MAC OSX"
sys.exit(1)
import wx
import re
import time
import os
def cur_file_dir():
#获取脚本路径
global MYOS
if MYOS == 'Linux':
path = sys.path[0]
else:
path = sys.argv[0]
if isinstance(path,str):
path=path.decode('utf-8')
#判断为脚本文件还是py2exe编译后的文件,如果是脚本文件,则返回的是脚本的目录,如果是编译后的文件,则返回的是编译后的文件路径
if os.path.isdir(path):
return path
elif os.path.isfile(path):
return os.path.dirname(path)
#---------------------------------------------------------------------------
class LiteView(wx.ScrolledWindow):
u"""LiteView,一个看书的wxpython文本控件,具备如下特性:
-只读
-支持 背景(图片)/行间距/下划线/页边距/字体 等可设置
-支持三种不同的显示模式(纸张/书本/竖排书本)
-支持文字选择和拷贝(鼠标右键单击拷贝)
"""
def __init__(self, parent, id = -1, bg_img=None):
u"""
bg_img: background image, can be bitmap obj or a string of filepath
"""
sdc=wx.ScreenDC()
wx.ScrolledWindow.__init__(self, parent, id, (0, 0), size=sdc.GetSize(), style=wx.SUNKEN_BORDER|wx.CLIP_CHILDREN)
if platform.system()=='Linux': #this is to fix resize problem under linux
self.SetMinSize((300,300))
else:
self.SetMinSize((150,150))
#初始化一些设置
self.TextBackground='white'
self.SetBackgroundColour(self.TextBackground)
self.pagemargin=50
self.bookmargin=50
self.vbookmargin=50
self.centralmargin=20
self.linespace=5
self.vlinespace=15
self.vbookpunc=True #是否在竖排书本模式下显示标点
self.Value=u""
self.ValueCharCount=0
self.under_line=True
self.under_line_color="GREY"
self.under_line_style=wx.DOT
self.curPageTextList=[]
self.bg_buff=None
self.newbmp=None
self.newnewbmp=None
self.bg_img_path=None
self.SetImgBackground(bg_img)
self.bg_style='tile'
self.show_mode='paper'
self.buffer_bak=None
self.TextForeground='black'
#render direction, used for self.GetHitPos()
self.RenderDirection=1
#defaul selection color
self.DefaultSelectionColor=wx.Colour(255, 0, 0,128)
#setup the default font
self.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, ""))
self.current_pos=0
self.start_pos=0
self.SelectedRange=[0,0]
# Initialize the buffer bitmap. No real DC is needed at this point.
self.buffer=None
# Initialize the mouse dragging value
self.LastMousePos=None
self.FirstMousePos=None
self.pos_list=[]
self.MaxPosEntry=20
#绑定事件处理
## self.Bind(wx.EVT_SCROLLWIN,self.OnScroll)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_CHAR,self.OnChar)
self.Bind(wx.EVT_SIZE,self.OnResize)
self.Bind(wx.EVT_LEFT_DOWN,self.OnMouseDrag)
self.Bind(wx.EVT_LEFT_UP,self.OnMouseDrag)
self.Bind(wx.EVT_MOTION,self.OnMouseDrag)
self.Bind(wx.EVT_LEFT_DOWN,self.MouseClick)
#self.Bind(wx.EVT_RIGHT_UP,self.OnMouseDrag)
def getPosList(self):
return self.pos_list
def updatePosList(self,newpos):
if len(self.pos_list)>0:
if abs(self.pos_list[-1:][0]-newpos)<=50:return
if len(self.pos_list)>=self.MaxPosEntry:
self.pos_list.pop(0)
self.pos_list.append(newpos)
def MouseClick(self,evt):
self.SetFocus()
evt.Skip()
def GetHitPos(self,pos):
"""返回坐标所在字在self.Value中的[index,字的坐标]"""
r={}
dc=wx.MemoryDC()
dc.SelectObject(wx.EmptyBitmap(1, 1))#this is needed on MAC OSX
dc.SetFont(self.GetFont())
ch_h=dc.GetCharHeight()
ch_w=dc.GetTextExtent(u'我')[0]
if self.show_mode=='paper':
line=pos[1]/(self.linespace+ch_h)
tlen=len(self.curPageTextList)
if tlen<=0: return None
if line>=tlen:line=tlen-1
pos_list=dc.GetPartialTextExtents(self.curPageTextList[line][0])
i=0
tlen=pos[0]-self.pagemargin
while i<len(pos_list):
if pos_list[i]>tlen:break
else:
i+=1
if i>=len(self.curPageTextList[line][0]):
i=len(self.curPageTextList[line][0])
m=0
delta=0
while m<line:
delta+=len(self.curPageTextList[m][0])+self.curPageTextList[m][1]
m+=1
delta+=i
if len(self.curPageTextList[line][0])==0:
x=self.pagemargin
else:
x=self.pagemargin+dc.GetTextExtent(self.curPageTextList[line][0][:i])[0]
## if self.RenderDirection==1 or self.start_pos==0:
## y=(ch_h+self.linespace)*line
## else:
## y=(ch_h+self.linespace)*line+1.5*self.linespace
y=self.curPageTextList[line][2]
r['index']=self.start_pos+delta
r['pos']=(x,y)
r['line']=line
r['row']=i
return r
elif self.show_mode=='book':
if self.RenderDirection==1:
if pos[0]<=self.maxWidth/2:
line=pos[1]/(self.linespace+ch_h)
tlen=pos[0]-self.bookmargin
else:
line=pos[1]/(self.linespace+ch_h)+len(self.curPageTextList)/2
tlen=pos[0]-self.centralmargin-self.maxWidth/2
else:
if pos[0]<=self.maxWidth/2:
line=self.blockline-((self.maxHeight-pos[1])/(self.linespace+ch_h))-1
tlen=pos[0]-self.bookmargin
else:
line=self.blockline-((self.maxHeight-pos[1])/(self.linespace+ch_h))-1+len(self.curPageTextList)/2
tlen=pos[0]-self.centralmargin-self.maxWidth/2
if line>=len(self.curPageTextList):line=len(self.curPageTextList)-1
pos_list=dc.GetPartialTextExtents(self.curPageTextList[line][0])
i=0
while i<len(pos_list):
if pos_list[i]>tlen:break
else:
i+=1
if i>=len(self.curPageTextList[line][0]):
i=len(self.curPageTextList[line][0])
m=0
delta=0
while m<line:
delta+=len(self.curPageTextList[m][0])+self.curPageTextList[m][1]
m+=1
delta+=i
if pos[0]<=self.maxWidth/2:
if len(self.curPageTextList[line][0])==0:
x=self.bookmargin
else:
x=self.bookmargin+dc.GetTextExtent(self.curPageTextList[line][0][:i])[0]
## if self.RenderDirection==1 or self.start_pos==0:
## y=(ch_h+self.linespace)*line
## else:
## y=(ch_h+self.linespace)*line+self.linespace*1.5
else:
if len(self.curPageTextList[line][0])==0:
x=self.centralmargin+self.maxWidth/2
else:
x=self.centralmargin+self.maxWidth/2+dc.GetTextExtent(self.curPageTextList[line][0][:i])[0]
## if self.RenderDirection==1 or self.start_pos==0:
## y=(ch_h+self.linespace)*(line-len(self.curPageTextList)/2)
## else:
## y=(ch_h+self.linespace)*(line-len(self.curPageTextList)/2)+self.linespace*1.5
y=self.curPageTextList[line][2]
r['index']=self.start_pos+delta
r['pos']=(x,y)
r['line']=line
r['row']=i
return r
elif self.show_mode=='vbook':
## if self.RenderDirection==1:
newwidth=self.maxWidth/2-self.vbookmargin-self.centralmargin
newheight=self.maxHeight-2*self.vbookmargin
self.blockline=newwidth/(ch_w+self.vlinespace)
if pos[0]>self.maxWidth/2:
line=(self.maxWidth-self.vbookmargin-pos[0])/(ch_w+self.vlinespace)+1
else:
line=(self.maxWidth/2-self.centralmargin-2*ch_w-pos[0])/(ch_w+self.vlinespace)+2+self.blockline
if line>=len(self.curPageTextList):line=len(self.curPageTextList)-1
tlen=pos[1]-self.vbookmargin
if tlen<0:tlen=0
ti=tlen/(ch_h+2)
if ti>=len(self.curPageTextList[line][0]):ti=len(self.curPageTextList[line][0])
m=0
delta=0
while m<line:
delta+=len(self.curPageTextList[m][0])+self.curPageTextList[m][1]
m+=1
delta+=ti
m=0
y=ti*(ch_h+2)+self.vbookmargin
if line<=self.blockline:
x=self.maxWidth-self.vbookmargin-line*(ch_w+self.vlinespace/2+self.vlinespace/2)-self.vlinespace/3
else:
x=(self.maxWidth/2)-(self.centralmargin/2)-(line-self.blockline)*(ch_w+self.vlinespace/2+self.vlinespace/2)-ch_w
## else:
## #if direction == -1
## none
r['index']=self.start_pos+delta
r['pos']=(x,y)
r['line']=line
r['row']=ti
v1=r['index']
return r
def GenSelectColor(self):
"""返回选择文字时候被选择文字的颜色"""
cf=wx.NamedColour(self.TextForeground)
oldr=cf.Red()
oldg=cf.Green()
oldb=cf.Blue()
if self.bg_img==None:
cb=wx.NamedColour(self.TextBackground)
bgr=cb.Red()
bgg=cb.Green()
bgb=cb.Blue()
newr=(510-oldr-bgr)/2
newg=(510-oldg-bgg)/2
newb=(510-oldb-bgb)/2
if oldr==0: oldr=1
if oldg==0: oldg=1
if oldb==0: oldb=1
if bgr==0:bgr=1
if bgg==0:bgg=1
if bgb==0:bgb=1
if (float(oldg)/float(oldr)<0.5 and float(oldb)/float(oldr)<0.5) or (float(bgg)/float(bgr)<0.5 and float(bgb)/float(bgr)<0.5):
return (wx.Colour(newr,newg,newb,128))
else:
return self.DefaultSelectionColor
else:
dc = wx.MemoryDC( )
dc.SelectObject( self.bg_buff)
x=dc.GetSize()[0]/2
y=dc.GetSize()[1]/2
n=50
xt=x+n
b=0
g=0
r=0
while x<xt:
y+=1
tc=dc.GetPixel(x,y)
b+=tc.Blue()
g+=tc.Green()
r+=tc.Red()
x+=1
b/=n
g/=n
r/=n
newr=(510-oldr-r)/2
newg=(510-oldg-g)/2
newb=(510-oldb-b)/2
if oldr==0: oldr=1
if oldg==0: oldg=1
if oldb==0: oldb=1
if r==0: r=1
if g==0: g=1
if b==0: b=1
if (float(oldg)/float(oldr)<0.5 and float(oldb)/float(oldr)<0.5) or (float(g)/float(r)<0.5 and float(b)/float(r)<0.5):
return (wx.Colour(newr,newg,newb,128))
else:
return self.DefaultSelectionColor
def DrawSelection(self,dc,r1,r2):
"""内部函数,画出选择文字时的选择条"""
dc.SetFont(self.GetFont())
if r1==None or r2==None:return
ch_h=dc.GetCharHeight()
ch_w=dc.GetTextExtent(u'我')[0]
newc=self.GenSelectColor()
self.blockline=self.maxHeight/(ch_h+self.linespace)
dc.SetTextForeground(newc)
dc.BeginDrawing()
gc = wx.GraphicsContext.Create(dc)
gc.SetBrush(wx.Brush(newc))
if self.show_mode=='paper':
if r1['pos'][1]==r2['pos'][1]:
#如果在同一行
dc.SetTextForeground(newc)
y=r1['pos'][1]
if r1['pos'][0]>r2['pos'][0]:
x1=r2['pos'][0]
x2=r1['pos'][0]
i1=r2['index']
i2=r1['index']
else:
x2=r2['pos'][0]
x1=r1['pos'][0]
i2=r2['index']
i1=r1['index']
gc.DrawRectangle(x1,y,(x2-x1),ch_h)
else:
if r1['pos'][1]>r2['pos'][1]:
y2=r1['pos'][1]
x2=r1['pos'][0]
l2=r1['line']
w2=r1['row']
y1=r2['pos'][1]
x1=r2['pos'][0]
l1=r2['line']
w1=r2['row']
elif r1['pos'][1]<r2['pos'][1]:
y1=r1['pos'][1]
x1=r1['pos'][0]
l1=r1['line']
w1=r1['row']
y2=r2['pos'][1]
x2=r2['pos'][0]
l2=r2['line']
w2=r2['row']
gc.DrawRectangle(x1,y1,self.maxWidth-self.pagemargin-x1,ch_h)
line=l1
y=y1+ch_h+self.linespace
while line<l2-1:
gc.DrawRectangle(self.pagemargin,y,self.maxWidth-2*self.pagemargin,ch_h)
line+=1
y+=ch_h+self.linespace
gc.DrawRectangle(self.pagemargin,y,x2-self.pagemargin,ch_h)
elif self.show_mode=='book':
if r1['pos'][1]==r2['pos'][1] \
and ((r1['pos'][0]<=self.maxWidth/2 and r2['pos'][0]<=self.maxWidth/2) \
or (r1['pos'][0]>self.maxWidth/2 and r2['pos'][0]>self.maxWidth/2)):
dc.SetTextForeground(newc)
y=r1['pos'][1]
if r1['pos'][0]>r2['pos'][0]:
x1=r2['pos'][0]
x2=r1['pos'][0]
i1=r2['index']
i2=r1['index']
else:
x2=r2['pos'][0]
x1=r1['pos'][0]
i2=r2['index']
i1=r1['index']
gc.DrawRectangle(x1,y,(x2-x1),ch_h)
else:
if r1['index']<r2['index']:
y1=r1['pos'][1]
x1=r1['pos'][0]
l1=r1['line']
w1=r1['row']
i1=r1['index']
i2=r2['index']
y2=r2['pos'][1]
x2=r2['pos'][0]
l2=r2['line']
w2=r2['row']
else:
y2=r1['pos'][1]
x2=r1['pos'][0]
l2=r1['line']
w2=r1['row']
i1=r2['index']
i2=r1['index']
y1=r2['pos'][1]
x1=r2['pos'][0]
l1=r2['line']
w1=r2['row']
#draw book mode
#draw left page
if l1<self.blockline:
gc.DrawRectangle(x1,y1,self.maxWidth/2-self.centralmargin/2-x1,ch_h)
line=l1
y=y1+ch_h+self.linespace
if l2<=self.blockline:
tline=l2-1
else:
tline=self.blockline-1
while line<tline:
gc.DrawRectangle(self.bookmargin,y,self.maxWidth/2-self.centralmargin/2-self.bookmargin,ch_h)
line+=1
y+=ch_h+self.linespace
if l2<=self.blockline:
gc.DrawRectangle(self.bookmargin,y,x2-self.bookmargin,ch_h)
#draw right page
if l2>=self.blockline:
y=0
if l1>=self.blockline:
y=y1
gc.DrawRectangle(x1,y,self.maxWidth-self.bookmargin-x1,ch_h)
line=l1
y+=self.linespace+ch_h
while line<l2-1:
gc.DrawRectangle(self.maxWidth/2+self.centralmargin/2,y,self.maxWidth-(self.maxWidth/2+self.centralmargin/2+self.bookmargin),ch_h)
line+=1
y+=ch_h+self.linespace
gc.DrawRectangle(self.maxWidth/2+self.centralmargin/2,y,x2-(self.maxWidth/2+self.centralmargin/2),ch_h)
else:
if l2==line+1:
gc.DrawRectangle(self.maxWidth/2+self.centralmargin/2,y,x2-(self.maxWidth/2+self.centralmargin/2),ch_h)
y+=self.linespace+ch_h
else:
if l1>self.blockline:
tt=l2
else:
tt=l2-1
while line<tt:
gc.DrawRectangle(self.maxWidth/2+self.centralmargin/2,y,self.maxWidth-(self.maxWidth/2+self.centralmargin/2+self.bookmargin),ch_h)
line+=1
y+=ch_h+self.linespace
gc.DrawRectangle(self.maxWidth/2+self.centralmargin/2,y,x2-(self.maxWidth/2+self.centralmargin/2),ch_h)
elif self.show_mode=='vbook':
newwidth=self.maxWidth/2-self.vbookmargin-self.centralmargin
newheight=self.maxHeight-2*self.vbookmargin
self.blockline=newwidth/(ch_w+self.vlinespace)
if r1['pos'][0]==r2['pos'][0]:
if r1['pos'][1]<r2['pos'][1]:
x1=r1['pos'][0]
x2=r2['pos'][0]
y1=r1['pos'][1]
y2=r2['pos'][1]
else:
x1=r2['pos'][0]
x2=r1['pos'][0]
y1=r2['pos'][1]
y2=r1['pos'][1]
bar_wid=ch_w+self.vlinespace/2
gc.DrawRectangle(x1,y1,bar_wid,y2-y1)
else:
bar_wid=ch_w+self.vlinespace/2
if r1['pos'][0]>r2['pos'][0]:
x1=r1['pos'][0]
x2=r2['pos'][0]
y1=r1['pos'][1]
y2=r2['pos'][1]
l1=r1['line']
l2=r2['line']
i1=r1['row']
i2=r2['row']
v1=r1['index']
v2=r2['index']
else:
x1=r2['pos'][0]
x2=r1['pos'][0]
y1=r2['pos'][1]
y2=r1['pos'][1]
l1=r2['line']
l2=r1['line']
i1=r2['row']
i2=r1['row']
v1=r2['index']
v2=r1['index']
#draw right page
if l1<=self.blockline:
line=l1
gc.DrawRectangle(x1,y1,bar_wid,self.maxHeight-self.vbookmargin-y1)
line+=1
x=x1-(ch_w+self.vlinespace/2+self.vlinespace/2)
y=self.vbookmargin
if self.blockline>l2:
tline=l2
else:
tline=self.blockline
while line<tline:
gc.DrawRectangle(x,y,bar_wid,self.maxHeight-2*self.vbookmargin)
line+=1
x-=(ch_w+self.vlinespace/2+self.vlinespace/2)
if tline==l2:
gc.DrawRectangle(x,y,bar_wid,(ch_h+2)*i2)
else:
gc.DrawRectangle(x,y,bar_wid,self.maxHeight-2*self.vbookmargin)
#draw left page
if l2>self.blockline:
if l1>self.blockline:
line=l1
gc.DrawRectangle(x1,y1,bar_wid,self.maxHeight-self.vbookmargin-y1)
line+=1
x=x1-(ch_w+self.vlinespace/2+self.vlinespace/2)
y=self.vbookmargin
while line<l2:
gc.DrawRectangle(x,y,bar_wid,self.maxHeight-2*self.vbookmargin)
line+=1
x-=(ch_w+self.vlinespace/2+self.vlinespace/2)
gc.DrawRectangle(x,y,bar_wid,(ch_h+2)*i2)
else:
line=self.blockline
x=self.maxWidth/2-self.centralmargin-2*ch_w
y=self.vbookmargin
while line<l2-1:
gc.DrawRectangle(x,y,bar_wid,self.maxHeight-2*self.vbookmargin)
line+=1
x-=(ch_w+self.vlinespace/2+self.vlinespace/2)
gc.DrawRectangle(x,y,bar_wid,(ch_h+2)*i2)
dc.EndDrawing()
def OnMouseDrag(self,evt):
"""处理鼠标事件的函数,主要是用来处理选择文字极其拷贝的操作"""
if evt.ButtonDown(wx.MOUSE_BTN_LEFT):
self.LastMousePos=evt.GetPositionTuple()
self.FirstMousePos=evt.GetPositionTuple()
if self.buffer_bak<>None:
if self.bg_img==None or self.bg_buff==None or self.newbmp==None:
self.buffer=self.buffer_bak.GetSubBitmap(wx.Rect(0, 0, self.buffer_bak.GetWidth(), self.buffer_bak.GetHeight()))
dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)
else:
self.newbmp=self.buffer_bak.GetSubBitmap(wx.Rect(0, 0, self.buffer_bak.GetWidth(), self.buffer_bak.GetHeight()))
dc = wx.BufferedDC(wx.ClientDC(self), self.newbmp)
dc.BeginDrawing()
dc.EndDrawing()
return
if evt.Dragging():
current_mouse_pos=evt.GetPositionTuple()
if current_mouse_pos==self.LastMousePos or self.FirstMousePos==None:
return
else:
r1=self.GetHitPos(self.FirstMousePos)
r2=self.GetHitPos(current_mouse_pos)
if self.bg_img==None or self.bg_buff==None or self.newbmp==None:
self.buffer=self.buffer_bak.GetSubBitmap(wx.Rect(0, 0, self.buffer_bak.GetWidth(), self.buffer_bak.GetHeight()))
dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)
else:
self.newbmp=self.buffer_bak.GetSubBitmap(wx.Rect(0, 0, self.buffer_bak.GetWidth(), self.buffer_bak.GetHeight()))
dc = wx.BufferedDC(wx.ClientDC(self), self.newbmp)
self.DrawSelection(dc,r1,r2)
self.LastMousePos=current_mouse_pos
elif evt.ButtonUp(wx.MOUSE_BTN_LEFT) and not evt.LeftDClick():
if self.FirstMousePos==None:return
current_mouse_pos=evt.GetPositionTuple()
r1=self.GetHitPos(self.FirstMousePos)
r2=self.GetHitPos(current_mouse_pos)
if r1==None or r2==None:return
if r1['index']>r2['index']:
self.SelectedRange[0]=r2['index']
self.SelectedRange[1]=r1['index']
## self.SelectedRange=[r2['index'],r1['index']]
else:
self.SelectedRange[1]=r2['index']
self.SelectedRange[0]=r1['index']
## self.SelectedRange=[r1['index'],r2['index']]
## if evt.RightUp():
## clipdata = wx.TextDataObject()
## clipdata.SetText(self.Value[self.SelectedRange[0]:self.SelectedRange[1]])
## if not wx.TheClipboard.IsOpened():
## wx.TheClipboard.Open()
## wx.TheClipboard.SetData(clipdata)
## wx.TheClipboard.Close()
## if self.buffer_bak<>None:
## if self.bg_img==None or self.bg_buff==None or self.newbmp==None:
## self.buffer=self.buffer_bak.GetSubBitmap(wx.Rect(0, 0, self.buffer_bak.GetWidth(), self.buffer_bak.GetHeight()))
## dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)
## else:
## self.newbmp=self.buffer_bak.GetSubBitmap(wx.Rect(0, 0, self.buffer_bak.GetWidth(), self.buffer_bak.GetHeight()))
## dc = wx.BufferedDC(wx.ClientDC(self), self.newbmp)
## dc.BeginDrawing()
## dc.EndDrawing()
def CopyText(self):
clipdata = wx.TextDataObject()
clipdata.SetText(self.Value[self.SelectedRange[0]:self.SelectedRange[1]])
if not wx.TheClipboard.IsOpened():
wx.TheClipboard.Open()
wx.TheClipboard.SetData(clipdata)
wx.TheClipboard.Close()
if self.buffer_bak<>None:
if self.bg_img==None or self.bg_buff==None or self.newbmp==None:
self.buffer=self.buffer_bak.GetSubBitmap(wx.Rect(0, 0, self.buffer_bak.GetWidth(), self.buffer_bak.GetHeight()))
dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)
else:
self.newbmp=self.buffer_bak.GetSubBitmap(wx.Rect(0, 0, self.buffer_bak.GetWidth(), self.buffer_bak.GetHeight()))
dc = wx.BufferedDC(wx.ClientDC(self), self.newbmp)
dc.BeginDrawing()
dc.EndDrawing()
def OnChar(self,event):
"""键盘输入控制函数"""
key=event.GetKeyCode()
if key == wx.WXK_PAGEDOWN or key==wx.WXK_SPACE or key==wx.WXK_RIGHT:
self.ScrollP(1)
return
if key==wx.WXK_LEFT or key == wx.WXK_PAGEUP:
self.ScrollP(-1)
return
if key == wx.WXK_UP:
self.ScrollLine(-1)
return
if key == wx.WXK_DOWN:
self.ScrollLine(1)
return
if key == wx.WXK_HOME :
self.ScrollTop()
return
if key == wx.WXK_END :
self.ScrollBottom()
return
event.Skip()
def DrawBackground(self,dc):
"""Draw background according to show_mode and bg_img"""
sz = dc.GetSize()
w = self.bg_img.GetWidth()
h = self.bg_img.GetHeight()
if self.bg_style=='tile':
x = 0
while x <= sz.width:
y = 0
while y <= sz.height:
dc.DrawBitmap(self.bg_img, x, y)
y = y + h
x = x + w
else:
startx=(sz.width-w)/2
if startx<0:startx=0
starty=(sz.height-h)/2
if starty<0:starty=0
dc.DrawBitmap(self.bg_img,startx,starty)
self.DrawBookCentral(dc)
## if self.show_mode=='vbook':
## oldpen=dc.GetPen()
## oldbrush=dc.GetBrush()
## dc.SetPen(wx.Pen('grey',width=5))
## dc.SetBrush(wx.Brush('white',style=wx.TRANSPARENT))
## dc.DrawLine(self.vbookmargin,self.vbookmargin,self.maxWidth-self.vbookmargin,self.vbookmargin)
## dc.DrawLine(self.vbookmargin,self.maxHeight-2*self.vbookmargin,self.maxWidth-self.vbookmargin,self.maxHeight-2*self.vbookmargin)
## dc.SetPen(oldpen)
## dc.SetBrush(oldbrush)
## if self.show_mode=='book' or self.show_mode=='vbook':
## dc.DrawLine(3,0,3,sz.height)
## dc.DrawLine(4,0,4,sz.height)
## dc.DrawLine(6,0,6,sz.height)
## dc.DrawLine(8,0,8,sz.height)
## dc.DrawLine(10,0,10,sz.height)
##
## dc.DrawLine(sz.width-3,0,sz.width-3,sz.height)
## dc.DrawLine(sz.width-4,0,sz.width-4,sz.height)
## dc.DrawLine(sz.width-6,0,sz.width-6,sz.height)
## dc.DrawLine(sz.width-8,0,sz.width-8,sz.height)
## dc.DrawLine(sz.width-10,0,sz.width-10,sz.height)
## x=sz.width/2-20
## y=self.pagemargin+10
## n=self.pagemargin+10
## xt=x+n
## b=0
## g=0
## r=0
## while x<xt:
## tc=dc.GetPixel(x,y)
## b+=tc.Blue()
## g+=tc.Green()
## r+=tc.Red()
## x+=1
## b/=n
## g/=n
## r/=n
##
## dc.GradientFillLinear((sz.width/2-self.centralmargin,0, self.centralmargin,sz.height),wx.Color(r,g,b,0),'grey')
## dc.GradientFillLinear((sz.width/2,0, self.centralmargin,sz.height),'grey',wx.Color(r,g,b,0))
def DrawBookCentral(self,dc):
sz = dc.GetSize()
if self.show_mode=='book' or self.show_mode=='vbook':
dc.DrawLine(3,0,3,sz.height)
dc.DrawLine(4,0,4,sz.height)
dc.DrawLine(6,0,6,sz.height)
dc.DrawLine(8,0,8,sz.height)
dc.DrawLine(10,0,10,sz.height)
dc.DrawLine(sz.width-3,0,sz.width-3,sz.height)
dc.DrawLine(sz.width-4,0,sz.width-4,sz.height)
dc.DrawLine(sz.width-6,0,sz.width-6,sz.height)
dc.DrawLine(sz.width-8,0,sz.width-8,sz.height)
dc.DrawLine(sz.width-10,0,sz.width-10,sz.height)
x=sz.width/2-20
y=self.pagemargin+10
n=self.pagemargin+10
xt=x+n
b=0
g=0
r=0
while x<xt:
tc=dc.GetPixel(x,y)
b+=tc.Blue()
g+=tc.Green()
r+=tc.Red()
x+=1
b/=n
g/=n
r/=n
dc.GradientFillLinear((sz.width/2-self.centralmargin,0, self.centralmargin,sz.height),wx.Colour(r,g,b,0),'grey')
dc.GradientFillLinear((sz.width/2,0, self.centralmargin,sz.height),'grey',wx.Colour(r,g,b,0))
def Clear(self):
self.SetValue('')
self.ReDraw()
def ReDraw(self):
"""ReDraw self"""
delta=(self.GetSize()[1]-self.GetClientSize()[1])+1
self.maxHeight=self.GetClientSize()[1]
self.maxWidth=self.GetClientSize()[0]-delta
self.SetVirtualSize((self.maxWidth, self.maxHeight))
self.current_pos=self.start_pos
self.bg_buff=None
self.buffer=None
self.ShowPos(1)
## self.current_pos=0
self.current_pos=self.start_pos
self.ShowPos(1)
self.Refresh(False)
def SetShowMode(self,m):
"""设置显示模式,支持的有'book/paper/vbook'"""
self.show_mode=m
def GetPos(self):
"""返回当前页面显示最后一个字在self.ValueList中的index"""
return self.current_pos
def GetStartPos(self):
return self.start_pos
def GetPosPercent(self):
try:
return (float(self.current_pos)/float(self.ValueCharCount))*100
except:
return False
def GetConfig(self):
r={}
r['pagemargin']=self.pagemargin
r['bookmargin']=self.bookmargin
r['vbookmargin']=self.vbookmargin
r['centralmargin']=self.centralmargin
r['linespace']=self.linespace
r['vlinespace']=self.vlinespace
r['underline']=self.under_line
r['underlinecolor']=self.under_line_color
r['underlinestyle']=self.under_line_style
r['backgroundimg']=self.bg_img_path
r['backgroundimglayout']=self.bg_style
r['showmode']=self.show_mode
return r
def ScrollHalfP(self,direction=1):
"""翻半页"""
if self.show_mode<>'paper':return
line_no=len(self.curPageTextList)
self.ScrollLine(direction,line_no/2)
def ScrollPercent(self,percent,direction=1):
"""按百分比翻页"""
if not isinstance(percent,int) or percent<=0 or percent>100:return
self.updatePosList(self.start_pos)
delta=(self.ValueCharCount*percent)/100
if direction==1:
newpos=self.current_pos+delta
if newpos<self.ValueCharCount:
self.current_pos=newpos
self.ShowPos()
else:
self.start_pos=self.ValueCharCount
self.ShowPos(-1)
else:
newpos=self.start_pos-delta
if newpos<=0:
self.current_pos=0
self.ShowPos()
else:
self.start_pos=newpos
self.ShowPos(-1)
self.Refresh()
def ScrollLine(self,direction=1,line_count=1):
if self.show_mode<>'paper':return
line_no=len(self.curPageTextList)
if line_no == 0:return
if direction==1:
if self.curPageTextList[line_no-1][4]>=self.ValueCharCount:
return
self.current_pos=self.curPageTextList[line_count-1][4]
self.ScrollP(1)
elif direction==-1:
self.start_pos=self.curPageTextList[line_no-line_count][3]
self.ScrollP(-1)
def ScrollTop(self):
"""显示第一页"""
self.updatePosList(self.start_pos)
self.current_pos=0
self.start_pos=0
self.ShowPos(1)
self.Refresh()
def ScrollBottom(self):
"""显示最后一页"""
self.updatePosList(self.start_pos)
self.start_pos=self.ValueCharCount
self.ShowPos(-1)
self.Refresh()
def ScrollP(self,direction):
"""向上或是向下翻页"""
## t1=time.time()
self.ShowPos(direction)
self.Refresh(False) #Use False to avoid background flicker
## print time.time()-t1
## def getPreviousLine(self,txt):
## llist=txt.splitlines()
## dc=wx.MemoryDC()
## dc.SetFont(self.GetFont())
## delta=2*dc.GetCharHeight()
## lline=llist[len(llist)-1]
## newwidth=self.maxWidth-2*self.pagemargin
## if dc.GetTextExtent(lline)[0]<=newwidth:
## if txt[len(txt)-1]=='\n':
## return lline+'\n'
## else:
## return lline
## else:
## high=len(lline)-1
## low=0
##
## while low<high:
## mid=(low+high)/2
## if dc.GetTextExtent(lline[mid:])[0]>newwidth: low=mid+1
## else:
## if dc.GetTextExtent(lline[mid:])[0]<newwidth: high=mid-1
## else:
## break
## if dc.GetTextExtent(lline[mid:])[0]>newwidth: mid-=1
## if txt[len(txt)-1]=='\n': return lline[mid:]+'\n'
## else:
## return lline[mid:]
## def ScrollL(self,direction):
## """向上或是向下翻行"""
## if direction==1:
## self.current_pos=self.start_pos+len(self.curPageTextList[0][0])+self.curPageTextList[0][1]
## self.ShowPos(1)
## else:
## n=len(self.curPageTextList)
## self.start_pos=self.start_pos+len()
##
## self.ShowPos(-1)
##
## self.Refresh()
## def OnScroll(self,evt):
## if self.GetScrollPos(wx.VERTICAL)==0:
## self.ScollP(-1)
#### pass
## else:
## if self.GetScrollPos(wx.VERTICAL)+self.GetScrollThumb(wx.VERTICAL)==self.GetScrollRange(wx.VERTICAL):
## self.ScollP(1)
## evt.Skip()
def OnResize(self,evt):
"""处理窗口尺寸变化的事件"""
self.isdirty=True
self.ReDraw()
evt.Skip()
def OnPaint(self, event):
"""处理重画事件"""
delta=(self.GetSize()[1]-self.GetClientSize()[1])+1
self.maxHeight=self.GetClientSize()[1]
self.maxWidth=self.GetClientSize()[0]-delta
self.SetVirtualSize((self.maxWidth, self.maxHeight))
if self.buffer<>None and not self.isdirty:
if self.bg_img==None or self.bg_buff==None or self.newbmp==None:
dc = wx.BufferedPaintDC(self, self.buffer, wx.BUFFER_VIRTUAL_AREA)
else:
dc = wx.BufferedPaintDC(self, self.newbmp, wx.BUFFER_VIRTUAL_AREA)
else:
self.ShowPos(1)
def GetValue(self):
return self.Value
def SetValue(self,txt,pos=0):
"""赋值函数,载入并显示一个字符串"""
#把DOS ending转换成UNIX Ending,否则选择文字的时候会出问题
self.Value=txt.replace("\r\n","\n")
self.ValueCharCount=len(self.Value)
self.current_pos=pos
self.start_pos=0
self.Refresh()
self.ReDraw()
self.pos_list=[]
def AppendValue(self,txt):
"""
append txt to current value and keep current_pos
"""
txt=txt.replace("\r\n","\n")
self.ValueCharCount+=len(txt)
self.Value+=txt
#self.Refresh()
self.ReDraw()
def JumpTo(self,pos):
self.updatePosList(self.start_pos)
self.current_pos=pos
self.start_pos=0
self.ShowPos(1)
self.ReDraw()
def SetSpace(self,pagemargin=None,bookmargin=None,vbookmargin=None,centralmargin=None,linespace=None,vlinespace=None):
if pagemargin<>None:self.pagemargin=pagemargin
if bookmargin<>None:self.bookmargin=bookmargin
if vbookmargin<>None:self.vbookmargin=vbookmargin
if centralmargin<>None:self.centralmargin=centralmargin
if linespace<>None:self.linespace=linespace
if vlinespace<>None:self.vlinespace=vlinespace
def SetUnderline(self,visual=None,style=None,color=None):
if visual<>None:self.under_line=visual
if color<>None:self.under_line_color=color
if style<>None:self.under_line_style=style
def SetFColor(self,color):
self.TextForeground=color
def GetFColor(self):
return self.TextForeground
def SetImgBackground(self,img,style='tile'):
"""设置图片背景"""
self.bg_style=style
if img==None or img=='':
self.bg_img=None
self.bg_img_path=None
return
if isinstance(img,wx.Bitmap):
self.bg_img=img
else:
if isinstance(img,str) or isinstance(img,unicode):
if img=='' or img==None:
self.bg_img=None
return
if isinstance(img,str):img=img.decode('gbk')
if os.name=='nt' or sys.platform=='win32':
if img.find('\\')==-1:
if not isinstance(sys.argv[0],unicode):
argv0=os.path.abspath(sys.argv[0]).decode('gbk')
else:
argv0=os.path.abspath(sys.argv[0])
img=os.path.dirname(argv0)+u"\\background\\"+img
else:
if img.find('/')==-1:
img=cur_file_dir()+u"/background/"+img
if not os.path.exists(img):
return False
self.bg_img_path=img
self.bg_img=wx.Bitmap(img, wx.BITMAP_TYPE_ANY)
else:
self.bg_img=None
## if self.bg_img<>None:
## self.bg_img_buffer.BeginDrawing()
## self.DrawBackground(self.bg_img_buffer)
## self.bg_img_buffer.EndDrawing()
def breakline(self,line,dc):
"""内部函数,断句"""
rr=line
rlist=[]
if self.show_mode=='paper':
newwidth=self.maxWidth-2*self.pagemargin
#delta=int(dc.GetCharWidth()*2.5)
delta=dc.GetCharWidth()
delta=0
elif self.show_mode=='book':
newwidth=self.maxWidth/2-self.bookmargin-self.centralmargin
delta=dc.GetCharHeight()
elif self.show_mode=='vbook':
ch_h=dc.GetCharHeight()
ch_w=dc.GetCharWidth()
newwidth=self.maxWidth-2*self.vbookmargin
newheight=self.maxHeight-2*self.vbookmargin
if self.show_mode=='book' or self.show_mode=='paper':
llist=dc.GetPartialTextExtents(line)
## ii=0
## test=[]
## while ii<len(line):
## #test[line[ii]]=llist[ii]
## test.append((line[ii],llist[ii]))
## ii+=1
## print 'newwidth is',newwidth
## for x in test:
## print x[0],x[1]
n=len(llist)-1
mid=0
mylen=llist[n]
while mylen>newwidth:
high=n
low=mid
base=mid
if base==0:
lfix=llist[0]
else:
lfix=llist[base]-llist[base-1]
mid=(low+high)/2
while low<=high:
if (llist[mid]-llist[base]+lfix)>newwidth:
high=mid-1
else:
if (llist[mid]-llist[base]+lfix)<newwidth:
low=mid+1
else:
## print "give me a break"
## print "low,high",low,high
## print llist
break
mid=(low+high)/2
## if dc.GetTextExtent(rr[:mid])[0]>newwidth: mid-=1
mid+=1
rlist.append([rr[base:mid],0])
nstr=rr[base:mid]
# if nstr[-2:]==u'酒醉':
## print nstr
## print 'high is ',high
## print 'low is ',low
mylen=llist[n]-llist[mid-1]
rlist.append([rr[mid:],1])
return rlist
elif self.show_mode=='vbook':
n=newheight/(ch_h+2)
i=0
while i<len(line):
rlist.append([line[i:i+n],0])
i+=n
i-=n
rlist[len(rlist)-1][1]=1
return rlist
def mywrap(self,txt):
"""排版"""
dc=wx.MemoryDC()
dc.SelectObject(wx.EmptyBitmap(1, 1))
dc.SetFont(self.GetFont())
ch_h=dc.GetCharHeight()
ch_w=dc.GetCharWidth()
if self.show_mode=='paper':
newwidth=self.maxWidth-2*self.pagemargin
elif self.show_mode=='book':
newwidth=self.maxWidth/2-self.bookmargin-self.centralmargin
elif self.show_mode=='vbook':
newwidth=self.maxWidth-2*self.vbookmargin
newheight=self.maxHeight-2*self.vbookmargin
rlist=[]
if self.show_mode=='paper':
for line in txt.splitlines():
if dc.GetTextExtent(line)[0]<= newwidth:
rlist.append([line,1])
else:
trlist=self.breakline(line,dc)
rlist+=trlist
elif self.show_mode=='book':
for line in txt.splitlines():
if dc.GetTextExtent(line)[0]<= newwidth:
rlist.append([line,1])
else:
trlist=self.breakline(line,dc)
rlist+=trlist
elif self.show_mode=='vbook':
for line in txt.splitlines():
if len(line)*(self.linespace+ch_h)<=newheight:
rlist.append([line,1])
else:
trlist=self.breakline(line,dc)
rlist+=trlist
return rlist
def Find(self,key,pos=0,direction=1):
if direction==1:
next_index=self.Value.find(key,pos)
else:
next_index=self.Value.rfind(key,0,pos)
if next_index==-1:return False
self.JumpTo(next_index)
self.ReDraw()
return next_index
def ShowPosition(self,pos):
self.updatePosList(self.start_pos)
self.start_pos=pos
self.ShowPos()
def ShowPos(self,direction=1):
"""从指定位置开始,画出一页的文本"""
## if self.Value==None or self.Value=='':
## print "value"
## self.Value=u"LiteBook 2.0"
## self.ValueCharCount=len(u"LiteBook 2.0")
self.isdirty=False
## if self.start_pos<0: self.start_pos=0
if self.Value==None:
return
if direction==1:
if self.current_pos>=self.ValueCharCount & self.ValueCharCount<>0:
return
else:
if self.start_pos<=0:
## self.start_pos=0
return
## if direction==1:
## if self.current_pos>=len(self.Value) & self.ValueCharCount<>0:
## return
self.RenderDirection=direction
dc=wx.MemoryDC()
dc.SelectObject(wx.EmptyBitmap(1, 1))
dc.SetFont(self.GetFont())
ch_h=dc.GetCharHeight()
ch_w=dc.GetCharWidth()
maxcount=(self.maxHeight/(ch_h+self.linespace))*((self.maxWidth-2*self.pagemargin)/(ch_w))
self.blockline=self.maxHeight/(ch_h+self.linespace)
self.SetVirtualSize((self.maxWidth, self.maxHeight))
self.buffer = wx.EmptyBitmap(self.maxWidth, self.maxHeight)
if self.bg_buff==None:
dc = wx.BufferedDC(None, self.buffer)
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
else:
self.newbmp=self.bg_buff.GetSubBitmap(wx.Rect(0, 0, self.bg_buff.GetWidth(), self.bg_buff.GetHeight()));
dc = wx.BufferedDC(None, self.newbmp)
dc.SetFont(self.GetFont())
dc.SetTextForeground(self.TextForeground)
dc.SetTextBackground('black')
dc.BeginDrawing()
#draw backgroup
if self.bg_img<>None and self.bg_buff==None:
self.DrawBackground(dc)
if self.bg_buff==None:
memory = wx.MemoryDC( )
x,y = self.GetClientSizeTuple()
self.bg_buff = wx.EmptyBitmap( x,y, -1 )
memory.SelectObject( self.bg_buff )
memory.Blit( 0,0,x,y, dc, 0,0)
memory.SelectObject( wx.NullBitmap)
if self.bg_img==None:
self.DrawBookCentral(dc)
if self.ValueCharCount==0:
dc.EndDrawing()
memory = wx.MemoryDC( )
x,y = self.GetClientSizeTuple()
self.buffer_bak = wx.EmptyBitmap( x,y, -1 )
memory.SelectObject( self.buffer_bak )
memory.Blit( 0,0,x,y, dc, 0,0)
memory.SelectObject( wx.NullBitmap)
return
if self.show_mode=='paper':
#draw paper mode
h=0
cur_pos=self.current_pos
cur_x=0
self.curPageTextList=[]
if direction==1:
if cur_pos+maxcount<len(self.Value):
tmptxt=self.Value[cur_pos:cur_pos+maxcount]
else:
tmptxt=self.Value[cur_pos:]
ptxtlist=self.mywrap(tmptxt)
if tmptxt[len(tmptxt)-1]<>'\n':ptxtlist[len(ptxtlist)-1][1]=0
line=0
delta=0
line_start=0
line_end=0
while line<self.blockline:
dc.DrawText(ptxtlist[line][0],self.pagemargin,h)
if self.under_line:
oldpen=dc.GetPen()
newpen=wx.Pen(self.under_line_color,style=self.under_line_style)
dc.SetPen(newpen)
dc.DrawLine(self.pagemargin,h+ch_h+2,self.maxWidth-self.pagemargin,h+ch_h+2)
dc.SetPen(oldpen)
line_start=self.current_pos+delta
delta+=len(ptxtlist[line][0])+ptxtlist[line][1]
line_end=self.current_pos+delta
self.curPageTextList.append([ptxtlist[line][0],ptxtlist[line][1],h,line_start,line_end])
if line==len(ptxtlist)-1:break
h+=ch_h+self.linespace
line+=1
self.start_pos=self.current_pos
self.current_pos+=delta
else:
pos1=self.start_pos-maxcount
if pos1<0: pos1=0
pos2=self.start_pos
tmptxt=self.Value[pos1:pos2]
ptxtlist=self.mywrap(tmptxt)
if tmptxt[len(tmptxt)-1]<>'\n':ptxtlist[len(ptxtlist)-1][1]=0
line=len(ptxtlist)-1
if line<0:line=0
delta=0
h=self.maxHeight-ch_h
tlen=len(ptxtlist)-1-self.blockline
elist=[]
line_start=0
line_end=0
if tlen<0:
tmptxt=self.Value[:maxcount]
ptxtlist=self.mywrap(tmptxt)
if tmptxt[len(tmptxt)-1]<>'\n':ptxtlist[len(ptxtlist)-1][1]=0
line=0
delta=0
h=0
cpos=0
while line<self.blockline:
dc.DrawText(ptxtlist[line][0],self.pagemargin,h)
if self.under_line:
oldpen=dc.GetPen()
newpen=wx.Pen(self.under_line_color,style=self.under_line_style)
dc.SetPen(newpen)
dc.DrawLine(self.pagemargin,h+ch_h+2,self.maxWidth-self.pagemargin,h+ch_h+2)
dc.SetPen(oldpen)
line_start=cpos+delta
delta+=len(ptxtlist[line][0])+ptxtlist[line][1]
line_end=cpos+delta
self.curPageTextList.append([ptxtlist[line][0],ptxtlist[line][1],h,line_start,line_end])
if line==len(ptxtlist)-1:break
h+=ch_h+self.linespace
line+=1
self.start_pos=delta
self.current_pos=delta
else:
delta=0
while line>tlen :
dc.DrawText(ptxtlist[line][0],self.pagemargin,h)
if self.under_line:
oldpen=dc.GetPen()
newpen=wx.Pen(self.under_line_color,style=self.under_line_style)
dc.SetPen(newpen)
dc.DrawLine(self.pagemargin,h+ch_h+2,self.maxWidth-self.pagemargin,h+ch_h+2)
dc.SetPen(oldpen)
line_end=self.start_pos-delta
delta+=len(ptxtlist[line][0])+ptxtlist[line][1]
line_start=self.start_pos-delta
elist.append([ptxtlist[line][0],ptxtlist[line][1],h,line_start,line_end])
h-=(ch_h+self.linespace)
line-=1
self.current_pos=self.start_pos
self.start_pos-=delta
i=len(elist)-1
while i>=0:
self.curPageTextList.append(elist[i])
i-=1
elif self.show_mode=='book':
#draw book mode
h=0
cur_pos=self.current_pos
cur_x=0
self.curPageTextList=[]
if direction==1:
if cur_pos+maxcount<len(self.Value):
tmptxt=self.Value[cur_pos:cur_pos+maxcount]
else:
tmptxt=self.Value[cur_pos:]
ptxtlist=self.mywrap(tmptxt)
if tmptxt[len(tmptxt)-1]<>'\n':ptxtlist[len(ptxtlist)-1][1]=0
line=0
delta=0
#draw left page
while line<self.blockline:
dc.DrawText(ptxtlist[line][0],self.bookmargin,h)
self.curPageTextList.append([ptxtlist[line][0],ptxtlist[line][1],h])
if self.under_line:
oldpen=dc.GetPen()
newpen=wx.Pen(self.under_line_color,style=self.under_line_style)
dc.SetPen(newpen)
dc.DrawLine(self.bookmargin,h+ch_h+2,self.maxWidth-self.bookmargin,h+ch_h+2)
dc.SetPen(oldpen)
delta+=len(ptxtlist[line][0])+ptxtlist[line][1]
if line==len(ptxtlist)-1:break
h+=ch_h+self.linespace
line+=1
#draw right page
if line>=self.blockline:
h=0
newx=self.maxWidth/2+self.centralmargin
while line<2*self.blockline:
dc.DrawText(ptxtlist[line][0],newx,h)
self.curPageTextList.append([ptxtlist[line][0],ptxtlist[line][1],h])
## if self.under_line:
## oldpen=dc.GetPen()
## newpen=wx.Pen(self.under_line_color,style=self.under_line_style)
## dc.SetPen(newpen)
## dc.DrawLine(self.maxWidth/2+self.centralmargin,h+ch_h+2,self.maxWidth-self.bookmargin,h+ch_h+2)
## dc.SetPen(oldpen)
delta+=len(ptxtlist[line][0])+ptxtlist[line][1]
if line==len(ptxtlist)-1:break
h+=ch_h+self.linespace
line+=1
self.start_pos=self.current_pos
self.current_pos+=delta
else:
pos1=self.start_pos-maxcount
if pos1<0: pos1=0
pos2=self.start_pos
tmptxt=self.Value[pos1:pos2]
ptxtlist=self.mywrap(tmptxt)
if tmptxt[len(tmptxt)-1]<>'\n':ptxtlist[len(ptxtlist)-1][1]=0
line=len(ptxtlist)-1
if line<0:line=0
delta=0
h=self.maxHeight-ch_h
tlen=len(ptxtlist)-1-2*self.blockline
elist=[]
if tlen<0:
tmptxt=self.Value[:maxcount]
ptxtlist=self.mywrap(tmptxt)
if tmptxt[len(tmptxt)-1]<>'\n':ptxtlist[len(ptxtlist)-1][1]=0
line=0
delta=0
h=0
#draw left page
while line<self.blockline:
dc.DrawText(ptxtlist[line][0],self.pagemargin,h)
self.curPageTextList.append([ptxtlist[line][0],ptxtlist[line][1],h])
if self.under_line:
oldpen=dc.GetPen()
newpen=wx.Pen(self.under_line_color,style=self.under_line_style)
dc.SetPen(newpen)
dc.DrawLine(self.pagemargin,h+ch_h+2,self.maxWidth-self.pagemargin,h+ch_h+2)
dc.SetPen(oldpen)
delta+=len(ptxtlist[line][0])+ptxtlist[line][1]
if line==len(ptxtlist)-1:break
h+=ch_h+self.linespace
line+=1
#draw right page
h=0
newx=self.maxWidth/2+self.centralmargin
while line<2*self.blockline:
dc.DrawText(ptxtlist[line][0],newx,h)
self.curPageTextList.append([ptxtlist[line][0],ptxtlist[line][1],h])
## if self.under_line:
## oldpen=dc.GetPen()
## print "i am e"
## #newpen=wx.Pen(self.under_line_color,style=self.under_line_style)
## print "style is ",self.under_line_style
## print "dot is ",wx.DOT
## print "newpen sty is ",newpen.GetStyle()
## dc.SetPen(newpen)
## dc.DrawLine(self.maxWidth/2+self.centralmargin,h+ch_h+2,self.maxWidth-self.bookmargin,h+ch_h+2)
## dc.SetPen(oldpen)
delta+=len(ptxtlist[line][0])+ptxtlist[line][1]
if line==len(ptxtlist)-1:break
h+=ch_h+self.linespace
line+=1
self.start_pos=delta
self.current_pos=delta
else:
elist_right=[]
line=tlen+self.blockline
#draw left page
while line>tlen:
dc.DrawText(ptxtlist[line][0],self.pagemargin,h)
if self.under_line:
oldpen=dc.GetPen()
newpen=wx.Pen(self.under_line_color,style=self.under_line_style)
dc.SetPen(newpen)
dc.DrawLine(self.pagemargin,h+ch_h+2,self.maxWidth-self.pagemargin,h+ch_h+2)
dc.SetPen(oldpen)
elist.append([ptxtlist[line][0],ptxtlist[line][1],h])
delta+=len(ptxtlist[line][0])+ptxtlist[line][1]
h-=(ch_h+self.linespace)
line-=1
#draw right page
h=self.maxHeight-ch_h
newx=self.maxWidth/2+self.centralmargin
line=len(ptxtlist)-1
while line>tlen+self.blockline:
dc.DrawText(ptxtlist[line][0],newx,h)
## if self.under_line:
## oldpen=dc.GetPen()
## newpen=wx.Pen(self.under_line_color,style=self.under_line_style)
## dc.SetPen(newpen)
## dc.DrawLine(self.pagemargin,h+ch_h+2,self.maxWidth-self.pagemargin,h+ch_h+2)
## dc.SetPen(oldpen)
elist_right.append([ptxtlist[line][0],ptxtlist[line][1],h])
delta+=len(ptxtlist[line][0])+ptxtlist[line][1]
h-=(ch_h+self.linespace)
line-=1
self.current_pos=self.start_pos
self.start_pos-=delta
i=len(elist)-1
while i>=0:
self.curPageTextList.append(elist[i])
i-=1
if self.RenderDirection==-1 & self.start_pos<>0:
i=len(elist_right)-1
while i>=0:
self.curPageTextList.append(elist_right[i])
i-=1
elif self.show_mode=='vbook':
#draw vertical book
ch_w=dc.GetTextExtent(u'我')[0]
h=0
cur_pos=self.current_pos
cur_x=0
self.curPageTextList=[]
newwidth=self.maxWidth/2-self.vbookmargin-self.centralmargin
newheight=self.maxHeight-2*self.vbookmargin
self.blockline=newwidth/(ch_w+self.vlinespace)
if direction==1:
if cur_pos+maxcount<len(self.Value):
tmptxt=self.Value[cur_pos:cur_pos+maxcount]
else:
tmptxt=self.Value[cur_pos:]
tmptxt=self.toVBook(tmptxt)
ptxtlist=self.mywrap(tmptxt)
if tmptxt[len(tmptxt)-1]<>'\n':ptxtlist[len(ptxtlist)-1][1]=0
line=0
delta=0
#draw right page
x=self.maxWidth-self.vbookmargin-ch_w-10
while line<=self.blockline:
y=self.vbookmargin
for chh in ptxtlist[line][0]:
dc.DrawText(chh,x,y)
y+=(ch_h+2)
x-=(self.vlinespace/2)
self.curPageTextList.append(ptxtlist[line])
if self.under_line:
oldpen=dc.GetPen()
newpen=wx.Pen(self.under_line_color,style=self.under_line_style)
dc.SetPen(newpen)
dc.DrawLine(x,self.vbookmargin,x,self.maxHeight-self.vbookmargin)
dc.SetPen(oldpen)
x-=(ch_w+self.vlinespace/2)
delta+=len(ptxtlist[line][0])+ptxtlist[line][1]
if line==len(ptxtlist)-1:break
line+=1
#draw left page
if line>self.blockline:
x=self.maxWidth/2-self.centralmargin-2*ch_w
while line<=2*self.blockline:
y=self.vbookmargin
for chh in ptxtlist[line][0]:
dc.DrawText(chh,x,y)
y+=(ch_h+2)
x-=(self.vlinespace/2)
self.curPageTextList.append(ptxtlist[line])
if self.under_line:
oldpen=dc.GetPen()
newpen=wx.Pen(self.under_line_color,style=self.under_line_style)
dc.SetPen(newpen)
dc.DrawLine(x,self.vbookmargin,x,self.maxHeight-self.vbookmargin)
dc.SetPen(oldpen)
x-=(ch_w+self.vlinespace/2)
delta+=len(ptxtlist[line][0])+ptxtlist[line][1]
if line==len(ptxtlist)-1:break
line+=1
self.start_pos=self.current_pos
self.current_pos+=delta
else:
pos1=self.start_pos-maxcount
if pos1<0: pos1=0
pos2=self.start_pos
tmptxt=self.Value[pos1:pos2]
tmptxt=self.toVBook(tmptxt)
ptxtlist=self.mywrap(tmptxt)
if tmptxt[len(tmptxt)-1]<>'\n':ptxtlist[len(ptxtlist)-1][1]=0
line=len(ptxtlist)-1
if line<0:line=0
delta=0
h=self.maxHeight-ch_h
tlen=len(ptxtlist)-1-2*self.blockline
elist=[]
if tlen<0:
tmptxt=self.Value[:maxcount]
tmptxt=self.toVBook(tmptxt)
ptxtlist=self.mywrap(tmptxt)
if tmptxt[len(tmptxt)-1]<>'\n':ptxtlist[len(ptxtlist)-1][1]=0
line=0
delta=0
h=0
#draw right page
x=self.maxWidth-self.vbookmargin
while line<=self.blockline:
y=self.vbookmargin
for chh in ptxtlist[line][0]:
dc.DrawText(chh,x,y)
y+=(ch_h+2)
x-=(self.vlinespace/2)
self.curPageTextList.append(ptxtlist[line])
if self.under_line:
oldpen=dc.GetPen()
newpen=wx.Pen(self.under_line_color,style=self.under_line_style)
dc.SetPen(newpen)
dc.DrawLine(x,self.vbookmargin,x,self.maxHeight-self.vbookmargin)
dc.SetPen(oldpen)
x-=(ch_w+self.vlinespace/2)
delta+=len(ptxtlist[line][0])+ptxtlist[line][1]
if line==len(ptxtlist)-1:break
line+=1
#draw left page
x=self.maxWidth/2-self.centralmargin-2*ch_w
while line<=2*self.blockline:
y=self.vbookmargin
for chh in ptxtlist[line][0]:
dc.DrawText(chh,x,y)
y+=(ch_h+2)
x-=(self.vlinespace/2)
self.curPageTextList.append(ptxtlist[line])
if self.under_line:
oldpen=dc.GetPen()
newpen=wx.Pen(self.under_line_color,style=self.under_line_style)
dc.SetPen(newpen)
dc.DrawLine(x,self.vbookmargin,x,self.maxHeight-self.vbookmargin)
dc.SetPen(oldpen)
x-=(ch_w+self.vlinespace/2)
delta+=len(ptxtlist[line][0])+ptxtlist[line][1]
if line==len(ptxtlist)-1:break
line+=1
self.start_pos=delta
self.current_pos=delta
else:
line=tlen
#line=0
#draw right page
x=self.maxWidth-self.vbookmargin
while line<=tlen+self.blockline:
y=self.vbookmargin
for chh in ptxtlist[line][0]:
dc.DrawText(chh,x,y)
y+=(ch_h+2)
x-=(self.vlinespace/2)
self.curPageTextList.append(ptxtlist[line])
if self.under_line:
oldpen=dc.GetPen()
newpen=wx.Pen(self.under_line_color,style=self.under_line_style)
dc.SetPen(newpen)
dc.DrawLine(x,self.vbookmargin,x,self.maxHeight-self.vbookmargin)
dc.SetPen(oldpen)
x-=(ch_w+self.vlinespace/2)
delta+=len(ptxtlist[line][0])+ptxtlist[line][1]
if line==len(ptxtlist)-1:break
line+=1
#draw left page
x=self.maxWidth/2-self.centralmargin-2*ch_w
line=tlen+self.blockline+1
while line<len(ptxtlist):
y=self.vbookmargin
for chh in ptxtlist[line][0]:
dc.DrawText(chh,x,y)
y+=(ch_h+2)
x-=(self.vlinespace/2)
if self.under_line:
oldpen=dc.GetPen()
newpen=wx.Pen(self.under_line_color,style=self.under_line_style)
dc.SetPen(newpen)
dc.DrawLine(x,self.vbookmargin,x,self.maxHeight-self.vbookmargin)
dc.SetPen(oldpen)
x-=(ch_w+self.vlinespace/2)
self.curPageTextList.append(ptxtlist[line])
delta+=len(ptxtlist[line][0])+ptxtlist[line][1]
line+=1
self.current_pos=self.start_pos
self.start_pos-=delta
i=len(elist)-1
while i>=0:
self.curPageTextList.append(elist[i])
i-=1
dc.EndDrawing()
memory = wx.MemoryDC( )
x,y = self.GetClientSizeTuple()
self.buffer_bak = wx.EmptyBitmap( x,y, -1 )
memory.SelectObject( self.buffer_bak )
memory.Blit( 0,0,x,y, dc, 0,0)
memory.SelectObject( wx.NullBitmap)
def toVBook(self,instr):
"""
将instr转换为适合竖排书本显示模式
mode:
1:将标点符号变成竖排标点
2:去掉所有标点,只留竖排︒
"""
if self.vbookpunc==True:
h2v={
u'.':u'\ufe12',
u'。':u'\ufe12',
u',':u'\ufe10',
u',':u'\ufe10',
u'、':u'\ufe11',
u':':u'\ufe13',
u':':u'\ufe13',
u';':u'\ufe14',
u';':u'\ufe14',
u'!':u'\ufe15',
u'!':u'\ufe15',
u'?':u'\ufe16',
u'?':u'\ufe16',
u'“':u'\ufe17',
u'”':u'\ufe18',
u"‘":u'\ufe17',
u'’':u'\ufe18',
u'\u2026':u'\ufe19',
}
else:
h2v={
u'.':u'\ufe12',
u'。':u'\ufe12',
u',':u'',
u',':u'',
u'、':u'',
u':':u'',
u':':u'',
u';':u'',
u';':u'',
u'!':u'',
u'!':u'',
u'?':u'',
u'?':u'',
u'“':u'',
u'”':u'',
u"‘":u'',
u'’':u'',
u'\u2026':u'',
}
tovb_table = dict((ord(char),h2v[char]) for char in h2v.keys())
return instr.translate(tovb_table)
def SetVbookpunc(self,mode):
self.vbookpunc=mode
class MyTestFrame(wx.Frame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame.__init__
kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.Maximize(True)
# Tool Bar
self.frame_1_toolbar = wx.ToolBar(self, -1)
self.SetToolBar(self.frame_1_toolbar)
# Tool Bar end
self.frame_1_statusbar = self.CreateStatusBar(1, 0)
# Menu Bar
self.frame_1_menubar = wx.MenuBar()
wxglade_tmp_menu = wx.Menu()
wxglade_tmp_menu.Append(101, u"关于(&A)", u"关于本程序", wx.ITEM_NORMAL)
self.frame_1_menubar.Append(wxglade_tmp_menu, "item")
self.SetMenuBar(self.frame_1_menubar)
# Menu Bar end
self.Bind(wx.EVT_MENU, self.Menu101, id=101)
self.__set_properties()
self.panel_1 = LiteView(self)
self.__do_layout()
def Menu101(self,evt):
self.ShowFullScreen(True,wx.FULLSCREEN_ALL)
# end wxGlade
def __set_properties(self):
self.frame_1_toolbar.Realize()
self.frame_1_statusbar.SetStatusWidths([-1])
# statusbar fields
frame_1_statusbar_fields = ["frame_1_statusbar"]
for i in range(len(frame_1_statusbar_fields)):
self.frame_1_statusbar.SetStatusText(frame_1_statusbar_fields[i], i)
# end wxGlade
def __do_layout(self):
# begin wxGlade: MyFrame.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_1.Add(self.panel_1, 1, wx.EXPAND, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
# end wxGlade
# end of class MyFrame
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = MyTestFrame(None, -1, "")
app.SetTopWindow(frame_1)
frame_1.Show()
if len(sys.argv)<=1:
fp=open("3.txt",'r')
else:
fp=open(sys.argv[1],'r')
alltxt=fp.read()
alltxt=alltxt.decode('gbk','ignore')
if len(sys.argv)<=2:
frame_1.panel_1.SetImgBackground('6.jpg')
pass
else:
frame_1.panel_1.SetImgBackgroup(sys.argv[2])
if len(sys.argv)<=3:
frame_1.panel_1.SetShowMode('paper')
else:
frame_1.panel_1.SetShowMode(sys.argv[3])
frame_1.panel_1.SetValue(alltxt)
frame_1.panel_1.SetShowMode('vbook')
frame_1.panel_1.SetSpace(vbookmargin=1)
## frame_1.panel_1.Refresh()
## frame_1.panel_1.Update()
app.MainLoop()
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,258
|
hujun-open/litebook
|
refs/heads/master
|
/jf.py
|
#!/usr/bin/env py32
# -*- coding: utf-8 -*-
#
import codecs
import os.path
import sys
rpath=os.path.abspath(sys.argv[0])
rpath=os.path.dirname(rpath)
rpath=os.path.join(rpath,'jf.dat')
jfdb=codecs.open(rpath,'r','utf-8')
j2f=f2j={}
for line in jfdb:
j,f=line.strip().split()
j2f[j]=f
f2j[f]=j
j2ftable = dict((ord(char),j2f[char]) for char in j2f.keys())
f2jtable = dict((ord(char),f2j[char]) for char in f2j.keys())
def jtof(instr):
"""
instr must be unicode
"""
return instr.translate(j2ftable)
def ftoj(instr):
"""
instr must be unicode
"""
return instr.translate(f2jtable)
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,259
|
hujun-open/litebook
|
refs/heads/master
|
/web_download_manager.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Sun Jul 08 15:59:49 2012
import wx
import wx.lib.newevent
import fileDownloader
import urlparse
import sys
import os
import thread
import traceback
import urllib
import platform
import os
# begin wxGlade: extracode
# end wxGlade
(DownloadReport,EVT_DRA)=wx.lib.newevent.NewEvent()
#(DownloadUpdateAlert,EVT_DUA)=wx.lib.newevent.NewEvent()
MYOS = platform.system()
def cur_file_dir():
#获取脚本路径
global MYOS
if MYOS == 'Linux':
path = sys.path[0]
elif MYOS == 'Windows':
return os.path.dirname(os.path.abspath(sys.argv[0]))
else:
if sys.argv[0].find('/') != -1:
path = sys.argv[0]
else:
path = sys.path[0]
if isinstance(path,str):
path=path.decode('utf-8')
#判断为脚本文件还是py2exe编译后的文件,如果是脚本文件,则返回的是脚本的目录,如果是编译后的文件,则返回的是编译后的文件路径
if os.path.isdir(path):
return path
elif os.path.isfile(path):
return os.path.dirname(path)
##def HumanSize(ffsize):
## fsize=float(ffsize)
## if fsize >= 1000000000.0:
## r=float(fsize)/1000000000.0
## return '%(#).2f' % {'#':r}+' GB'
## else:
## if fsize>=1000000:
## r=float(fsize)/1000000.0
## return '%(#).2f' % {'#':r}+' MB'
## else:
## if fsize>=1000:
## r=float(fsize)/1000.0
## return '%(#).2f' % {'#':r}+' KB'
## else:
## return '< 1KB'
class WebDownloadManager(wx.Frame):
def __init__(self,parent):
"""
savepath is the directory save the download file
"""
# begin wxGlade: DownloadManager.__init__
#kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, parent,-1)
self.sizer_4_staticbox = wx.StaticBox(self, -1, "")
self.sizer_3_staticbox = wx.StaticBox(self, -1, u"当前任务")
self.list_ctrl_1 = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
#self.button_8 = wx.Button(self, -1, u"添加")
self.btn_del = wx.Button(self,wx.ID_DELETE,label=u'删除')
self.btn_cancel = wx.Button(self,wx.ID_CANCEL,label=u'取消')
self.tasklist = {}
##
## self.Bind(EVT_DRA,self.updateProgress)
self.Bind(wx.EVT_BUTTON, self.onClose, self.btn_cancel)
self.Bind(wx.EVT_BUTTON, self.onDel, self.btn_del)
## self.Bind(wx.EVT_BUTTON, self.inputURL, self.button_8)
self.Bind(wx.EVT_CLOSE,self.onClose)
## self.list_ctrl_1.Bind(wx.EVT_LIST_ITEM_SELECTED,self.onSelect)
self.__set_properties()
self.__do_layout()
# end wxGlade
def __set_properties(self):
# begin wxGlade: DownloadManager.__set_properties
_icon = wx.EmptyIcon()
_icon.CopyFromBitmap(wx.Bitmap(cur_file_dir()+u"/icon/litebook-icon_32x32.png", wx.BITMAP_TYPE_ANY))
self.SetIcon(_icon)
self.SetTitle(u"WEB下载管理器")
self.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
self.list_ctrl_1.InsertColumn(0,u'书名',width=200)
self.list_ctrl_1.InsertColumn(1,u'网址',width=300)
self.list_ctrl_1.InsertColumn(2,u'进度')
self.list_ctrl_1.InsertColumn(3,u'大小')
self.SetSize((700,400))
# end wxGlade
def __do_layout(self):
# begin wxGlade: DownloadManager.__do_layout
sizer_2 = wx.BoxSizer(wx.VERTICAL)
sizer_4 = wx.StaticBoxSizer(self.sizer_4_staticbox, wx.HORIZONTAL)
sizer_3 = wx.StaticBoxSizer(self.sizer_3_staticbox, wx.HORIZONTAL)
sizer_3.Add(self.list_ctrl_1, 1, wx.EXPAND, 0)
sizer_2.Add(sizer_3, 1, wx.EXPAND, 0)
sizer_4.Add((20, 20), 1, 0, 0)
sizer_4.Add(self.btn_del, 0,0, 0)
sizer_4.Add((20, 20), 0,0, 0)
sizer_4.Add(self.btn_cancel, 0,0, 0)
sizer_2.Add(sizer_4, 0, wx.EXPAND|wx.ALIGN_CENTER_VERTICAL, 5)
self.SetSizer(sizer_2)
#sizer_2.Fit(self)
self.Layout()
# end wxGlade
def addTask(self,task):
ti=self.list_ctrl_1.InsertStringItem(sys.maxint,task['bkname'])
#self.list_ctrl_1.SetItemData(ti,task['url'])
self.list_ctrl_1.SetStringItem(ti,1,task['url'])
self.list_ctrl_1.SetStringItem(ti,2,u'开始下载...')
self.list_ctrl_1.SetStringItem(ti,3,task['size'])
self.tasklist[task['url']]=[]
def findItem(self,url):
i=-1
while True:
i=self.list_ctrl_1.GetNextItem(i)
if i==-1: return -1
if self.list_ctrl_1.GetItem(i,1).GetText()==url:
return i
def updateProgress(self,msg,url):
item=self.findItem(url)
if item == -1:
return
self.list_ctrl_1.SetStringItem(item,2,msg)
def _delItemviaData(self,data):
i=-1
while True:
i=self.list_ctrl_1.GetNextItem(i)
if i==-1: return False
if self.list_ctrl_1.GetItemData(i)==data:
self.list_ctrl_1.DeleteItem(i)
return i
def onDel(self,evt):
item=-1
item_list=[]
while True:
item=self.list_ctrl_1.GetNextSelected(item)
if item == -1: break
item_list.append(item)
self.delTask(item_list)
def delTask(self,item_list):
for item in item_list:
url=self.list_ctrl_1.GetItem(item,1).GetText()
self.tasklist[url].append(False)
break
self.list_ctrl_1.DeleteItem(item)
def onClose(self,evt):
self.Hide()
# end of class DownloadManager
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = WebDownloadManager(None)
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,260
|
hujun-open/litebook
|
refs/heads/master
|
/ComboDialog.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Thu Jan 13 21:44:56 2011
import wx
# begin wxGlade: extracode
# end wxGlade
class ComboDialog(wx.Dialog):
def __init__(self, parent,ichoice=[],ititle='',idesc=''):
# begin wxGlade: MyDialog.__init__
wx.Dialog.__init__(self, parent=parent,title=ititle)
self.sizer_1_staticbox = wx.StaticBox(self, -1, idesc)
self.combo_box_1 = wx.ComboBox(self, -1, choices=ichoice, style=wx.CB_DROPDOWN)
self.button_1 = wx.Button(self, -1, u" 确定")
self.button_2 = wx.Button(self, -1, u"取消")
self.Bind(wx.EVT_BUTTON,self.OnOK,self.button_1)
self.Bind(wx.EVT_BUTTON,self.OnCancell,self.button_2)
self.__do_layout()
# end wxGlade
def __do_layout(self):
# begin wxGlade: MyDialog.__do_layout
sizer_1 = wx.StaticBoxSizer(self.sizer_1_staticbox, wx.VERTICAL)
sizer_3 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
sizer_2.Add(self.combo_box_1, 1, wx.EXPAND, 0)
sizer_1.Add(sizer_2, 0, wx.EXPAND, 0)
sizer_3.Add(self.button_1, 0, 0, 0)
sizer_3.Add(self.button_2, 0, 0, 0)
sizer_1.Add(sizer_3, 1, wx.EXPAND, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
# end wxGlade
def GetValue(self):
return self.combo_box_1.GetValue()
def OnOK(self,evt):
self.EndModal(wx.ID_OK)
def OnCancell(self,evt):
self.EndModal(wx.ID_CANCEL)
# end of class MyDialog
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
dialog_1 = MyDialog(None, -1, "")
app.SetTopWindow(dialog_1)
dialog_1.Show()
app.MainLoop()
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,261
|
hujun-open/litebook
|
refs/heads/master
|
/UnRAR2/setup.py
|
# setup.py, config file for distutils
import __init__
from distutils.core import setup
from distutils.command.install_data import install_data
import os
class smart_install_data(install_data):
def run(self):
#need to change self.install_dir to the actual library dir
install_cmd = self.get_finalized_command('install')
self.install_dir = getattr(install_cmd, 'install_lib')
return install_data.run(self)
data_files = []
for dirpath, dirnames, filenames in os.walk(r'.'):
for dirname in ['.svn','build', 'dist', '_sgbak', '.hg']:
try:
dirnames.remove(dirname)
except ValueError:
pass
for filename in [fn for fn in filenames if os.path.splitext(fn)[-1].lower() in ('.pyc', '.pyo', '.scc')]:
filenames.remove(filename)
parts = ['UnRAR2']+dirpath.split(os.sep)[1:]
data_files.append((os.path.join(*parts), [os.path.join(dirpath, fn) for fn in filenames]))
setup(name='pyUnRAR2',
version=__init__.__version__,
description='Improved Python wrapper around the free UnRAR.dll',
long_description=__init__.__doc__.strip(),
author='Konstantin Yegupov',
author_email='yk4ever@gmail.com',
url='http://code.google.com/py-unrar2',
license='MIT',
platforms='Windows',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Win32 (MS Windows)',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: Microsoft :: Windows',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System :: Archiving :: Compression',
],
packages=['UnRAR2'],
package_dir={'UnRAR2' : ''},
data_files=data_files,
cmdclass = {'install_data': smart_install_data},
)
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,262
|
hujun-open/litebook
|
refs/heads/master
|
/UnRAR2/unix.py
|
# Copyright (c) 2003-2005 Jimmy Retzlaff, 2008 Konstantin Yegupov
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Unix version uses unrar command line executable
import subprocess
import gc
import os, os.path
import time, re
from rar_exceptions import *
class UnpackerNotInstalled(Exception): pass
rar_executable_cached = None
def call_unrar(params):
"Calls rar/unrar command line executable, returns stdout pipe"
global rar_executable_cached
if rar_executable_cached is None:
for command in ('unrar', 'rar'):
try:
subprocess.Popen([command], stdout=subprocess.PIPE)
rar_executable_cached = command
break
except OSError:
pass
if rar_executable_cached is None:
raise UnpackerNotInstalled("No suitable RAR unpacker installed")
assert type(params) == list, "params must be list"
args = [rar_executable_cached] + params
try:
gc.disable() # See http://bugs.python.org/issue1336
return subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
finally:
gc.enable()
class RarFileImplementation(object):
def init(self, password=None):
self.password = password
stdoutdata, stderrdata = self.call('v', []).communicate()
for line in stderrdata.splitlines():
if line.strip().startswith("Cannot open"):
raise FileOpenError
if line.find("CRC failed")>=0:
raise IncorrectRARPassword
accum = []
source = iter(stdoutdata.splitlines())
line = ''
while not (line.startswith('Comment:') or line.startswith('Pathname/Comment')):
if line.strip().endswith('is not RAR archive'):
raise InvalidRARArchive
line = source.next()
while not line.startswith('Pathname/Comment'):
accum.append(line.rstrip('\n'))
line = source.next()
if len(accum):
accum[0] = accum[0][9:]
self.comment = '\n'.join(accum[:-1])
else:
self.comment = None
def escaped_password(self):
return '-' if self.password == None else self.password
def call(self, cmd, options=[], files=[]):
options2 = options + ['p'+self.escaped_password()]
soptions = ['-'+x for x in options2]
return call_unrar([cmd]+soptions+['--',self.archiveName]+files)
def infoiter(self):
stdoutdata, stderrdata = self.call('v', ['c-']).communicate()
for line in stderrdata.splitlines():
if line.strip().startswith("Cannot open"):
raise FileOpenError
accum = []
source = iter(stdoutdata.splitlines())
line = ''
while not line.startswith('--------------'):
if line.strip().endswith('is not RAR archive'):
raise InvalidRARArchive
if line.find("CRC failed")>=0:
raise IncorrectRARPassword
line = source.next()
line = source.next()
i = 0
re_spaces = re.compile(r"\s+")
while not line.startswith('--------------'):
accum.append(line)
if len(accum)==2:
data = {}
data['index'] = i
data['filename'] = accum[0].strip()
info = re_spaces.split(accum[1].strip())
data['size'] = int(info[0])
attr = info[5]
data['isdir'] = 'd' in attr.lower()
data['datetime'] = time.strptime(info[3]+" "+info[4], '%d-%m-%y %H:%M')
data['comment'] = None
yield data
accum = []
i += 1
line = source.next()
def read_files(self, checker):
res = []
for info in self.infoiter():
checkres = checker(info)
if checkres==True and not info.isdir:
pipe = self.call('p', ['inul'], [info.filename]).stdout
res.append((info, pipe.read()))
return res
def extract(self, checker, path, withSubpath, overwrite):
res = []
command = 'x'
if not withSubpath:
command = 'e'
options = []
if overwrite:
options.append('o+')
else:
options.append('o-')
if not path.endswith(os.sep):
path += os.sep
names = []
for info in self.infoiter():
checkres = checker(info)
if type(checkres) in [str, unicode]:
raise NotImplementedError("Condition callbacks returning strings are deprecated and only supported in Windows")
if checkres==True and not info.isdir:
names.append(info.filename)
res.append(info)
names.append(path)
proc = self.call(command, options, names)
stdoutdata, stderrdata = proc.communicate()
if stderrdata.find("CRC failed")>=0:
raise IncorrectRARPassword
return res
def destruct(self):
pass
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,263
|
hujun-open/litebook
|
refs/heads/master
|
/fileDownloader.py
|
"""Downloads files from http or ftp locations"""
import os
import urllib2
import ftplib
import urlparse
import urllib
import sys
import socket
version = "0.4.0"
class DownloadFile(object):
"""This class is used for downloading files from the internet via http or ftp.
It supports basic http authentication and ftp accounts, and supports resuming downloads.
It does not support https or sftp at this time.
The main advantage of this class is it's ease of use, and pure pythoness. It only uses the Python standard library,
so no dependencies to deal with, and no C to compile.
#####
If a non-standard port is needed just include it in the url (http://example.com:7632).
Basic usage:
Simple
downloader = fileDownloader.DownloadFile('http://example.com/file.zip')
downloader.download()
Use full path to download
downloader = fileDownloader.DownloadFile('http://example.com/file.zip', "C:/Users/username/Downloads/newfilename.zip")
downloader.download()
Basic Authentication protected download
downloader = fileDownloader.DownloadFile('http://example.com/file.zip', "C:/Users/username/Downloads/newfilename.zip", ('username','password'))
downloader.download()
Resume
downloader = fileDownloader.DownloadFile('http://example.com/file.zip')
downloader.resume()
"""
def __init__(self, url, localFileName=None, auth=None, timeout=120.0, autoretry=False, retries=5):
"""Note that auth argument expects a tuple, ('username','password')"""
self.url = url
self.urlFileName = None
self.progress = 0
self.fileSize = None
self.localFileName = localFileName
self.type = self.getType()
self.auth = auth
self.timeout = timeout
self.retries = retries
self.curretry = 0
self.cur = 0
try:
self.urlFilesize = self.getUrlFileSize()
except:
self.urlFilesize = False
self.stopsign = False
if not self.localFileName: #if no filename given pulls filename from the url
self.localFileName = self.getUrlFilename(self.url)
def __downloadFile__(self, urlObj, fileObj, callBack=None,reportFunc=None,curSize=0):
"""starts the download loop"""
self.fileSize = self.getUrlFileSize()
if self.fileSize == False:
reportFunc(False,False)
cur_size=curSize
while 1:
if self.stopsign==True:
fileObj.close()
break
try:
data = urlObj.read(8192)
except (socket.timeout, socket.error) as t:
#print "caught ", t
self.__retry__()
break
cur_size+=len(data)
if reportFunc != None:
reportFunc(cur_size,self.fileSize)
if not data:
fileObj.close()
reportFunc(-1,self.fileSize)#-1 means finished
break
fileObj.write(data)
self.cur += 8192
if callBack:
callBack(cursize=self.cur)
def __retry__(self):
"""auto-resumes up to self.retries"""
if self.retries > self.curretry:
self.curretry += 1
if self.getLocalFileSize() != self.urlFilesize:
self.resume()
else:
print 'retries all used up'
return False, "Retries Exhausted"
def __authHttp__(self):
"""handles http basic authentication"""
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
# this creates a password manager
passman.add_password(None, self.url, self.auth[0], self.auth[1])
# because we have put None at the start it will always
# use this username/password combination for urls
authhandler = urllib2.HTTPBasicAuthHandler(passman)
# create the AuthHandler
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
def __authFtp__(self):
"""handles ftp authentication"""
ftped = urllib2.FTPHandler()
ftpUrl = self.url.replace('ftp://', '')
req = urllib2.Request("ftp://%s:%s@%s"%(self.auth[0], self.auth[1], ftpUrl))
req.timeout = self.timeout
ftpObj = ftped.ftp_open(req)
return ftpObj
def __startHttpResume__(self, restart=None, callBack=None, reportFunc=None):
"""starts to resume HTTP"""
#print "start http resume"
curSize = self.getLocalFileSize()
self.cur = curSize
if restart:
f = open(self.localFileName , "wb")
else:
f = open(self.localFileName , "ab")
if self.auth:
self.__authHttp__()
#print "url is ",self.url
req = urllib2.Request(self.url)
#print " i am here"
urlSize=self.getUrlFileSize()
#print curSize,'----',urlSize
if float(curSize)>=float(urlSize):
#print "already downloaded"
reportFunc(-1,urlSize)
return
req.headers['Range'] = 'bytes=%s-%s' % (curSize, urlSize)
urllib2Obj = urllib2.urlopen(req, timeout=self.timeout)
self.__downloadFile__(urllib2Obj, f, callBack=callBack,reportFunc=reportFunc,curSize=curSize)
def __startFtpResume__(self, restart=None):
"""starts to resume FTP"""
if restart:
f = open(self.localFileName , "wb")
else:
f = open(self.localFileName , "ab")
ftper = ftplib.FTP(timeout=60)
parseObj = urlparse.urlparse(self.url)
baseUrl= parseObj.hostname
urlPort = parseObj.port
bPath = os.path.basename(parseObj.path)
gPath = parseObj.path.replace(bPath, "")
unEncgPath = urllib.unquote(gPath)
fileName = urllib.unquote(os.path.basename(self.url))
ftper.connect(baseUrl, urlPort)
ftper.login(self.auth[0], self.auth[1])
if len(gPath) > 1:
ftper.cwd(unEncgPath)
ftper.sendcmd("TYPE I")
ftper.sendcmd("REST " + str(self.getLocalFileSize()))
downCmd = "RETR "+ fileName
ftper.retrbinary(downCmd, f.write)
def getUrlFilename(self, url):
"""returns filename from url"""
return urllib.unquote(os.path.basename(url))
def getUrlFileSize(self):
"""gets filesize of remote file from ftp or http server"""
if self.type == 'http':
if self.auth:
authObj = self.__authHttp__()
urllib2Obj = urllib2.urlopen(self.url, timeout=self.timeout)
size = urllib2Obj.headers.get('content-length')
#print "url size is ",size
return size
def getLocalFileSize(self):
"""gets filesize of local file"""
size = os.stat(self.localFileName).st_size
#print "the local size of ",self.localFileName," is ",size
return size
def getType(self):
"""returns protocol of url (ftp or http)"""
type = urlparse.urlparse(self.url).scheme
return type
def checkExists(self):
"""Checks to see if the file in the url in self.url exists"""
if self.auth:
if self.type == 'http':
authObj = self.__authHttp__()
try:
urllib2.urlopen(self.url, timeout=self.timeout)
except urllib2.HTTPError:
return False
return True
elif self.type == 'ftp':
return "not yet supported"
else:
urllib2Obj = urllib2.urlopen(self.url, timeout=self.timeout)
try:
urllib2.urlopen(self.url, timeout=self.timeout)
except urllib2.HTTPError:
return False
return True
def download(self, callBack=None,reportFunc=None):
"""starts the file download"""
self.stopsign=False
self.curretry = 0
self.cur = 0
if not isinstance(self.localFileName,unicode):
outfname=self.localFileName.decode('utf-8')
else:
outfname = self.localFileName
f = open(outfname , "wb")
if self.auth:
if self.type == 'http':
self.__authHttp__()
try:
urllib2Obj = urllib2.urlopen(self.url, timeout=self.timeout)
self.__downloadFile__(urllib2Obj, f, callBack=callBack,reportFunc=reportFunc)
except:
reportFunc(False,False)
return False
elif self.type == 'ftp':
self.url = self.url.replace('ftp://', '')
authObj = self.__authFtp__()
self.__downloadFile__(authObj, f, callBack=callBack,reportFunc=reportFunc)
else:
try:
urllib2Obj = urllib2.urlopen(self.url, timeout=self.timeout)
self.__downloadFile__(urllib2Obj, f, callBack=callBack,reportFunc=reportFunc)
except:
reportFunc(False,False)
return False
return True
def resume(self, callBack=None,reportFunc=None):
"""attempts to resume file download"""
self.stopsign=False
type = self.getType()
if type == 'http':
try:
self.__startHttpResume__(callBack=callBack,reportFunc=reportFunc)
except Exception as inst:
#print inst
reportFunc(False,False)
return False
elif type == 'ftp':
self.__startFtpResume__()
def stop(self):
self.stopsign = True
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,264
|
hujun-open/litebook
|
refs/heads/master
|
/plugin/www.23xsw.net.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#-------------------------------------------------------------------------------
# Name: litebook plugin for www.ranwen.net
# Purpose:
#
# Author:
#
# Created: 02/01/2013
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import platform
import sys
import re, htmlentitydefs
MYOS = platform.system()
osarch=platform.architecture()
if osarch[1]=='ELF' and MYOS == 'Linux':
sys.path.append('..')
if osarch[0]=='64bit':
from lxml_linux_64 import html
elif osarch[0]=='32bit':
# from lxml_linux import etree
from lxml_linux import html
elif MYOS == 'Darwin':
from lxml_osx import html
else:
from lxml import html
#import lxml.html
import urlparse
import urllib2
import time
import re
import wx
import thread
import threading
import htmlentitydefs
import urllib
import Queue
from datetime import datetime
Description=u"""支持的网站: http://www.23xsw.net/
插件版本:1.0
发布时间: TBD
简介:
- 支持多线程下载
- 关键字大于2
- 支持HTTP代理
- 支持流看
作者:litebook.author@gmail.com
"""
SearchURL='http://www.23xsw.net/modules/article/search.php'
def myopen(url,post_data=None,useproxy=False,proxyserver='',proxyport=0,proxyuser='',proxypass=''):
interval=10 #number of seconds to wait after fail download attampt
max_retries=3 #max number of retry
retry=0
finished=False
if useproxy:
proxy_info = {
'user' : proxyuser,
'pass' : proxypass,
'host' : proxyserver,
'port' : proxyport
}
proxy_support = urllib2.ProxyHandler({"http" : \
"http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info})
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
if post_data<>None:
myrequest=urllib2.Request(url,post_data)
else:
myrequest=urllib2.Request(url)
#spoof user-agent as IE8 on win7
myrequest.add_header("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)")
while retry<max_retries and finished==False:
try:
fp=urllib2.urlopen(myrequest)
finished=True
except:
retry+=1
time.sleep(interval)
if finished==False:
return None
else:
try:
return fp.read()
except:
return None
def htmname2uni(htm):
if htm[1]=='#':
try:
uc=unichr(int(htm[2:-1]))
return uc
except:
return htm
else:
try:
uc=unichr(htmlentitydefs.name2codepoint[htm[1:-1]])
return uc
except:
return htm
def unescape(text):
# Removes HTML or XML character references and entities from a text string.
#
# @param text The HTML (or XML) source text.
# @return The plain text, as a Unicode string, if necessary.
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except ValueError:
pass
else:
# named entity
try:
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
return re.sub("&#?\w+;", fixup, text)
def htm2txt(inf):
""" extract the text context"""
doc=html.document_fromstring(inf)
content=doc.xpath('//*[@id="contents"]')
htmls=html.tostring(content[0],False)
htmls=htmls.replace('<br>','\n')
htmls=htmls.replace('<p>','\n')
htmls=unescape(htmls)
p=re.compile('\n{2,}') #replace more than 2 newlines in a row into one newline
htmls=p.sub('\n',htmls)
newdoc=html.document_fromstring(htmls)
return newdoc.text_content()
class NewDThread:
def __init__(self,Q,useproxy=False,proxyserver='',proxyport=0,proxyuser='',proxypass='',tr=[],cv=None):
self.Q=Q
self.proxyserver=proxyserver
self.proxyport=proxyport
self.proxyuser=proxyuser
self.proxypass=proxypass
self.useproxy=useproxy
self.tr=tr
self.cv=cv
thread.start_new_thread(self.run, ())
def run(self):
while True:
try:
task=self.Q.get(False)
except:
return
self.cv.acquire()
self.tr[task['index']]=htm2txt(myopen(task['url'],post_data=None,
useproxy=self.useproxy,
proxyserver=self.proxyserver,proxyport=self.proxyport,
proxyuser=self.proxyuser,proxypass=self.proxypass))
self.cv.release()
self.Q.task_done()
def get_search_result(url,key,useproxy=False,proxyserver='',proxyport=0,proxyuser='',proxypass=''):
#get search result web from url by using key as the keyword
#this only apply for POST
#return None when fetch fails
if useproxy:
proxy_info = {
'user' : proxyuser,
'pass' : proxypass,
'host' : proxyserver,
'port' : proxyport # or 8080 or whatever
}
proxy_support = urllib2.ProxyHandler({"http" : \
"http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info})
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)
# install it
urllib2.install_opener(opener)
if isinstance(key,unicode):
key=key.encode("GBK")
post_data=urllib.urlencode({u"searchkey":key,u'searchtype':'articlename'})
myrequest=urllib2.Request(url,post_data)
#spoof user-agent as IE8 on win7
myrequest.add_header("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)")
try:
rr=urllib2.urlopen(myrequest)
return rr.read()
except Exception as inst:
return None
def GetSearchResults(key,useproxy=False,proxyserver='',proxyport=0,proxyuser='',proxypass=''):
global SearchURL
if key.strip()=='':return []
rlist=[]
page=get_search_result(SearchURL,key,useproxy,proxyserver,proxyport,proxyuser,proxypass)
if page==None:
return None
doc=html.document_fromstring(page)
rtable=doc.xpath('//*[@id="content"]/table')
#get the main table, you could use chrome inspect element to get the xpath. note: for tables, end with /table, dont end with table/tbody because chrome sometime will insert tbody
#you could use chorme extension xpath helper to get correct xpath because sometime chrome inspect element return wrong result
if len(rtable)!=0:
row_list=rtable[0].findall('tr') #get the row list
row_list=row_list[1:] #remove first row of caption
for row in row_list:
r={}
col_list = row.getchildren() #get col list in each row
r['bookname']=col_list[0].xpath('a')[0].text
r['book_index_url']=col_list[1].xpath('a')[0].get('href')
r['book_index_url']=urlparse.urljoin(SearchURL,r['book_index_url'])
r['authorname']=col_list[2].text
r['booksize']=col_list[3].text
r['lastupdatetime']=col_list[4].text
r['bookstatus']=col_list[5].text
rlist.append(r)
return rlist
else:#means the search result is a direct hit, the result page is the book portal page
r={}
try:
r['bookname']=doc.xpath('//*[@id="content"]/dd[1]/h1')[0].text
r['bookstatus']=doc.xpath('//*[@id="at"]/tr[1]/td[3]')[0].text #remove tbody here
r['lastupdatetime']=doc.xpath('//*[@id="at"]/tr[2]/td[3]')[0].text
r['authorname']=doc.xpath('//*[@id="at"]/tr[1]/td[2]')[0].text
r['book_index_url']=doc.xpath("//*[@id='content']/dd[2]/div[@class='fl'][2]/p[@class='btnlinks']/a[@class='read']")[0].get('href')
r['book_index_url']=urlparse.urljoin(SearchURL,r['book_index_url'])
r['booksize']=''
except:
return []
return [r]
return []
def GetBook(url,bkname='',win=None,evt=None,useproxy=False,proxyserver='',
proxyport=0,proxyuser='',proxypass='',concurrent=10,
mode='new',last_chapter_count=0,dmode='down',sevt=None,control=[]):
"""
mode is either 'new' or 'update', default is 'new', update is used to
retrie the updated part
dmode is either 'down' or 'stream'
sevt is the event for stream
if control != [] then download will stop (because list is mutable type, boolean is not)
"""
bb=''
cv=threading.Lock()
if useproxy:
proxy_info = {
'user' : proxyuser,
'pass' : proxypass,
'host' : proxyserver,
'port' : proxyport
}
proxy_support = urllib2.ProxyHandler({"http" : \
"http://%(user)s:%(pass)s@%(host)s:%(port)d" % proxy_info})
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
try:
up=urllib2.urlopen(url)
except:
return None,{'index_url':url}
fs=up.read()
up.close()
doc=html.document_fromstring(fs)
r=doc.xpath('//*[@id="at"]') #get the main table, you could use chrome inspect element to get the xpath
row_list=r[0].findall('tr') #get the row list
clist=[]
for r in row_list:
for col in r.getchildren(): #get col list in each row
for a in col.xpath('a'): #use relative xpath to locate <a>
chapt_name=a.text,
chapt_url=urlparse.urljoin(url,a.get('href'))
clist.append({'cname':chapt_name,'curl':chapt_url})
ccount=len(clist)
if mode=='update':
if ccount<=last_chapter_count:
return '',{'index_url':url}
else:
clist=clist[last_chapter_count:]
ccount=len(clist)
i=0
Q=Queue.Queue()
tr=[]
for c in clist:
Q.put({'url':c['curl'],'index':i})
tr.append(-1)
i+=1
tlist=[]
for x in range(concurrent):
tlist.append(NewDThread(Q,useproxy,proxyserver,proxyport,proxyuser,
proxypass,tr,cv))
i=0
while True:
if control!=[]:
return None, {'index_url':url}
qlen=Q.qsize()
if Q.empty():
Q.join()
break
percent=int((float(ccount-qlen)/float(ccount))*100)
evt.Value=str(percent)+'%'
wx.PostEvent(win,evt)
if dmode=='stream':
if tr[i] != -1:
sevt.value="\n"+clist[i]['cname'][0]+"\n"+tr[i]
wx.PostEvent(win,sevt)
i+=1
time.sleep(1)
i=0
bb=u''
for c in clist:
bb+="\n"+c['cname'][0]+"\n"
bb+=tr[i]
i+=1
if not isinstance(bb,unicode):
bb=bb.decode('GBK','ignore')
evt.Value=u'下载完毕!'
evt.status='ok'
bookstate={}
bookstate['bookname']=bkname
bookstate['index_url']=url
bookstate['last_chapter_name']=clist[-1:][0]['cname'][0]
bookstate['last_update']=datetime.today().strftime('%y-%m-%d %H:%M')
bookstate['chapter_count']=ccount
wx.PostEvent(win,evt)
return bb,bookstate
if __name__ == '__main__':
#GetBook('http://www.ranwen.net/files/article/17/17543/index.html')
#GetSearchResults(u'修真')
GetBook("http://www.23xsw.net/book/2/2445/index.html")
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,265
|
hujun-open/litebook
|
refs/heads/master
|
/download_manager.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6.3 on Sun Jul 08 15:59:49 2012
import wx
import wx.lib.newevent
import fileDownloader
import urlparse
import sys
import os
import thread
import traceback
import urllib
import platform
import os
# begin wxGlade: extracode
# end wxGlade
(DownloadReport,EVT_DRA)=wx.lib.newevent.NewEvent()
MYOS = platform.system()
def cur_file_dir():
#获取脚本路径
global MYOS
if MYOS == 'Linux':
path = sys.path[0]
elif MYOS == 'Windows':
return os.path.dirname(os.path.abspath(sys.argv[0]))
else:
if sys.argv[0].find('/') != -1:
path = sys.argv[0]
else:
path = sys.path[0]
if isinstance(path,str):
path=path.decode('utf-8')
#判断为脚本文件还是py2exe编译后的文件,如果是脚本文件,则返回的是脚本的目录,如果是编译后的文件,则返回的是编译后的文件路径
if os.path.isdir(path):
return path
elif os.path.isfile(path):
return os.path.dirname(path)
def HumanSize(ffsize):
fsize=float(ffsize)
if fsize >= 1000000000.0:
r=float(fsize)/1000000000.0
return '%(#).2f' % {'#':r}+' GB'
else:
if fsize>=1000000:
r=float(fsize)/1000000.0
return '%(#).2f' % {'#':r}+' MB'
else:
if fsize>=1000:
r=float(fsize)/1000.0
return '%(#).2f' % {'#':r}+' KB'
else:
return '< 1KB'
class DownloadManager(wx.Frame):
def __init__(self,parent,savepath='.'):
"""
savepath is the directory save the download file
"""
# begin wxGlade: DownloadManager.__init__
#kwds["style"] = wx.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, parent,-1)
self.sizer_4_staticbox = wx.StaticBox(self, -1, "")
self.sizer_3_staticbox = wx.StaticBox(self, -1, u"当前任务")
self.list_ctrl_1 = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
self.button_8 = wx.Button(self, -1, u"添加")
self.button_9 = wx.Button(self, -1, u"删除")
self.button_10 = wx.Button(self, -1, u"继续下载")
self.button_11 = wx.Button(self, -1, u"暂停")
self.tasklist = {}
self.savepath=savepath
self.Bind(EVT_DRA,self.updateProgress)
self.Bind(wx.EVT_BUTTON, self.resumeDownloading, self.button_10)
self.Bind(wx.EVT_BUTTON, self.stopDownloading, self.button_11)
self.Bind(wx.EVT_BUTTON, self.delTask, self.button_9)
self.Bind(wx.EVT_BUTTON, self.inputURL, self.button_8)
self.Bind(wx.EVT_CLOSE,self.OnClose)
self.list_ctrl_1.Bind(wx.EVT_LIST_ITEM_SELECTED,self.onSelect)
self.__set_properties()
self.__do_layout()
# end wxGlade
def __set_properties(self):
# begin wxGlade: DownloadManager.__set_properties
_icon = wx.EmptyIcon()
_icon.CopyFromBitmap(wx.Bitmap(cur_file_dir()+u"/icon/litebook-icon_32x32.png", wx.BITMAP_TYPE_ANY))
self.SetIcon(_icon)
self.SetTitle(u"下载管理器")
self.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
self.list_ctrl_1.InsertColumn(0,u'文件名',width=200)
self.list_ctrl_1.InsertColumn(1,u'URL',width=300)
self.list_ctrl_1.InsertColumn(2,u'进度')
self.list_ctrl_1.InsertColumn(3,u'大小')
self.SetSize((700,400))
# end wxGlade
def __do_layout(self):
# begin wxGlade: DownloadManager.__do_layout
sizer_2 = wx.BoxSizer(wx.VERTICAL)
sizer_4 = wx.StaticBoxSizer(self.sizer_4_staticbox, wx.HORIZONTAL)
sizer_3 = wx.StaticBoxSizer(self.sizer_3_staticbox, wx.HORIZONTAL)
sizer_3.Add(self.list_ctrl_1, 1, wx.EXPAND, 0)
sizer_2.Add(sizer_3, 1, wx.EXPAND, 0)
sizer_4.Add((20, 20), 1, 0, 0)
sizer_4.Add(self.button_8, 0, 0, 0)
sizer_4.Add((20, 20), 0, 0, 0)
sizer_4.Add(self.button_9, 0, 0, 0)
sizer_4.Add((20, 20), 0, 0, 0)
sizer_4.Add(self.button_10, 0, 0, 0)
sizer_4.Add((20, 20), 0, 0, 0)
sizer_4.Add(self.button_11, 0, 0, 0)
sizer_4.Add((20, 20), 1, 0, 0)
sizer_2.Add(sizer_4, 0, wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
self.SetSizer(sizer_2)
#sizer_2.Fit(self)
self.Layout()
# end wxGlade
def addTask(self,url,savepath=None):
"""
return False if invalid url
"""
newurl=url
if newurl[:7].lower() != 'http://':
newurl='http://'+newurl
purl=urlparse.urlparse(newurl)
if purl.netloc=='' or purl.scheme <>'http' or purl.path == '':
return False
for t in self.tasklist.values():
if t['url'] == newurl: return
if savepath==None:
savepath=self.savepath
fname = str(os.path.basename(urlparse.urlparse(newurl).path))
fname = urllib.unquote_plus(fname).decode('utf-8')
ti=self.list_ctrl_1.InsertStringItem(sys.maxint,fname)
self.list_ctrl_1.SetItemData(ti,ti)
self.list_ctrl_1.SetStringItem(ti,1,newurl)#url
self.list_ctrl_1.SetStringItem(ti,2,u'开始下载')#cur
self.list_ctrl_1.SetStringItem(ti,3,'0')#total
localname=os.path.abspath(savepath+os.sep+fname)
dt=DThread(self,newurl,ti,localname)
## print "add ",newurl,"as ",ti
self.tasklist[ti]={'url':newurl,'thread':dt,'localname':localname}
return True
def updateProgress(self,evt):
if evt.current_size == False or evt.total_size == False:
self.list_ctrl_1.SetStringItem(evt.tid,2,u'失败')
self.list_ctrl_1.SetStringItem(evt.tid,3,u'失败')
self.Refresh()
return
if evt.current_size==-1:
self.list_ctrl_1.SetStringItem(evt.tid,2,u'完成')
self.updateButtonStatus()
else:
self.list_ctrl_1.SetStringItem(evt.tid,2,HumanSize(evt.current_size))
self.list_ctrl_1.SetStringItem(evt.tid,3,HumanSize(evt.total_size))
self.Refresh()
def resumeDownloading(self,evt):
item=-1
while True:
item=self.list_ctrl_1.GetNextSelected(item)
if item == -1: return
dt=DThread(self,self.tasklist[item]['url'],item,self.tasklist[item]['localname'])
self.tasklist[item]['thread']=dt
if self.list_ctrl_1.GetItem(item,2).GetText()!=u'失败':
self.button_10.Disable()
self.button_11.Enable()
self.list_ctrl_1.SetStringItem(item,2,u'开始下载')#cur
self.list_ctrl_1.SetStringItem(item,3,u'0')#total
def stopDownloading(self,evt):
item=-1
while True:
item=self.list_ctrl_1.GetNextSelected(item)
if item == -1: return
self.tasklist[item]['thread'].stop()
self.button_11.Disable()
if self.list_ctrl_1.GetItem(item,2).GetText()==u'完成':
self.button_10.Disable()
else:
self.button_10.Enable()
def updateButtonStatus(self):
selected_item=self.list_ctrl_1.GetNextSelected(-1)
if selected_item == -1:return
task_id=self.list_ctrl_1.GetItemData(selected_item)
if self.tasklist[task_id]['thread'].running == True:
self.button_10.Disable()
self.button_11.Enable()
else:
self.button_11.Disable()
if self.list_ctrl_1.GetItem(selected_item,2).GetText()==u'完成':
self.button_10.Disable()
else:
self.button_10.Enable()
self.Refresh()
self.Update()
def printlist(self):
i=-1
print "*******************"
while True:
i=self.list_ctrl_1.GetNextSelected(i)
if i==-1:return
print i,'----',self.list_ctrl_1.GetItemData(i)
def _delItemviaData(self,data):
i=-1
while True:
i=self.list_ctrl_1.GetNextItem(i)
if i==-1: return False
if self.list_ctrl_1.GetItemData(i)==data:
self.list_ctrl_1.DeleteItem(i)
return i
def delTask(self,evt):
item=-1
s_list=[]
while True:
item=self.list_ctrl_1.GetNextSelected(item)
if item == -1: break
else:
s_list.append(item)
for data in s_list:
self.tasklist[data]['thread'].stop()
self._delItemviaData(data)
## self.button_11.Disable()
## if self.list_ctrl_1.GetItem(item,2).GetText()==u'完成':
## self.button_10.Disable()
## else:
## self.button_10.Enable()
def inputURL(self,evt):
dlg = wx.TextEntryDialog(
self, u'请输入地址:',
u'添加下载任务', '')
if dlg.ShowModal() == wx.ID_OK:
if self.addTask(dlg.GetValue()) == False:
mdlg = wx.MessageDialog(self,u'错误的HTTP URL!',
u'出错了!',
wx.OK | wx.ICON_ERROR
)
mdlg.ShowModal()
mdlg.Destroy()
dlg.Destroy()
def onSelect(self,evt):
self.updateButtonStatus()
def OnClose(self,evt):
self.Hide()
# end of class DownloadManager
class DThread:
def __init__(self,win,url,id,savename):
self.win=win
self.url=url
self.tid = id
self.savename=savename
self.running=False
thread.start_new_thread(self.run, ())
def report(self,cur,all):
"""
report download progress via wx.PostEvent
"""
new_evt=DownloadReport(current_size=cur,total_size=all,tid=self.tid)
wx.PostEvent(self.win,new_evt)
def run(self):
self.running=True
self.downloader=fileDownloader.DownloadFile(self.url,localFileName=self.savename)
if self.running == False: return
try:
if os.path.isfile(self.savename):
self.downloader.resume(reportFunc=self.report)
else:
self.downloader.download(reportFunc=self.report)
except Exception as inst:
print traceback.format_exc()
print inst
self.running=False
def stop(self):
try:
self.downloader.stop()
except:
pass
self.running=False
if __name__ == "__main__":
app = wx.PySimpleApp(0)
wx.InitAllImageHandlers()
frame_1 = DownloadManager(None)
#frame_1.addTask('http://litebook-project.googlecode.com/files/LiteBook2_v2d.1_Win_setup.exe','.')
#frame_1.addTask('http://127.0.0.1:8000/%E5%86%92%E7%89%8C%E5%A4%A7%E8%8B%B1%E9%9B%84.epub','.')
frame_1.addTask('http://10.10.10.10:8000/1.epub','.')
frame_1.addTask('http://20.20.20.20:8000/2.epub','.')
frame_1.addTask('http://30.30.30.30:8000/3.epub','.')
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,266
|
hujun-open/litebook
|
refs/heads/master
|
/build.py
|
from distutils.core import setup
import glob
import py2exe
import os,sys
import shutil
def myignore(src,name):
return (['.svn',])
sys.argv.append('py2exe')
setup(windows=[{'script':'litebook.py',"icon_resources": [(1, "litebook.ico")]},],
data_files=[('templates', glob.glob('templates/*.*')),
('UnRAR2', glob.glob('UnRAR2/*.*')),
('icon', glob.glob('icon/*.*')),
('background', glob.glob('background/*.*')),
('plugin', glob.glob('plugin/*.py')),
"litebook.exe.manifest",
"litebook.ico","unrar.dll","bh.dat","py.dat","defaultconfig.ini",
"Readme.txt",
"LTBNET_Readme.txt",
"jf.dat",
],
options = {'py2exe': {'bundle_files': 3,'compressed':False,'optimize':2,
'includes': ['lxml.etree',
'lxml._elementpath',
'lxml.html',
'bs4',
'gzip',
'download_manager',
'ctypes.*',
],
'packages':['netifaces',],
"dll_excludes": ["MSVCP90.dll"],
'excludes': [
"pywin", "pywin.debugger", "pywin.debugger.dbgcon",
"pywin.dialogs", "pywin.dialogs.list",
"Tkconstants","Tkinter","tcl",
"jieba",
],
},
},
zipfile = "lib/library.zip",
)
shutil.copytree('helpdoc','.\\dist\\helpdoc',ignore=myignore)
|
{"/UnRAR2/test_UnRAR2.py": ["/UnRAR2/__init__.py"], "/web_download_manager.py": ["/fileDownloader.py"]}
|
14,274
|
Prakyathkantharaju/sokobanAI
|
refs/heads/master
|
/Agents/utils.py
|
MAXIMUM_FLOAT_VALUE = float('inf')
class MinMaxStats(object):
"""A class that holds the min-max values of the tree."""
def __init__(self, known_bounds):
self.maximum = known_bounds.max if known_bounds else -MAXIMUM_FLOAT_VALUE
self.minimum = known_bounds.min if known_bounds else MAXIMUM_FLOAT_VALUE
def update(self, value: float):
if value is None:
raise ValueError
self.maximum = max(self.maximum, value)
self.minimum = min(self.minimum, value)
def normalize(self, value: float) -> float:
# If the value is unknow, by default we set it to the minimum possible value
if value is None:
return 0.0
if self.maximum > self.minimum:
# We normalize only when we have set the maximum and minimum values.
return (value - self.minimum) / (self.maximum - self.minimum)
return value
|
{"/Agents/examples/Random_Sampling.py": ["/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"], "/Agents/MCTS/MainMCTS.py": ["/Agents/utils.py", "/Agents/MCTS/utils.py", "/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"]}
|
14,275
|
Prakyathkantharaju/sokobanAI
|
refs/heads/master
|
/Agents/DDQN/main.py
|
# general import
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import time, sys
# relative import
sys.path.append('/home/prakyath/gitfolder/sokoban')
from Agents.DDQN.Agent import Agent
import gym
import gym_sokoban
if __name__ == '__main__':
tf.compat.v1.disable_eager_execution()
fig, ax = plt.subplots(2,1)
env_name = 'Sokoban-v0'
env = gym.make(env_name)
lr = 0.01
n_games = 500
action_space = 9
observation_space = np.array([10*10])
agent = Agent(gamma=0.99, epsilon=1.0, lr=lr,
input_dims=observation_space,
n_actions= action_space, mem_size=1000000, batch_size= 3000, epsilon_end=0.01, fname = 'models/new_model.h5')
# agent.load_model()
score_history = []
epsilon_history = []
test_score = [0]
test_history = []
main_done = False
local_done = False
for n in range(n_games):
main_counter = 0
store_local = []
global_done = False
env.reset()
main_counter += 1
score = 0
local_done = False
observation, reward, local_done ,info = env.step(1,observation_mode = 'custom',weight_method = 'custom')
observation = observation.flatten()
counter = 0
while not local_done:
counter += 1
action = agent.choose_action(observation)
observation_, reward, local_done ,info = env.step(action,observation_mode = 'custom', weight_method = 'custom')
temp = observation_
observation_ = observation_.flatten()
score += reward
agent.store_transition(observation, action, reward, observation_, local_done)
observation = observation_
agent.learn()
print(temp)
store_local.append(score/counter)
score_history.append(np.mean(store_local[:-10]))
print('main counter: {}, part counter: {}, epsilon {}, avg score: {}'.format(n,counter,\
agent.epsilon,np.mean(store_local)))
agent.save_model()
|
{"/Agents/examples/Random_Sampling.py": ["/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"], "/Agents/MCTS/MainMCTS.py": ["/Agents/utils.py", "/Agents/MCTS/utils.py", "/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"]}
|
14,276
|
Prakyathkantharaju/sokobanAI
|
refs/heads/master
|
/Agents/examples/Random_Sampling.py
|
import gym
import numpy as np
import gym_sokoban
import time
import os,sys
# realtive import
print(os.getcwd())
sys.path.append('/home/prakyath/gitfolder/sokoban')
from Agents.cost_functions.cost import MSE
from Agents.trees.MainTree import State, Match_state
# Before you can make a Sokoban Environment you need to call:
# import gym_sokoban
# This import statement registers all Sokoban environments
# provided by this package
env_name = 'Sokoban-v0'
env = gym.make(env_name)
mse = MSE()
env.OBSERVATION_SPACE = 1
env.ACTION_SPACE = 8
ACTION_LOOKUP = env.unwrapped.get_action_lookup()
print("Created environment: {}".format(env_name))
print(ACTION_LOOKUP)
prev_state = None
for i_episode in range(1):#20
observation = env.reset()
for t in range(100):#100
env.render(mode='human')
action = env.action_space.sample()
# Sleep makes the actions visible for users
time.sleep(1)
observation, reward, done, info = env.step(action, observation_mode = 'raw')
print(ACTION_LOOKUP[action], reward, done, info)
wall,goals,boxes,player = observation[0],observation[1],observation[2],observation[3]
player = np.argwhere(player == 1)
goals = np.argwhere(goals == 1)
boxes = np.argwhere(boxes == 1)
print('player', player, 'goals', goals, 'boxes', boxes)
new_state = State(env.room_state.flatten())
new_state.add_child(prev_state)
print('matchstate',Match_state(new_state,prev_state))
new_state.add_reward(mse.evaluate(goals,boxes, player))
prev_state = new_state
if done:
print("Episode finished after {} timesteps".format(t+1))
env.render()
break
env.close()
time.sleep(10)
|
{"/Agents/examples/Random_Sampling.py": ["/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"], "/Agents/MCTS/MainMCTS.py": ["/Agents/utils.py", "/Agents/MCTS/utils.py", "/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"]}
|
14,277
|
Prakyathkantharaju/sokobanAI
|
refs/heads/master
|
/Agents/trees/MainTree.py
|
# general imports
import numpy as np
# This file is for state tree construction
# This will have following class/function
# - State: each state class
# - Match_state: function to return true is states are matched
class State(object):
"""State."""
'''
state class
to have child, parent and occurance information
also can add weight
'''
def __init__(self, state):
"""__init__.
:param state:
"""
self.parent = []
self.child = {}
self.state = state
self.visit = 0
self.reward = [0]
self.sum_reward = 0
self.prior = 0
def add_child(self, child, action):
self.child[action] = child
def add_parent(self, parent):
self.parent.append(parent)
def add_visit(self):
self.visit += 1
def add_reward(self, reward):
self.reward.append(reward)
def add_roomstate(self, room_state):
self.room_state = room_state
def get_roomstate(self):
return np.copy(self.room_state)
def value(self):
return self.reward[-1]
def expanded(self):
if len(self.child.values()) == 0:
return True
else:
return False
def Match_state(state1,state2):
'''
function to check if the state1 and state2 match
return
True if they match
False if they do not match
'''
if type(state1) == type(None) or type(state2) == type(None):
return False
comparision = state1.state == state2.state
return comparision.all()
def Search_tree(old_state,new_state):
'''
Search tree function is for searching if the there is a same state before
return (True/False,state) True/False if there exists with state
'''
queue = []
match = None
queue = old_state.child
while len(queue) != 0:
# picking at no particular order
curr_child = queue[0]
queue = queue + curr_child.child
if Match_state(new_state,curr_child):
return True, curr_child
queue.pop(0)
return False, match
|
{"/Agents/examples/Random_Sampling.py": ["/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"], "/Agents/MCTS/MainMCTS.py": ["/Agents/utils.py", "/Agents/MCTS/utils.py", "/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"]}
|
14,278
|
Prakyathkantharaju/sokobanAI
|
refs/heads/master
|
/Agents/cost_functions/cost.py
|
# General import
import numpy as np
# base class
class cost(object):
def __init__(self, no_of_goals = 3):
self.state_number = no_of_goals
def evaluate(self,goals,target,player):
raise NotImplemented
# Mean square error
class MSE(cost):
def __init__(self,no_of_goals = 3, cost_type = 'SUM'):
super().__init__(no_of_goals)
self.type = cost_type
self.no_of_goals = no_of_goals
def evaluate(self,goals, box, player):
weight = 0
if self.type == 'SUM':
# remove FOR loops (OMG I am so bad)
# should get MSE sum of all the weights with respect all the goals
# n goals x n target
x = 0
for i in range(self.no_of_goals):
print(box[i],goals[i])
x += sum([sum((box[j] - goals[i]) * (box[j] - goals[i]).T)
for j in range(self.no_of_goals)])
weight = x
if self.type == 'DIST':
pass
return weight
|
{"/Agents/examples/Random_Sampling.py": ["/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"], "/Agents/MCTS/MainMCTS.py": ["/Agents/utils.py", "/Agents/MCTS/utils.py", "/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"]}
|
14,279
|
Prakyathkantharaju/sokobanAI
|
refs/heads/master
|
/old_env/sokoban_env.py
|
# import general ai
import gym
import numpy as np
# import game
try:
import sokoban.game as game
except:
from env.sokoban_game import game
# this is the gym
class sokoban_env(gym.Env):
def __init__(self,level):
self.game = game('env/levels', level)
self.state = {}
self.state['worker'] = 0
self.state['box'] = 0
self.state['dock'] = 0
# reset
def reset(self):
pass
#need to reset the game and start again
# step
def step(self, action, store = False):
# action :
# left = 1
# right = 2
# top = 3
# bottom = 4
# the True is cause the render will store all the action in the queue
if action == 1:
self.game.move(-1,0,store)
elif action == 2:
self.game.move(1,0,store)
elif action == 3:
self.game.move(0,-1,store)
elif action == 4:
self.game.move(0,1,store)
# render
def render(self):
pass
# render the figure in pygame window
def close(self):
# close the data and also the pygame window is open
pass
def seed(self):
# set the random variable of the data
pass
def observation(self):
# get state of the person and the box
pass
def get_info(self):
# set the number of box, number of open space, number of complete goal
pass
def reward(self):
# calculate the euclidian distance from the goal
pass
def get_state(self):
# dock(s) location
# worker location
# box location
WORKER,BOX,DOCK = self.game.get_state()
WORKER = WORKER[:-1]
state = {}
self.state['worker'] = WORKER
self.state['box'] = BOX
self.state['dock'] = DOCK
print(self.get_weight())
def _state_size(self):
self.get_state()
self.len = 1
self.len += len(self.state['box'])
def get_weight(self,weight_type = 'euclidian', com_type = 'SUM'):
# option of getting weight:
# 'manhattan'
# 'euclidian'
# 'diagonal'
# option to combine weight:
# 'SUM': add all the weight from each dock to box
# 'LEAST': add the least distance from the dock for each box
# 'MEAN': add the weight and divide it by the number of docks
# TODO: need to add different type of weights
weight = 0
if weight_type == 'euclidian':
for i in self.state['box']:
for j in self.state['dock']:
if com_type == 'SUM':
weight += np.sqrt((i[0] - j[0])**2 + (i[1] - j[1])**2)
else:
weight = 0
return weight
|
{"/Agents/examples/Random_Sampling.py": ["/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"], "/Agents/MCTS/MainMCTS.py": ["/Agents/utils.py", "/Agents/MCTS/utils.py", "/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"]}
|
14,280
|
Prakyathkantharaju/sokobanAI
|
refs/heads/master
|
/Agents/MCTS/utils.py
|
import numpy as np
def Match_goal_box(previous_state, new_state):
box_loc = get_box_loc(previous_state) == get_box_loc(new_state)
goal_loc = get_goals_loc(previous_state) == get_box_loc(new_state)
if box_loc.all() and goal_loc.all():
return True
else:
return False
def get_box_loc(state):
prev_box = np.where(state == 4)
prev_box = np.append(prev_box, np.where(state == 3), axis= 1)
return prev_box
def get_goals_loc(state):
prev_goal = np.where(state == 2)
return prev_goal
|
{"/Agents/examples/Random_Sampling.py": ["/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"], "/Agents/MCTS/MainMCTS.py": ["/Agents/utils.py", "/Agents/MCTS/utils.py", "/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"]}
|
14,281
|
Prakyathkantharaju/sokobanAI
|
refs/heads/master
|
/test.py
|
from env.sokoban_env import sokoban_env
env = sokoban_env(1)
env.get_state()
|
{"/Agents/examples/Random_Sampling.py": ["/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"], "/Agents/MCTS/MainMCTS.py": ["/Agents/utils.py", "/Agents/MCTS/utils.py", "/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"]}
|
14,282
|
Prakyathkantharaju/sokobanAI
|
refs/heads/master
|
/Agents/state_queue.py
|
# This class is to store the state and weight for A-star search
class queue(object):
def __init__(self,len_state):
# len_state is the len of the box + worker
self.data = {}
|
{"/Agents/examples/Random_Sampling.py": ["/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"], "/Agents/MCTS/MainMCTS.py": ["/Agents/utils.py", "/Agents/MCTS/utils.py", "/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"]}
|
14,283
|
Prakyathkantharaju/sokobanAI
|
refs/heads/master
|
/Agents/MCTS/MainMCTS.py
|
# Main Monte carlo tree search file
import collections, math
import gym, time
import numpy as np
import gym_sokoban, copy, random
import time, os, sys
print(os.getcwd())
sys.path.append('/home/prakyath/gitfolder/sokoban/')
from Agents.utils import MinMaxStats
from Agents.MCTS.utils import Match_goal_box
# relative imports
from Agents.cost_functions.cost import MSE
from Agents.trees.MainTree import State, Match_state
KnownBounds = collections.namedtuple('KnownBounds', ['min', 'max'])
class MCTS(object):
def __init__(self):
env_name = 'Sokoban-v0'
self.env = gym.make(env_name)
self.mse = MSE()
self.env.render(mode = 'human')
self.env.OBSERVATION_SPACE = 1
self.env.ACTION_SPACE = 8
self.ACTION_LOOKUP = self.env.unwrapped.get_action_lookup()
self.env.reset()
# expansion counter
self.expantion = 0
# term to penalize the if the same state is achieved again and again.
self.cost_append = 0
# action stuck
self.action_stuck = []
def run(self):
# Main run function to controll all the MCTS
# TODO: move left is not working
parent_state = self.env.get_state()
parent_state = State(parent_state)
previous_state = parent_state
room_state = self.env.room_state
parent_state.add_roomstate(room_state)
print(room_state)
parent_state = self.expand(parent_state, room_state)
state_list = [parent_state]
for i in range(100):
current_state = state_list[-1]
self.main_mcts(current_state)
action, child_ = max(current_state.child.items(), key = lambda item: item[1].visit)
for action_list,child in current_state.child.items():
print(action_list,child.visit, 'action and child count')
print(action)
player_position = np.copy(self.env.player_position)
self.env.update_room_state(np.copy(room_state))
print('before')
print(self.env.room_state)
observation, reward, done, info = self.env.step(action,player_position,weight_method = 'custom', print_ = True)
print('after state')
print(self.env.room_state)
child_state = self.env.get_state()
child_state = State(child_state)
child_state.add_roomstate(np.copy(self.env.room_state))
room_state = np.copy(self.env.room_state)
child_state = self.expand(child_state,room_state)
state_list.append(child_state)
time.sleep(1)
print(self.env.get_action_lookup())
if Match_goal_box(previous_state,child_state):
current_state.add_reward(-100)
self.action_stuck = [action]
rand_action = np.random.randint(1,8)
print('applying random action',rand_action)
observation, reward, done, info = self.env.step(rand_action,player_position,weight_method = 'custom', print_ = True)
print('after state')
print(self.env.room_state)
child_state = self.env.get_state()
child_state = State(child_state)
child_state.add_roomstate(np.copy(self.env.room_state))
room_state = np.copy(self.env.room_state)
child_state = self.expand(child_state,room_state)
state_list.append(child_state)
else:
self.cost_append = 0
self.env.render()
previous_state = child_state
# input('test')
def main_mcts(self, root):
min_max_bounds = MinMaxStats(None)
# eenforced exploration
epsilon = np.random.randint(80, size = 80)
print(epsilon)
for i in range(100):
node = root
search_path = [node]
action_history = []
counter = 0
while not(node.expanded()):
if i in epsilon:
action,node = self.select_child(node, min_max_bounds, explore = True)
else:
action, node = self.select_child(node, min_max_bounds)
search_path.append(node)
action_history.append(action)
# if node.expanded() == True:
# print(node.get_roomstate())
# print(len(node.child.values()))
parent = search_path[-2]
room_state = node.get_roomstate()
node = self.expand(node, room_state)
self.backprop(search_path, min_max_bounds)
def select_child(self, node, min_max_stats, explore = False):
if node.visit == 0 or explore == True:
return random.sample(node.child.items(), 1)[0]
else:
t, action, child = \
max((self.ucb_score(node, child, min_max_stats), action, child) \
for action , child in node.child.items())
return action , child
def backprop(self, search_path, min_max_stats):
value = 0
for node in search_path[::-1]:
node.sum_reward += value
min_max_stats.update(node.value())
value = node.value() + 0.99 * value
node.add_visit()
def ucb_score(self, parent, child, min_max_stats):
pb_c = math.log((parent.visit + 19652 + 1) / 19652) + 1.25
pb_c *= math.sqrt(parent.visit) / (child.visit + 1)
prior_score = pb_c * child.prior
value_score = min_max_stats.normalize(child.value())
return prior_score + value_score
def expand_old(self,list_of_actions, state):
self.expantion += 1
# do till the there are no possible action or ten children
while len(list_of_actions) != 0 or self.expantion < 10:
self.env.room_state = state.room_state
new_state = State(self.env.get_state())
new_state.room_state = self.env.room_state
state.add_child(State(self.env.get_state()))
list_of_actions.pop(0)
return state
def expand(self, state, raw_state):
# simulate throught all the 8 actions and select the best one
parent_state = state
player_position = self.env.get_player()
# print('player',player_position.shape)
save_state = copy.deepcopy(raw_state)
test_ = copy.deepcopy(save_state)
list_state = save_state.tolist()
# print(np.where(test_ == 5))
possible_actions = [i for i in range(1,9)]
for i in range(1,9):
action = i
# print('action:',i)
# print('actual player position', np.where(test_ == 5), np.where(save_state == 5),np.where(np.array(list_state) == 5))
self.env.update_room_state(test_)
observation, reward, done, info = self.env.step(action,player_position,weight_method = 'custom',
observation_mode = 'raw')
child_state = self.env.get_state()
child_state = State(child_state)
child_state.add_reward(reward)
child_state.add_roomstate(np.copy(self.env.room_state))
# print(player_position)
parent_state.add_child(child_state, i)
# self.env.render()
return state
def _calculate_cost(self, state):
state = state.room_state.flatten
if "__main__" == __name__:
main_cts = MCTS()
main_cts.run()
|
{"/Agents/examples/Random_Sampling.py": ["/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"], "/Agents/MCTS/MainMCTS.py": ["/Agents/utils.py", "/Agents/MCTS/utils.py", "/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"]}
|
14,284
|
Prakyathkantharaju/sokobanAI
|
refs/heads/master
|
/Agents/test.py
|
import gym
import gym_sokoban
|
{"/Agents/examples/Random_Sampling.py": ["/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"], "/Agents/MCTS/MainMCTS.py": ["/Agents/utils.py", "/Agents/MCTS/utils.py", "/Agents/cost_functions/cost.py", "/Agents/trees/MainTree.py"]}
|
14,306
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/src/pythonia/Bridge.py
|
import inspect, importlib, importlib.util
import json, types, traceback, os, sys
from proxy import Executor, Proxy
from weakref import WeakValueDictionary
def python(method):
return importlib.import_module(method, package=None)
def fileImport(moduleName, absolutePath, folderPath):
if folderPath not in sys.path:
sys.path.append(folderPath)
spec = importlib.util.spec_from_file_location(moduleName, absolutePath)
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
return foo
class Iterate:
def __init__(self, v):
self.what = v
# If we have a normal iterator, we need to make it a generator
if inspect.isgeneratorfunction(v):
it = self.next_gen()
elif hasattr(v, "__iter__"):
it = self.next_iter()
def next_iter():
try:
return next(it)
except Exception:
return "$$STOPITER"
self.Next = next_iter
def next_iter(self):
for entry in self.what:
yield entry
return
def next_gen(self):
yield self.what()
fix_key = lambda key: key.replace("~~", "") if type(key) is str else key
class Bridge:
m = {
0: {
"python": python,
"open": open,
"fileImport": fileImport,
"eval": eval,
"exec": exec,
"setattr": setattr,
"getattr": getattr,
"Iterate": Iterate,
"tuple": tuple,
"set": set,
"enumerate": enumerate,
"repr": repr,
}
}
# Things added to this dict are auto GC'ed
weakmap = WeakValueDictionary()
cur_ffid = 0
def __init__(self, ipc):
self.ipc = ipc
# This toggles if we want to send inspect data for console logging. It's auto
# disabled when a for loop is active; use `repr` to request logging instead.
self.m[0]["sendInspect"] = lambda x: setattr(self, "send_inspect", x)
self.send_inspect = True
self.q = lambda r, key, val, sig="": self.ipc.queue(
{"r": r, "key": key, "val": val, "sig": sig}
)
self.executor = Executor(self)
setattr(os, "JSPyBridge", Proxy(self.executor, 0))
def assign_ffid(self, what):
self.cur_ffid += 1
self.m[self.cur_ffid] = what
return self.cur_ffid
def make_class(this, name, proxy, bases, overriden):
def init(self):
for base_ffid, baseArgs, baseKwargs in bases:
base = this.m[base_ffid]
base.__init__(self, *baseArgs, **baseKwargs)
def getAttribute(self, attr):
if attr.startswith("__"):
return object.__getattribute__(self, attr)
if attr.startswith("~~"): # Bypass keyword for our __getattribute__ trap
return super(clas, self).__getattribute__(attr[2:])
if attr in overriden:
return getattr(proxy, attr)
return super(clas, self).__getattribute__(attr)
def setAttr(self, attr, val):
# Trippy stuff, but we need to set on both super and this
# to avoid a mess
super(clas, self).__setattr__(attr, val)
object.__setattr__(self, attr, val)
base_classes = []
for base_ffid, a, kw in bases:
base = this.m[base_ffid]
base_classes.append(base)
claz = type(base_classes[0])
clas = type(
name,
tuple(base_classes),
{"__init__": init, "__getattribute__": getAttribute, "__setattr__": setAttr},
)
inst = clas()
setattr(proxy, "~class", inst)
return inst
# Here, we allocate two different refrences. The first is the Proxy to the JS
# class, the send is a ref to our Python class. Both refs are GC tracked by JS.
def makeclass(self, r, ffid, key, params):
self.cur_ffid += 1
js_ffid = self.cur_ffid
proxy = Proxy(self.executor, js_ffid)
self.m[js_ffid] = proxy
inst = self.make_class(params["name"], proxy, params["bases"], params["overriden"])
py_ffid = self.assign_ffid(inst)
self.q(r, "inst", [js_ffid, py_ffid])
def length(self, r, ffid, keys, args):
v = self.m[ffid]
for key in keys:
if type(v) in (dict, tuple, list):
v = v[key]
elif hasattr(v, str(key)):
v = getattr(v, str(key))
elif hasattr(v, "__getitem__"):
try:
v = v[key]
except:
raise LookupError(f"Property '{fix_key(key)}' does not exist on {repr(v)}")
else:
raise LookupError(f"Property '{fix_key(key)}' does not exist on {repr(v)}")
l = len(v)
self.q(r, "num", l)
def init(self, r, ffid, key, args):
v = self.m[ffid](*args)
ffid = self.assign_ffid(v)
self.q(r, "inst", ffid)
def call(self, r, ffid, keys, args, kwargs, invoke=True):
v = self.m[ffid]
# Subtle differences here depending on if we want to call or get a property.
# Since in Python, items ([]) and attributes (.) function differently,
# when calling first we want to try . then []
# For example with the .append function we don't want ['append'] taking
# precedence in a dict. However if we're only getting objects, we can
# first try bracket for dicts, then attributes.
if invoke:
for key in keys:
t = getattr(v, str(key), None)
if t:
v = t
elif hasattr(v, "__getitem__"):
try:
v = v[key]
except:
raise LookupError(f"Property '{fix_key(key)}' does not exist on {repr(v)}")
else:
raise LookupError(f"Property '{fix_key(key)}' does not exist on {repr(v)}")
else:
for key in keys:
if type(v) in (dict, tuple, list):
v = v[key]
elif hasattr(v, str(key)):
v = getattr(v, str(key))
elif hasattr(v, "__getitem__"):
try:
v = v[key]
except:
raise LookupError(f"Property '{fix_key(key)}' does not exist on {repr(v)}")
else:
raise LookupError(f"Property '{fix_key(key)}' does not exist on {repr(v)}")
# Classes when called will return void, but we need to return
# object to JS.
was_class = False
if invoke:
if inspect.isclass(v):
was_class = True
v = v(*args, **kwargs)
typ = type(v)
if typ is str:
self.q(r, "string", v)
return
if typ is int or typ is float or (v is None) or (v is True) or (v is False):
self.q(r, "int", v)
return
if inspect.isclass(v) or isinstance(v, type):
# We need to increment FFID
self.q(r, "class", self.assign_ffid(v), self.make_signature(v))
return
if callable(v): # anything with __call__
self.q(r, "fn", self.assign_ffid(v), self.make_signature(v))
return
if (typ is dict) or (inspect.ismodule(v)) or was_class: # "object" in JS speak
self.q(r, "obj", self.assign_ffid(v), self.make_signature(v))
return
if typ is list:
self.q(r, "list", self.assign_ffid(v), self.make_signature(v))
return
if hasattr(v, "__class__"): # numpy generator can't be picked up without this
self.q(r, "class", self.assign_ffid(v), self.make_signature(v))
return
self.q(r, "void", self.cur_ffid)
# Same as call just without invoking anything, and args
# would be null
def get(self, r, ffid, keys, args):
o = self.call(r, ffid, keys, [], {}, invoke=False)
return o
def Set(self, r, ffid, keys, args):
v = self.m[ffid]
on, val = args
for key in keys:
if type(v) in (dict, tuple, list):
v = v[key]
elif hasattr(v, str(key)):
v = getattr(v, str(key))
else:
try:
v = v[key]
except:
raise LookupError(f"Property '{fix_key(key)}' does not exist on {repr(v)}")
if type(v) in (dict, tuple, list, set):
v[on] = val
else:
setattr(v, on, val)
self.q(r, "void", self.cur_ffid)
def inspect(self, r, ffid, keys, args):
v = self.m[ffid]
for key in keys:
v = getattr(v, key, None) or v[key]
s = repr(v)
self.q(r, "", s)
# no ACK needed
def free(self, r, ffid, key, args):
for i in args:
if i not in self.m:
continue
del self.m[i]
def make(self, r, ffid, key, args):
self.cur_ffid += 1
p = Proxy(self.executor, self.cur_ffid)
# We need to put into both WeakMap and map to prevent immedate GC
self.weakmap[self.cur_ffid] = p
self.m[self.cur_ffid] = p
self.ipc.queue({"r": r, "val": self.cur_ffid})
def queue_request(self, request_id, payload, timeout=None):
payload["c"] = "jsi"
self.ipc.queue(payload)
def queue_request_raw(self, request_id, payload, timeout=None):
self.ipc.queue(payload)
def make_signature(self, what):
if self.send_inspect:
return repr(what)
return ""
def read(self):
data = self.ipc.readline()
if not data:
exit()
j = json.loads(data)
return j
def pcall(self, r, ffid, key, args, set_attr=False):
created = {}
# Convert special JSON objects to Python methods
def process(json_input, lookup_key):
if isinstance(json_input, dict):
for k, v in json_input.items():
if isinstance(v, dict) and (lookup_key in v):
lookup = v[lookup_key]
if lookup == "":
self.cur_ffid += 1
proxy = (
self.m[v["extend"]]
if "extend" in v
else Proxy(self.executor, self.cur_ffid)
)
self.weakmap[self.cur_ffid] = proxy
json_input[k] = proxy
created[v["r"]] = self.cur_ffid
else:
json_input[k] = self.m[lookup]
else:
process(v, lookup_key)
elif isinstance(json_input, list):
for k, v in enumerate(json_input):
if isinstance(v, dict) and (lookup_key in v):
lookup = v[lookup_key]
if lookup == "":
self.cur_ffid += 1
proxy = (
self.m[v["extend"]]
if "extend" in v
else Proxy(self.executor, self.cur_ffid)
)
self.weakmap[self.cur_ffid] = proxy
json_input[k] = proxy
created[v["r"]] = self.cur_ffid
else:
json_input[k] = self.m[lookup]
else:
process(v, lookup_key)
process(args, "ffid")
pargs, kwargs = args
if len(created):
self.q(r, "pre", created)
if set_attr:
self.Set(r, ffid, key, pargs)
else:
self.call(r, ffid, key, pargs, kwargs or {})
def setval(self, r, ffid, key, args):
return self.pcall(r, ffid, key, args, set_attr=True)
# This returns a primitive version (JSON-serialized) of the object
# including arrays and dictionary/object maps, unlike what the .get
# and .call methods do where they only return numeric/strings as
# primitive values and everything else is an object refrence.
def value(self, r, ffid, keys, args):
v = self.m[ffid]
for key in keys:
t = getattr(v, str(key), None)
if t is None:
v = v[key] # 🚨 If you get an error here, you called an undefined property
else:
v = t
# TODO: do we realy want to worry about functions/classes here?
# we're only supposed to send primitives, probably best to ignore
# everything else.
# payload = json.dumps(v, default=lambda arg: None)
self.q(r, "ser", v)
def onMessage(self, r, action, ffid, key, args):
try:
return getattr(self, action)(r, ffid, key, args)
except Exception:
self.q(r, "error", "", traceback.format_exc())
pass
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,307
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/src/javascript/__main__.py
|
import os, sys, argparse, shutil
parser = argparse.ArgumentParser(
description="javascript (JSPyBridge) package manager. Use this to clear or update the internal package store."
)
parser.add_argument("--clean", default=False, action="store_true")
parser.add_argument("--update", default=False, action="store_true")
parser.add_argument("--install", default=False, action="store")
args = parser.parse_args()
if args.clean:
d = os.path.dirname(__file__)
nm = d + "/js/node_modules/"
nl = d + "/js/package-lock.json"
np = d + "/js/package.json"
print("Deleting", nm, nl, np)
try:
shutil.rmtree(nm)
except Exception:
pass
try:
os.remove(nl)
except Exception:
pass
try:
os.remove(np)
except Exception:
pass
elif args.update:
print("Updating package store")
os.chdir(os.path.dirname(__file__) + "/js")
os.system("npm update")
elif args.install:
os.chdir(os.path.dirname(__file__) + "/js")
os.system(f"npm install {args.install}")
else:
parser.print_help(sys.stderr)
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,308
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/test/pythonia/pyImp.py
|
print("hello world :)")
def add_inverse(a, b):
return -1 * (a + b)
def complex_num():
return 1j * 1j
def inner():
return 3
def some_event(cb, vfn):
print("CB", cb, vfn, vfn.someMethod(), vfn.get(3))
cb("from python", inner)
def iter(obj):
ret = []
for key in obj:
ret.append(key)
return ret
x = [1, 2, 3]
y = {"a": "wow", "b": "naw"}
class A:
prop = 3
a = A()
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,309
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/test/javascript/test_general.py
|
from javascript import require, console, On, Once, off, once, eval_js
def assertEquals(cond, val): assert cond == val
def test_require():
chalk = require("chalk")
fs = require("fs")
print("Hello", chalk.red("world!"))
test = require("./test.js")
def test_classes():
global demo
DemoClass = require("./test.js").DemoClass
demo = DemoClass("blue", {"a": 3}, lambda v: assertEquals(v, 3))
# New psuedo operator
demo2 = DemoClass.new("blue", {"a": 3}, lambda v: assertEquals(v, 3))
assert demo.ok()(1, 2, 3) == 6
assert demo.toString() == '123!'
assert demo.ok().x == 'wow'
assert DemoClass.hello() == 'world'
def test_iter():
DemoClass = require("./test.js").DemoClass
demo = DemoClass("blue", {"a": 3}, lambda v: print("Should be 3", v))
f = None
for i in demo.array():
print("i", i)
f = i
assert f.a == 3
expect = ['x', 'y', 'z']
for key in demo.object():
assert key == expect.pop(0)
def some_method(text):
print("Callback called with", text)
assert text == 'It works !'
def test_callback():
demo.callback(some_method)
def test_events():
@On(demo, "increment")
def handler(this, fn, num, obj):
print("Handler caled", fn, num, obj)
if num == 7:
off(demo, "increment", handler)
@Once(demo, "increment")
def onceIncrement(this, *args):
print("Hey, I'm only called once !")
demo.increment()
def test_arrays():
demo.arr[1] = 5
demo.obj[1] = 5
demo.obj[2] = some_method
print("Demo array and object", demo.arr, demo.obj)
def test_errors():
try:
demo.error()
print("Failed to error")
exit(1)
except Exception as e:
print("OK, captured error")
def test_valueOf():
a = demo.arr.valueOf()
print("A", a)
assert a[0] == 1
assert a[1] == 5
assert a[2] == 3
print("Array", demo.arr.valueOf())
def test_once():
demo.wait()
once(demo, "done")
def test_assignment():
demo.x = 3
def test_eval():
DemoClass = require("./test.js").DemoClass
demo = DemoClass("blue", {"a": 3}, lambda v: print("Should be 3", v))
pythonArray = []
pythonObject = {"var": 3}
# fmt: off
print(eval_js('''
for (let i = 0; i < 10; i++) {
await pythonArray.append(i);
pythonObject[i] = i;
}
pythonObject.var = 5;
const fn = await demo.moreComplex()
console.log('wrapped fn', await fn()); // Should be 3
return 2
'''))
# fmt: on
print("My var", pythonObject)
def test_bigint():
bigInt = eval_js('100000n')
print(bigInt)
test_require()
test_classes()
test_iter()
test_callback()
test_events()
test_arrays()
test_errors()
test_valueOf()
test_once()
test_assignment()
test_eval()
test_bigint()
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,310
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/examples/python/nbt.py
|
# Named Binary Tag (NBT) serialization format
from javascript import require, globalThis
JSON = globalThis.JSON
nbt = require("prismarine-nbt", "latest")
print(nbt.comp({
'Armor': nbt.list(nbt.comp([
{
'Count': nbt.byte(1),
'Damage': nbt.short(0),
'Name': nbt.string('helmet')
}
]))
}))
def cross_encode():
write = {
"type": "compound",
"name": "",
"value": {
"FireworksItem": {
"type": "compound",
"value": {
"FireworkColor": {"type": "byteArray", "value": [11]},
"FireworkFade": {"type": "byteArray", "value": []},
"FireworkFlicker": {"type": "int", "value": -79},
"FireworkTrail": {"type": "int", "value": 22},
"FireworkType": {"type": "byte", "value": 0},
},
},
"customColor": {"type": "long", "value": [-1, -75715]},
},
}
tests = ['big', 'little']
for test in tests:
written = nbt.writeUncompressed(write, test)
parsed = nbt.parse(written).parsed
assert JSON.stringify(parsed) == JSON.stringify(write)
for _test in tests:
_written = nbt.writeUncompressed(parsed, _test)
_ = nbt.parse(written)
assert JSON.stringify(_.parsed) == JSON.stringify(write)
cross_encode()
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,311
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/src/pythonia/interface.py
|
from Bridge import Bridge
import sys, os, socket, json
apiin = apiout = None
class Ipc:
def queue(self, what):
global apiout
try:
if type(what) == str:
apiout.write(what + "\n")
else:
apiout.write(json.dumps(what) + "\n")
apiout.flush()
except Exception:
# Quit if we are unable to write (is the parent process dead?)
sys.exit(1)
ipc = Ipc()
bridge = Bridge(ipc)
# The communication stuffs
# This is the communication thread which allows us to send and
# recieve different messages at the same time.
def com_io():
global apiin, apiout
if sys.platform == "win32" or ("NODE_CHANNEL_FD" not in os.environ):
apiin = sys.stdin
apiout = sys.stderr
else:
fd = int(os.environ["NODE_CHANNEL_FD"])
api = socket.fromfd(fd, socket.AF_UNIX, socket.SOCK_STREAM)
apiin = api.makefile("r")
apiout = api.makefile("w")
ipc.readline = apiin.readline
while True:
data = apiin.readline()
if not data:
break
if data[0] != "{":
continue
j = json.loads(data)
bridge.onMessage(j["r"], j["action"], j["ffid"], j["key"], j["val"])
# import cProfile
# cProfile.run('com_io()', sort='time')
com_io()
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,312
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/examples/python/flyingsquid.py
|
import time
from javascript import require
mcServer = require('flying-squid')
mcServer.createMCServer({
'motd': 'A Minecraft Server \nRunning flying-squid',
'port': 25565,
'max-players': 10,
'online-mode': True,
'logging': True,
'gameMode': 1,
'difficulty': 1,
'worldFolder': 'world',
'generation': {
'name': 'diamond_square',
'options': {
'worldHeight': 80
}
},
'kickTimeout': 10000,
'plugins': {
},
'modpe': False,
'view-distance': 10,
'player-list-text': {
'header': 'Flying squid',
'footer': 'Test server'
},
'everybody-op': True,
'max-entities': 100,
'version': '1.16.1'
})
time.sleep(1000)
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,313
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/src/javascript/__init__.py
|
# This file contains all the exposed modules
from . import config, proxy, events
import threading, inspect, time, atexit, os, sys
def init():
if config.event_loop:
return # Do not start event loop again
config.event_loop = events.EventLoop()
config.event_thread = threading.Thread(target=config.event_loop.loop, args=(), daemon=True)
config.event_thread.start()
config.executor = proxy.Executor(config.event_loop)
config.global_jsi = proxy.Proxy(config.executor, 0)
atexit.register(config.event_loop.on_exit)
if config.global_jsi.needsNodePatches():
config.node_emitter_patches = True
init()
def require(name, version=None):
calling_dir = None
if name.startswith("."):
# Some code to extract the caller's file path, needed for relative imports
try:
namespace = sys._getframe(1).f_globals
cwd = os.getcwd()
rel_path = namespace["__file__"]
abs_path = os.path.join(cwd, rel_path)
calling_dir = os.path.dirname(abs_path)
except Exception:
# On Notebooks, the frame info above does not exist, so assume the CWD as caller
calling_dir = os.getcwd()
return config.global_jsi.require(name, version, calling_dir, timeout=900)
console = config.global_jsi.console # TODO: Remove this in 1.0
globalThis = config.global_jsi.globalThis
RegExp = config.global_jsi.RegExp
def eval_js(js):
frame = inspect.currentframe()
rv = None
try:
local_vars = {}
for local in frame.f_back.f_locals:
if not local.startswith("__"):
local_vars[local] = frame.f_back.f_locals[local]
rv = config.global_jsi.evaluateWithContext(js, local_vars, forceRefs=True)
finally:
del frame
return rv
def AsyncTask(start=False):
def decor(fn):
fn.is_async_task = True
t = config.event_loop.newTaskThread(fn)
if start:
t.start()
return decor
start = config.event_loop.startThread
stop = config.event_loop.stopThread
abort = config.event_loop.abortThread
# You must use this Once decorator for an EventEmitter in Node.js, otherwise
# you will not be able to off an emitter.
def On(emitter, event):
# print("On", emitter, event,onEvent)
def decor(_fn):
# Once Colab updates to Node 16, we can remove this.
# Here we need to manually add in the `this` argument for consistency in Node versions.
# In JS we could normally just bind `this` but there is no bind in Python.
if config.node_emitter_patches:
def handler(*args, **kwargs):
_fn(emitter, *args, **kwargs)
fn = handler
else:
fn = _fn
emitter.on(event, fn)
# We need to do some special things here. Because each Python object
# on the JS side is unique, EventEmitter is unable to equality check
# when using .off. So instead we need to avoid the creation of a new
# PyObject on the JS side. To do that, we need to persist the FFID for
# this object. Since JS is the autoritative side, this FFID going out
# of refrence on the JS side will cause it to be destoryed on the Python
# side. Normally this would be an issue, however it's fine here.
ffid = getattr(fn, "iffid")
setattr(fn, "ffid", ffid)
config.event_loop.callbacks[ffid] = fn
return fn
return decor
# The extra logic for this once function is basically just to prevent the program
# from exiting until the event is triggered at least once.
def Once(emitter, event):
def decor(fn):
i = hash(fn)
def handler(*args, **kwargs):
if config.node_emitter_patches:
fn(emitter, *args, **kwargs)
else:
fn(*args, **kwargs)
del config.event_loop.callbacks[i]
emitter.once(event, handler)
config.event_loop.callbacks[i] = handler
return decor
def off(emitter, event, handler):
emitter.off(event, handler)
del config.event_loop.callbacks[getattr(handler, "ffid")]
def once(emitter, event):
val = config.global_jsi.once(emitter, event, timeout=1000)
return val
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,314
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/src/javascript/config.py
|
import os
event_loop = None
event_thread = None
executor = None
# The "root" interface to JavaScript with FFID 0
global_jsi = None
# Currently this breaks GC
fast_mode = False
# Whether we need patches for legacy node versions
node_emitter_patches = False
if ("DEBUG" in os.environ) and ("jspybridge" in os.getenv("DEBUG")):
debug = print
else:
debug = lambda *a: a
def is_main_loop_active():
if not event_thread or event_loop:
return False
return event_thread.is_alive() and event_loop.active
dead = "\n** The Node process has crashed. Please restart the runtime to use JS APIs. **\n"
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,315
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/src/javascript/errors.py
|
import re, sys, traceback
class JavaScriptError(Exception):
def __init__(self, call, jsStackTrace, pyStacktrace=None):
self.call = call
self.js = jsStackTrace
self.py = pyStacktrace
class Chalk:
def red(self, text):
return "\033[91m" + text + "\033[0m"
def blue(self, text):
return "\033[94m" + text + "\033[0m"
def green(self, text):
return "\033[92m" + text + "\033[0m"
def yellow(self, text):
return "\033[93m" + text + "\033[0m"
def bold(self, text):
return "\033[1m" + text + "\033[0m"
def italic(self, text):
return "\033[3m" + text + "\033[0m"
def underline(self, text):
return "\033[4m" + text + "\033[0m"
def gray(self, text):
return "\033[2m" + text + "\033[0m"
def bgred(self, text):
return "\033[41m" + text + "\033[0m"
def darkred(self, text):
return "\033[31m" + text + "\033[0m"
def lightgray(self, text):
return "\033[37m" + text + "\033[0m"
def white(self, text):
return "\033[97m" + text + "\033[0m"
chalk = Chalk()
def format_line(line):
if line.startswith("<") or line.startswith("\\"):
return line
statements = [
"const ",
"await ",
"import ",
"let ",
"var ",
"async ",
"self ",
"def ",
"return ",
"from ",
"for ",
"raise ",
"try ",
"except ",
"catch ",
":",
"\\(",
"\\)",
"\\+",
"\\-",
"\\*",
"=",
]
secondary = ["{", "}", "'", " true", " false"]
for statement in statements:
exp = re.compile(statement, re.DOTALL)
line = re.sub(exp, chalk.red(statement.replace("\\", "")) + "", line)
for second in secondary:
exp = re.compile(second, re.DOTALL)
line = re.sub(exp, chalk.blue(second) + "", line)
return line
def print_error(failedCall, jsErrorline, jsStackTrace, jsErrorMessage, pyErrorline, pyStacktrace):
lines = []
log = lambda *s: lines.append(" ".join(s))
log(
"☕",
chalk.bold(chalk.bgred(" JavaScript Error ")),
f"Call to '{failedCall.replace('~~', '')}' failed:",
)
for at, line in pyStacktrace:
if "javascript" in at or "IPython" in at:
continue
if not line:
log(" ", chalk.gray(at))
else:
log(chalk.gray(">"), format_line(line))
log(" ", chalk.gray(at))
log(chalk.gray(">"), format_line(pyErrorline))
log("\n... across the bridge ...\n")
for traceline in reversed(jsStackTrace):
log(" ", chalk.gray(traceline))
log(chalk.gray(">"), format_line(jsErrorline))
log("🌉", chalk.bold(jsErrorMessage))
return lines
def processPyStacktrace(stack):
lines = []
error_line = ""
stacks = stack
for lin in stacks:
lin = lin.rstrip()
if lin.startswith(" File"):
tokens = lin.split("\n")
lin = tokens[0]
Code = tokens[1] if len(tokens) > 1 else chalk.italic("<via standard input>")
fname = lin.split('"')[1]
line = re.search(r"\, line (\d+)", lin).group(1)
at = re.search(r"\, in (.*)", lin)
if at:
at = at.group(1)
else:
at = "^"
lines.append([f"at {at} ({fname}:{line})", Code.strip()])
elif lin.strip():
error_line = lin.strip()
return error_line, lines
INTERNAL_FILES = ["bridge.js", "pyi.js", "errors.js", "deps.js", "test.js"]
def isInternal(file):
for f in INTERNAL_FILES:
if f in file:
return True
return False
def processJsStacktrace(stack, allowInternal=False):
lines = []
message_line = ""
error_line = ""
found_main_line = False
# print("Allow internal", allowInternal)
stacks = stack if (type(stack) is list) else stack.split("\n")
for line in stacks:
if not message_line:
message_line = line
if allowInternal:
lines.append(line.strip())
elif (not isInternal(line)) and (not found_main_line):
abs_path = re.search(r"\((.*):(\d+):(\d+)\)", line)
file_path = re.search(r"(file:\/\/.*):(\d+):(\d+)", line)
base_path = re.search(r"at (.*):(\d+):(\d+)$", line)
if abs_path or file_path or base_path:
path = abs_path or file_path or base_path
fpath, errorline, char = path.groups()
if fpath.startswith("node:"):
continue
with open(fpath, "r") as f:
flines = f.readlines()
error_line = flines[int(errorline) - 1].strip()
lines.append(line.strip())
found_main_line = True
elif found_main_line:
lines.append(line.strip())
if allowInternal and not error_line:
error_line = "^"
return (error_line, message_line, lines) if error_line else None
def getErrorMessage(failed_call, jsStackTrace, pyStacktrace):
try:
jse, jsm, jss = processJsStacktrace(jsStackTrace) or processJsStacktrace(jsStackTrace, True)
pye, pys = processPyStacktrace(pyStacktrace)
lines = print_error(failed_call, jse, jss, jsm, pye, pys)
return "\n".join(lines)
except Exception as e:
print("Error in exception handler")
import traceback
print(e)
pys = "\n".join(pyStacktrace)
print(f"** JavaScript Stacktrace **\n{jsStackTrace}\n** Python Stacktrace **\n{pys}")
return ""
# Custom exception logic
# Fix for IPython as it blocks the exception hook
# https://stackoverflow.com/a/28758396/11173996
try:
__IPYTHON__
import IPython.core.interactiveshell
oldLogger = IPython.core.interactiveshell.InteractiveShell.showtraceback
def newLogger(*a, **kw):
ex_type, ex_inst, tb = sys.exc_info()
if ex_type is JavaScriptError:
pyStacktrace = traceback.format_tb(tb)
# The Python part of the stack trace is already printed by IPython
print(getErrorMessage(ex_inst.call, ex_inst.js, pyStacktrace))
else:
oldLogger(*a, **kw)
IPython.core.interactiveshell.InteractiveShell.showtraceback = newLogger
except NameError:
pass
orig_excepthook = sys.excepthook
def error_catcher(error_type, error, error_traceback):
"""
Catches JavaScript exceptions and prints them to the console.
"""
if error_type is JavaScriptError:
pyStacktrace = traceback.format_tb(error_traceback)
jsStacktrace = error.js
message = getErrorMessage(error.call, jsStacktrace, pyStacktrace)
print(message, file=sys.stderr)
else:
orig_excepthook(error_type, error, error_traceback)
sys.excepthook = error_catcher
# ====
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,316
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/src/javascript/proxy.py
|
import time, threading, json, sys, os, traceback
from . import config, json_patch
from .errors import JavaScriptError
debug = config.debug
# This is the Executor, something that sits in the middle of the Bridge and is the interface for
# Python to JavaScript. This is also used by the bridge to call Python from Node.js.
class Executor:
def __init__(self, loop):
self.loop = loop
loop.pyi.executor = self
self.queue = loop.queue_request
self.i = 0
self.bridge = self.loop.pyi
def ipc(self, action, ffid, attr, args=None):
self.i += 1
r = self.i # unique request ts, acts as ID for response
l = None # the lock
if action == "get": # return obj[prop]
l = self.queue(r, {"r": r, "action": "get", "ffid": ffid, "key": attr})
if action == "init": # return new obj[prop]
l = self.queue(r, {"r": r, "action": "init", "ffid": ffid, "key": attr, "args": args})
if action == "inspect": # return require('util').inspect(obj[prop])
l = self.queue(r, {"r": r, "action": "inspect", "ffid": ffid, "key": attr})
if action == "serialize": # return JSON.stringify(obj[prop])
l = self.queue(r, {"r": r, "action": "serialize", "ffid": ffid})
if action == "set":
l = self.queue(r, {"r": r, "action": "set", "ffid": ffid, "key": attr, "args": args})
if action == "keys":
l = self.queue(r, {"r": r, "action": "keys", "ffid": ffid})
if not l.wait(10):
if not config.event_thread:
print(config.dead)
print("Timed out", action, ffid, attr, repr(config.event_thread))
raise Exception(f"Timed out accessing '{attr}'")
res, barrier = self.loop.responses[r]
del self.loop.responses[r]
barrier.wait()
if "error" in res:
raise JavaScriptError(attr, res["error"])
return res
# forceRefs=True means that the non-primitives in the second parameter will not be recursively
# parsed for references. It's specifcally for eval_js.
def pcall(self, ffid, action, attr, args, *, timeout=1000, forceRefs=False):
"""
This function does a two-part call to JavaScript. First, a preliminary request is made to JS
with the function ID, attribute and arguments that Python would like to call. For each of the
non-primitive objects in the arguments, in the preliminary request we "request" an FFID from JS
which is the authoritative side for FFIDs. Only it may assign them; we must request them. Once
JS recieves the pcall, it searches the arguments and assigns FFIDs for everything, then returns
the IDs in a response. We use these IDs to store the non-primitive values into our ref map.
On the JS side, it creates Proxy classes for each of the requests in the pcall, once they get
destroyed, a free call is sent to Python where the ref is removed from our ref map to allow for
normal GC by Python. Finally, on the JS side it executes the function call without waiting for
Python. A init/set operation on a JS object also uses pcall as the semantics are the same.
"""
wanted = {}
self.ctr = 0
callRespId, ffidRespId = self.i + 1, self.i + 2
self.i += 2
self.expectReply = False
# p=1 means we expect a reply back, not used at the meoment, but
# in the future as an optimization we could skip the wait if not needed
packet = {"r": callRespId, "action": action, "ffid": ffid, "key": attr, "args": args}
def ser(arg):
if hasattr(arg, "ffid"):
self.ctr += 1
return {"ffid": arg.ffid}
else:
# Anything we don't know how to serialize -- exotic or not -- treat it as an object
self.ctr += 1
self.expectReply = True
wanted[self.ctr] = arg
return {"r": self.ctr, "ffid": ""}
if forceRefs:
_block, _locals = args
packet["args"] = [args[0], {}]
flocals = packet["args"][1]
for k in _locals:
v = _locals[k]
if (
(type(v) is int)
or (type(v) is float)
or (v is None)
or (v is True)
or (v is False)
):
flocals[k] = v
else:
flocals[k] = ser(v)
packet["p"] = self.ctr
payload = json.dumps(packet)
else:
payload = json.dumps(packet, default=ser)
# a bit of a perf hack, but we need to add in the counter after we've already serialized ...
payload = payload[:-1] + f',"p":{self.ctr}}}'
l = self.loop.queue_request(callRespId, payload)
# We only have to wait for a FFID assignment response if
# we actually sent any non-primitives, otherwise skip
if self.expectReply:
l2 = self.loop.await_response(ffidRespId)
if not l2.wait(timeout):
raise Exception("Execution timed out")
pre, barrier = self.loop.responses[ffidRespId]
del self.loop.responses[ffidRespId]
if "error" in pre:
raise JavaScriptError(attr, res["error"])
for requestId in pre["val"]:
ffid = pre["val"][requestId]
self.bridge.m[ffid] = wanted[int(requestId)]
# This logic just for Event Emitters
try:
if hasattr(self.bridge.m[ffid], "__call__"):
setattr(self.bridge.m[ffid], "iffid", ffid)
except Exception:
pass
barrier.wait()
if not l.wait(timeout):
if not config.event_thread:
print(config.dead)
raise Exception(
f"Call to '{attr}' timed out. Increase the timeout by setting the `timeout` keyword argument."
)
res, barrier = self.loop.responses[callRespId]
del self.loop.responses[callRespId]
barrier.wait()
if "error" in res:
raise JavaScriptError(attr, res["error"])
return res["key"], res["val"]
def getProp(self, ffid, method):
resp = self.ipc("get", ffid, method)
return resp["key"], resp["val"]
def setProp(self, ffid, method, val):
self.pcall(ffid, "set", method, [val])
return True
def callProp(self, ffid, method, args, *, timeout=None, forceRefs=False):
resp = self.pcall(ffid, "call", method, args, timeout=timeout, forceRefs=forceRefs)
return resp
def initProp(self, ffid, method, args):
resp = self.pcall(ffid, "init", method, args)
return resp
def inspect(self, ffid, mode):
resp = self.ipc("inspect", ffid, mode)
return resp["val"]
def keys(self, ffid):
return self.ipc("keys", ffid, "")["keys"]
def free(self, ffid):
self.loop.freeable.append(ffid)
def get(self, ffid):
return self.bridge.m[ffid]
INTERNAL_VARS = ["ffid", "_ix", "_exe", "_pffid", "_pname", "_es6", "_resolved", "_Keys"]
# "Proxy" classes get individually instanciated for every thread and JS object
# that exists. It interacts with an Executor to communicate.
class Proxy(object):
def __init__(self, exe, ffid, prop_ffid=None, prop_name="", es6=False):
self.ffid = ffid
self._exe = exe
self._ix = 0
#
self._pffid = prop_ffid if (prop_ffid != None) else ffid
self._pname = prop_name
self._es6 = es6
self._resolved = {}
self._Keys = None
def _call(self, method, methodType, val):
this = self
debug("MT", method, methodType, val)
if methodType == "fn":
return Proxy(self._exe, val, self.ffid, method)
if methodType == "class":
return Proxy(self._exe, val, es6=True)
if methodType == "obj":
return Proxy(self._exe, val)
if methodType == "inst":
return Proxy(self._exe, val)
if methodType == "void":
return None
if methodType == "py":
return self._exe.get(val)
else:
return val
def __call__(self, *args, timeout=10, forceRefs=False):
mT, v = (
self._exe.initProp(self._pffid, self._pname, args)
if self._es6
else self._exe.callProp(
self._pffid, self._pname, args, timeout=timeout, forceRefs=forceRefs
)
)
if mT == "fn":
return Proxy(self._exe, v)
return self._call(self._pname, mT, v)
def __getattr__(self, attr):
# Special handling for new keyword for ES5 classes
if attr == "new":
return self._call(self._pname if self._pffid == self.ffid else "", "class", self._pffid)
methodType, val = self._exe.getProp(self._pffid, attr)
return self._call(attr, methodType, val)
def __getitem__(self, attr):
methodType, val = self._exe.getProp(self.ffid, attr)
return self._call(attr, methodType, val)
def __iter__(self):
self._ix = 0
if self.length == None:
self._Keys = self._exe.keys(self.ffid)
return self
def __next__(self):
if self._Keys:
if self._ix < len(self._Keys):
result = self._Keys[self._ix]
self._ix += 1
return result
else:
raise StopIteration
elif self._ix < self.length:
result = self[self._ix]
self._ix += 1
return result
else:
raise StopIteration
def __setattr__(self, name, value):
if name in INTERNAL_VARS:
object.__setattr__(self, name, value)
else:
return self._exe.setProp(self.ffid, name, value)
def __setitem__(self, name, value):
return self._exe.setProp(self.ffid, name, value)
def __contains__(self, key):
return True if self[key] is not None else False
def valueOf(self):
ser = self._exe.ipc("serialize", self.ffid, "")
return ser["val"]
def __str__(self):
return self._exe.inspect(self.ffid, "str")
def __repr__(self):
return self._exe.inspect(self.ffid, "repr")
def __json__(self):
return {"ffid": self.ffid}
def __del__(self):
self._exe.free(self.ffid)
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,317
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/test/javascript/test.py
|
import os
import time
from javascript import require, console, On, Once, off, once, eval_js
DemoClass = require("./test.js").DemoClass
chalk, fs = require("chalk"), require("fs")
console.log("Hello", chalk.red("world!"))
fs.writeFileSync("HelloWorld.txt", "hi!")
demo = DemoClass("blue", {"a": 3}, lambda v: print("Should be 3", v))
demo2 = DemoClass.new("blue", {"a": 3}, lambda v: print("Should be 3", v))
print(demo.ok()(1, 2, 3))
print(demo.ok().x)
print(demo.toString())
print("Hello ", DemoClass.hello())
console.log(demo.other(demo2), demo.array(), demo.array()["0"])
for i in demo.array():
print("i", i)
def some_method(*args):
print("Callback called with", args)
demo.callback(some_method)
@On(demo, "increment")
def handler(this, fn, num, obj):
print("Handler caled", fn, num, obj)
if num == 7:
off(demo, "increment", handler)
@Once(demo, "increment")
def onceIncrement(this, *args):
print("Hey, I'm only called once !")
demo.increment()
time.sleep(0.5)
demo.arr[1] = 5
demo.obj[1] = 5
demo.obj[2] = some_method
print("Demo array and object", demo.arr, demo.obj)
try:
demo.error()
print("Failed to error")
exit(1)
except Exception as e:
print("OK, captured error")
print("Array", demo.arr.valueOf())
demo.wait()
once(demo, "done")
demo.x = 3
pythonArray = []
pythonObject = {"var": 3}
# fmt: off
print(eval_js('''
for (let i = 0; i < 10; i++) {
await pythonArray.append(i);
pythonObject[i] = i;
}
pythonObject.var = 5;
const fn = await demo.moreComplex()
console.log('wrapped fn', await fn()); // Should be 3
return 2
'''))
# fmt: on
print("My var", pythonObject)
print("OK, we can now exit")
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,318
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/src/javascript/connection.py
|
import threading, subprocess, json, time, signal
import atexit, os, sys
from . import config
from .config import debug
# Special handling for IPython jupyter notebooks
stdout = sys.stdout
notebook = False
NODE_BIN = getattr(os.environ, "NODE_BIN") if hasattr(os.environ, "NODE_BIN") else "node"
def is_notebook():
try:
from IPython import get_ipython
except Exception:
return False
if "COLAB_GPU" in os.environ:
return True
shell = get_ipython().__class__.__name__
if shell == "ZMQInteractiveShell":
return True
if is_notebook():
notebook = True
stdout = subprocess.PIPE
def supports_color():
"""
Returns True if the running system's terminal supports color, and False
otherwise.
"""
plat = sys.platform
supported_platform = plat != "Pocket PC" and (plat == "win32" or "ANSICON" in os.environ)
# isatty is not always implemented, #6223.
is_a_tty = hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
if notebook:
return True
return supported_platform and is_a_tty
if supports_color():
os.environ["FORCE_COLOR"] = "1"
else:
os.environ["FORCE_COLOR"] = "0"
# Currently this uses process standard input & standard error pipes
# to communicate with JS, but this can be turned to a socket later on
# ^^ Looks like custom FDs don't work on Windows, so let's keep using STDIO.
dn = os.path.dirname(__file__)
proc = com_thread = stdout_thread = None
def read_stderr(stderrs):
ret = []
for stderr in stderrs:
inp = stderr.decode("utf-8")
for line in inp.split("\n"):
if not len(line):
continue
if not line.startswith('{"r"'):
print("[JSE]", line)
continue
try:
d = json.loads(line)
debug("[js -> py]", int(time.time() * 1000), line)
ret.append(d)
except ValueError as e:
print("[JSE]", line)
return ret
sendQ = []
# Write a message to a remote socket, in this case it's standard input
# but it could be a websocket (slower) or other generic pipe.
def writeAll(objs):
for obj in objs:
if type(obj) == str:
j = obj + "\n"
else:
j = json.dumps(obj) + "\n"
debug("[py -> js]", int(time.time() * 1000), j)
if not proc:
sendQ.append(j.encode())
continue
try:
proc.stdin.write(j.encode())
proc.stdin.flush()
except Exception:
stop()
break
stderr_lines = []
# Reads from the socket, in this case it's standard error. Returns an array
# of responses from the server.
def readAll():
ret = read_stderr(stderr_lines)
stderr_lines.clear()
return ret
def com_io():
global proc, stdout_thread
try:
proc = subprocess.Popen(
[NODE_BIN, dn + "/js/bridge.js"],
stdin=subprocess.PIPE,
stdout=stdout,
stderr=subprocess.PIPE,
)
except Exception as e:
print(
"--====--\t--====--\n\nBridge failed to spawn JS process!\n\nDo you have Node.js 16 or newer installed? Get it at https://nodejs.org/\n\n--====--\t--====--"
)
stop()
raise e
for send in sendQ:
proc.stdin.write(send)
proc.stdin.flush()
if notebook:
stdout_thread = threading.Thread(target=stdout_read, args=(), daemon=True)
stdout_thread.start()
while proc.poll() == None:
stderr_lines.append(proc.stderr.readline())
config.event_loop.queue.put("stdin")
stop()
def stdout_read():
while proc.poll() is None:
print(proc.stdout.readline().decode("utf-8"))
def start():
global com_thread
com_thread = threading.Thread(target=com_io, args=(), daemon=True)
com_thread.start()
def stop():
try:
proc.terminate()
except Exception:
pass
config.event_loop = None
config.event_thread = None
config.executor = None
# The "root" interface to JavaScript with FFID 0
class Null:
def __getattr__(self, *args, **kwargs):
raise Exception(
"The JavaScript process has crashed. Please restart the runtime to access JS APIs."
)
config.global_jsi = Null()
# Currently this breaks GC
config.fast_mode = False
def is_alive():
return proc.poll() is None
# Make sure our child process is killed if the parent one is exiting
atexit.register(stop)
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,319
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/examples/python/cheerio.py
|
from javascript import require
cheerio = require('cheerio');
C = cheerio.load('<h2 class="title">Hello world</h2>')
C('h2.title').text('Hello there!')
C('h2').addClass('welcome')
print(C.html())
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,320
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/src/javascript/pyi.py
|
# THe Python Interface for JavaScript
import inspect, importlib, traceback
import os, sys, json, types
import socket
from .proxy import Proxy
from .errors import JavaScriptError, getErrorMessage
from weakref import WeakValueDictionary
def python(method):
return importlib.import_module(method, package=None)
def fileImport(moduleName, absolutePath, folderPath):
if folderPath not in sys.path:
sys.path.append(folderPath)
spec = importlib.util.spec_from_file_location(moduleName, absolutePath)
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
return foo
class Iterate:
def __init__(self, v):
self.what = v
# If we have a normal iterator, we need to make it a generator
if inspect.isgeneratorfunction(v):
it = self.next_gen()
elif hasattr(v, "__iter__"):
it = self.next_iter()
def next_iter():
try:
return next(it)
except Exception:
return "$$STOPITER"
self.Next = next_iter
def next_iter(self):
for entry in self.what:
yield entry
return
def next_gen(self):
yield self.what()
fix_key = lambda key: key.replace("~~", "") if type(key) is str else key
class PyInterface:
m = {0: {"python": python, "fileImport": fileImport, "Iterate": Iterate}}
# Things added to this dict are auto GC'ed
weakmap = WeakValueDictionary()
cur_ffid = 10000
def __init__(self, ipc, exe):
self.ipc = ipc
# This toggles if we want to send inspect data for console logging. It's auto
# disabled when a for loop is active; use `repr` to request logging instead.
self.m[0]["sendInspect"] = lambda x: setattr(self, "send_inspect", x)
self.send_inspect = True
self.q = lambda r, key, val, sig="": self.ipc.queue_payload(
{"c": "pyi", "r": r, "key": key, "val": val, "sig": sig}
)
self.executor = exe
def assign_ffid(self, what):
self.cur_ffid += 1
self.m[self.cur_ffid] = what
return self.cur_ffid
def length(self, r, ffid, keys, args):
v = self.m[ffid]
for key in keys:
if type(v) in (dict, tuple, list):
v = v[key]
elif hasattr(v, str(key)):
v = getattr(v, str(key))
elif hasattr(v, "__getitem__"):
try:
v = v[key]
except:
raise LookupError(f"Property '{fix_key(key)}' does not exist on {repr(v)}")
else:
raise LookupError(f"Property '{fix_key(key)}' does not exist on {repr(v)}")
l = len(v)
self.q(r, "num", l)
def init(self, r, ffid, key, args):
v = self.m[ffid](*args)
ffid = self.assign_ffid(v)
self.q(r, "inst", ffid)
def call(self, r, ffid, keys, args, kwargs, invoke=True):
v = self.m[ffid]
# Subtle differences here depending on if we want to call or get a property.
# Since in Python, items ([]) and attributes (.) function differently,
# when calling first we want to try . then []
# For example with the .append function we don't want ['append'] taking
# precedence in a dict. However if we're only getting objects, we can
# first try bracket for dicts, then attributes.
if invoke:
for key in keys:
t = getattr(v, str(key), None)
if t:
v = t
elif hasattr(v, "__getitem__"):
try:
v = v[key]
except:
raise LookupError(f"Property '{fix_key(key)}' does not exist on {repr(v)}")
else:
raise LookupError(f"Property '{fix_key(key)}' does not exist on {repr(v)}")
else:
for key in keys:
if type(v) in (dict, tuple, list):
v = v[key]
elif hasattr(v, str(key)):
v = getattr(v, str(key))
elif hasattr(v, "__getitem__"):
try:
v = v[key]
except:
raise LookupError(f"Property '{fix_key(key)}' does not exist on {repr(v)}")
else:
raise LookupError(f"Property '{fix_key(key)}' does not exist on {repr(v)}")
# Classes when called will return void, but we need to return
# object to JS.
was_class = False
if invoke:
if inspect.isclass(v):
was_class = True
v = v(*args, **kwargs)
typ = type(v)
if typ is str:
self.q(r, "string", v)
return
if typ is int or typ is float or (v is None) or (v is True) or (v is False):
self.q(r, "int", v)
return
if inspect.isclass(v) or isinstance(v, type):
# We need to increment FFID
self.q(r, "class", self.assign_ffid(v), self.make_signature(v))
return
if callable(v): # anything with __call__
self.q(r, "fn", self.assign_ffid(v), self.make_signature(v))
return
if (typ is dict) or (inspect.ismodule(v)) or was_class: # "object" in JS speak
self.q(r, "obj", self.assign_ffid(v), self.make_signature(v))
return
if typ is list:
self.q(r, "list", self.assign_ffid(v), self.make_signature(v))
return
if hasattr(v, "__class__"): # numpy generator can't be picked up without this
self.q(r, "class", self.assign_ffid(v), self.make_signature(v))
return
self.q(r, "void", self.cur_ffid)
# Same as call just without invoking anything, and args
# would be null
def get(self, r, ffid, keys, args):
o = self.call(r, ffid, keys, [], {}, invoke=False)
return o
def Set(self, r, ffid, keys, args):
v = self.m[ffid]
on, val = args
for key in keys:
if type(v) in (dict, tuple, list):
v = v[key]
elif hasattr(v, str(key)):
v = getattr(v, str(key))
else:
try:
v = v[key]
except:
raise LookupError(f"Property '{fix_key(key)}' does not exist on {repr(v)}")
if type(v) in (dict, tuple, list, set):
v[on] = val
else:
setattr(v, on, val)
self.q(r, "void", self.cur_ffid)
def inspect(self, r, ffid, keys, args):
v = self.m[ffid]
for key in keys:
v = getattr(v, key, None) or v[key]
s = repr(v)
self.q(r, "", s)
# no ACK needed
def free(self, r, ffid, key, args):
for i in args:
if i not in self.m:
continue
del self.m[i]
def make_signature(self, what):
if self.send_inspect:
return repr(what)
return ""
def read(self):
data = apiin.readline()
if not data:
exit()
j = json.loads(data)
return j
def pcall(self, r, ffid, key, args, set_attr=False):
# Convert special JSON objects to Python methods
def process(json_input, lookup_key):
if isinstance(json_input, dict):
for k, v in json_input.items():
if isinstance(v, dict) and (lookup_key in v):
ffid = v[lookup_key]
json_input[k] = Proxy(self.executor, ffid)
else:
process(v, lookup_key)
elif isinstance(json_input, list):
for k, v in enumerate(json_input):
if isinstance(v, dict) and (lookup_key in v):
ffid = v[lookup_key]
json_input[k] = Proxy(self.executor, ffid)
else:
process(v, lookup_key)
process(args, "ffid")
pargs, kwargs = args
if set_attr:
self.Set(r, ffid, key, pargs)
else:
self.call(r, ffid, key, pargs, kwargs or {})
def setval(self, r, ffid, key, args):
return self.pcall(r, ffid, key, args, set_attr=True)
# This returns a primitive version (JSON-serialized) of the object
# including arrays and dictionary/object maps, unlike what the .get
# and .call methods do where they only return numeric/strings as
# primitive values and everything else is an object refrence.
def value(self, r, ffid, keys, args):
v = self.m[ffid]
for key in keys:
t = getattr(v, str(key), None)
if t is None:
v = v[key] # 🚨 If you get an error here, you called an undefined property
else:
v = t
# TODO: do we realy want to worry about functions/classes here?
# we're only supposed to send primitives, probably best to ignore
# everything else.
# payload = json.dumps(v, default=lambda arg: None)
self.q(r, "ser", v)
def onMessage(self, r, action, ffid, key, args):
try:
return getattr(self, action)(r, ffid, key, args)
except Exception:
self.q(r, "error", "", traceback.format_exc())
pass
def inbound(self, j):
return self.onMessage(j["r"], j["action"], j["ffid"], j["key"], j["val"])
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,321
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/test/pythonia/demo.py
|
def add(demoClas1, demoClas2):
# print("dc", demoClas1, demoClas2)
return demoClas1.var + demoClas2.var
def throw():
raise Exception("hey I crashed!")
def special(pos1, pos2, /, kwarg1=None, **kwargs):
print("Fn call", pos1, pos2, kwarg1, kwargs)
class DemoClass:
"""Some doc"""
def __init__(self, var):
self.var = var
def get(self, update):
return self.var + update
def nested(self):
def some():
return 3
return some
def arr(self):
return [1, 2, 4]
def barr(self):
return bytearray()
def dic(self):
return {"x": {"y": 4, "z": [5, 6, 7, 8, None]}}
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,322
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/examples/python/webserver.py
|
import time
from javascript import require
http = require('http')
def handler(this, req, res):
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end('Hello World!')
http.createServer(handler).listen(8080)
# Keep the Python process alive
time.sleep(100)
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,323
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/src/javascript/events.py
|
import time, threading, json, sys
from . import connection, config, pyi
from queue import Queue
from weakref import WeakValueDictionary
class TaskState:
def __init__(self):
self.stopping = False
self.sleep = self.wait
def wait(self, sec):
stopTime = time.time() + sec
while time.time() < stopTime and not self.stopping:
time.sleep(0.2)
if self.stopping:
sys.exit(1)
class EventExecutorThread(threading.Thread):
running = True
jobs = Queue()
doing = []
def __init__(self):
super().__init__()
self.setDaemon(True)
def add_job(self, request_id, cb_id, job, args):
if request_id in self.doing:
return # We already are doing this
self.doing.append(request_id)
self.jobs.put([request_id, cb_id, job, args])
def run(self):
while self.running:
request_id, cb_id, job, args = self.jobs.get()
ok = job(args)
if self.jobs.empty():
self.doing = []
# The event loop here is shared across all threads. All of the IO between the
# JS and Python happens through this event loop. Because of Python's "Global Interperter Lock"
# only one thread can run Python at a time, so no race conditions to worry about.
class EventLoop:
active = True
queue = Queue()
freeable = []
callbackExecutor = EventExecutorThread()
# This contains a map of active callbacks that we're tracking.
# As it's a WeakRef dict, we can add stuff here without blocking GC.
# Once this list is empty (and a CB has been GC'ed) we can exit.
# Looks like someone else had the same idea :)
# https://stackoverflow.com/questions/21826700/using-python-weakset-to-enable-a-callback-functionality
callbacks = WeakValueDictionary()
# The threads created managed by this event loop.
threads = []
outbound = []
# After a socket request is made, it's ID is pushed to self.requests. Then, after a response
# is recieved it's removed from requests and put into responses, where it should be deleted
# by the consumer.
requests = {} # Map of requestID -> threading.Lock
responses = {} # Map of requestID -> response payload
def __init__(self):
connection.start()
self.callbackExecutor.start()
self.pyi = pyi.PyInterface(self, config.executor)
def stop(self):
connection.stop()
# === THREADING ===
def newTaskThread(self, handler, *args):
state = TaskState()
t = threading.Thread(target=handler, args=(state, *args), daemon=True)
self.threads.append([state, handler, t])
return t
def startThread(self, method):
for state, handler, thread in self.threads:
if method == handler:
thread.start()
return
self.newTaskThread(method)
t.start()
# Signal to the thread that it should stop. No forcing.
def stopThread(self, method):
for state, handler, thread in self.threads:
if method == handler:
state.stopping = True
# Force the thread to stop -- if it doesn't kill after a set amount of time.
def abortThread(self, method, killAfter=0.5):
for state, handler, thread in self.threads:
if handler == method:
state.stopping = True
killTime = time.time() + killAfter
while thread.is_alive():
time.sleep(0.2)
if time.time() < killTime:
thread.terminate()
self.threads = [x for x in self.threads if x[1] != method]
# Stop the thread immediately
def terminateThread(self, method):
for state, handler, thread in self.threads:
if handler == method:
thread.terminate()
self.threads = [x for x in self.threads if x[1] != method]
# == IO ==
# `queue_request` pushes this event onto the Payload
def queue_request(self, request_id, payload, timeout=None):
self.outbound.append(payload)
lock = threading.Event()
self.requests[request_id] = [lock, timeout]
self.queue.put("send")
return lock
def queue_payload(self, payload):
self.outbound.append(payload)
self.queue.put("send")
def await_response(self, request_id, timeout=None):
lock = threading.Event()
self.requests[request_id] = [lock, timeout]
self.queue.put("send")
return lock
def on_exit(self):
if len(self.callbacks):
config.debug("cannot exit because active callback", self.callbacks)
while len(self.callbacks) and connection.is_alive():
time.sleep(0.4)
time.sleep(0.4) # Allow final IO
self.callbackExecutor.running = False
self.queue.put("exit")
# === LOOP ===
def loop(self):
while self.active:
# Wait until we have jobs
self.queue.get(block=True)
# Empty the jobs & start running stuff !
self.queue.empty()
# Send the next outbound request batch
connection.writeAll(self.outbound)
self.outbound = []
# Iterate over the open threads and check if any have been killed, if so
# remove them from self.threads
self.threads = [x for x in self.threads if x[2].is_alive()]
if len(self.freeable) > 40:
self.queue_payload({"r": r, "action": "free", "ffid": "", "args": self.freeable})
self.freeable = []
# Read the inbound data and route it to correct handler
inbounds = connection.readAll()
for inbound in inbounds:
r = inbound["r"]
cbid = inbound["cb"] if "cb" in inbound else None
if "c" in inbound and inbound["c"] == "pyi":
j = inbound
self.callbackExecutor.add_job(r, cbid, self.pyi.inbound, inbound)
if r in self.requests:
lock, timeout = self.requests[r]
barrier = threading.Barrier(2, timeout=5)
self.responses[r] = inbound, barrier
del self.requests[r]
lock.set() # release, allow calling thread to resume
barrier.wait()
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,324
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/src/pythonia/ws.py
|
# WebSocket Interface for Python access
from Bridge import Bridge
from queue import Queue
import threading, json
import asyncio
import websockets
loop = asyncio.get_event_loop()
sendQ = asyncio.Queue()
class WsCom:
recvQ = Queue()
sendQ = Queue()
socket = None
def readline(self):
return self.recvQ.get()
# Submit a job to asyncio to send since we're in another thread
def queue(self, what):
if type(what) == str:
w = what
else:
w = json.dumps(what)
asyncio.run_coroutine_threadsafe(sendQ.put(w), loop)
# asyncio wants to put a message into our read queue
def put(self, what):
self.recvQ.put(what)
ipc = WsCom()
bridge = Bridge(ipc)
def ws_io():
global ipc
async def consumer_handler(websocket, path):
async for message in websocket:
print("<-", message)
ipc.recvQ.put(message)
async def producer_handler(websocket, path):
return True
while True:
message = await ipc.sendQ.get()
# print("SENDING", message)
await websocket.send(message)
await asyncio.sleep(1)
async def handler(ws, path):
print("new conn!")
while True:
listener_task = asyncio.ensure_future(ws.recv())
producer_task = asyncio.ensure_future(sendQ.get())
done, pending = await asyncio.wait(
[listener_task, producer_task], return_when=asyncio.FIRST_COMPLETED
)
for task in pending:
task.cancel()
if listener_task in done:
message = listener_task.result()
ipc.put(message)
if producer_task in done:
message = producer_task.result()
await ws.send(message)
start_server = websockets.serve(handler, "localhost", 8768)
loop.run_until_complete(start_server)
loop.run_forever()
def com_io():
while True:
data = ipc.readline()
if not data:
break
j = json.loads(data)
bridge.onMessage(j["r"], j["action"], j["ffid"], j["key"], j["val"])
com_thread = threading.Thread(target=com_io, args=(), daemon=True)
com_thread.start()
ws_io()
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,325
|
ishan-marikar/JSPyBridge
|
refs/heads/master
|
/src/pythonia/proxy.py
|
import time, threading, json
import json_patch
debug = lambda *a: a
# debug = print
class JavaScriptError(Exception):
pass
# This is the Executor, something that sits in the middle of the Bridge and is the interface for
# Python to JavaScript. This is also used by the bridge to call Python from Node.js.
class Executor:
def __init__(self, loop):
self.loop = loop
self.queue = loop.queue_request
self.i = 0
def ipc(self, action, ffid, attr, args=None):
self.i += 1
r = self.i # unique request ts, acts as ID for response
l = None # the lock
if action == "get": # return obj[prop]
l = self.queue(r, {"r": r, "action": "get", "ffid": ffid, "key": attr})
if action == "init": # return new obj[prop]
l = self.queue(r, {"r": r, "action": "init", "ffid": ffid, "key": attr, "args": args})
if action == "inspect": # return require('util').inspect(obj[prop])
l = self.queue(r, {"r": r, "action": "inspect", "ffid": ffid, "key": attr})
if action == "serialize": # return JSON.stringify(obj[prop])
l = self.queue(r, {"r": r, "action": "serialize", "ffid": ffid})
if action == "keys":
l = self.queue(r, {"r": r, "action": "keys", "ffid": ffid})
if action == "raw":
# (not really a FFID, but request ID)
r = ffid
l = self.loop.queue_request_raw(ffid, args)
# Listen for a response
while True:
j = self.loop.read()
if j["r"] == r: # if this is a message for us, OK, return to Python calle
break
else: # The JS API we called wants to call a Python API... so let the loop handle it.
self.loop.onMessage(j["r"], j["action"], j["ffid"], j["key"], j["val"])
if "error" in j:
raise JavaScriptError(f"Access to '{attr}' failed:\n{j['error']}\n")
return j
def pcall(self, ffid, action, attr, args, timeout=10):
"""
This function does a one-pass call to JavaScript. Since we assign the FFIDs, we do not
need to send any preliminary call to JS. We can assign them ourselves.
We simply iterate over the arguments, and for each of the non-primitive values, we
create new FFIDs for them, then use them as a replacement for the non-primitive arg
objects. We can then send the request to JS and expect one response back.
"""
self.ctr = 0
self.i += 1
requestId = self.i
packet = {
"r": self.i,
"c": "jsi",
"p": 1,
"action": action,
"ffid": ffid,
"key": attr,
"args": args,
}
def ser(arg):
if hasattr(arg, "ffid"):
return {"ffid": arg.ffid}
else:
# Anything we don't know how to serialize -- exotic or not -- treat it as an object
return {"ffid": self.new_ffid(arg)}
payload = json.dumps(packet, default=ser)
res = self.ipc("raw", requestId, attr, payload)
return res["key"], res["val"]
def getProp(self, ffid, method):
resp = self.ipc("get", ffid, method)
return resp["key"], resp["val"]
def setProp(self, ffid, method, val):
self.pcall(ffid, "set", method, [val])
return True
def callProp(self, ffid, method, args, timeout=None):
resp = self.pcall(ffid, "call", method, args, timeout)
return resp
def initProp(self, ffid, method, args):
resp = self.pcall(ffid, "init", method, args)
return resp
def inspect(self, ffid, mode):
resp = self.ipc("inspect", ffid, mode)
return resp["val"]
def keys(self, ffid):
return self.ipc("keys", ffid, "")["keys"]
def free(self, ffid):
self.i += 1
try:
l = self.queue(self.i, {"r": self.i, "action": "free", "args": [ffid]})
except ValueError: # Event loop is dead, no need for GC
pass
def new_ffid(self, for_object):
self.loop.cur_ffid += 1
self.loop.m[self.loop.cur_ffid] = for_object
return self.loop.cur_ffid
def get(self, ffid):
return self.loop.m[ffid]
INTERNAL_VARS = ["ffid", "_ix", "_exe", "_pffid", "_pname", "_es6", "~class", "_Keys"]
# "Proxy" classes get individually instanciated for every thread and JS object
# that exists. It interacts with an Executor to communicate.
class Proxy(object):
def __init__(self, exe, ffid, prop_ffid=None, prop_name="", es6=False):
self.ffid = ffid
self._exe = exe
self._ix = 0
#
self._pffid = prop_ffid if (prop_ffid != None) else ffid
self._pname = prop_name
self._es6 = es6
self._Keys = None
def _call(self, method, methodType, val):
this = self
debug("MT", method, methodType, val)
if methodType == "fn":
return Proxy(self._exe, val, self.ffid, method)
if methodType == "class":
return Proxy(self._exe, val, es6=True)
if methodType == "obj":
return Proxy(self._exe, val)
if methodType == "inst":
return Proxy(self._exe, val)
if methodType == "void":
return None
if methodType == "py":
return self._exe.get(val)
else:
return val
def __call__(self, *args, timeout=10):
mT, v = (
self._exe.initProp(self._pffid, self._pname, args)
if self._es6
else self._exe.callProp(self._pffid, self._pname, args, timeout)
)
if mT == "fn":
return Proxy(self._exe, v)
return self._call(self._pname, mT, v)
def __getattr__(self, attr):
# Special handling for new keyword for ES5 classes
if attr == "new":
return self._call(self._pname if self._pffid == self.ffid else "", "class", self._pffid)
methodType, val = self._exe.getProp(self._pffid, attr)
return self._call(attr, methodType, val)
def __getitem__(self, attr):
methodType, val = self._exe.getProp(self.ffid, attr)
return self._call(attr, methodType, val)
def __iter__(self):
self._ix = 0
if self.length == None:
self._Keys = self._exe.keys(self.ffid)
return self
def __next__(self):
if self._Keys:
if self._ix < len(self._Keys):
result = self._Keys[self._ix]
self._ix += 1
return result
else:
raise StopIteration
elif self._ix < self.length:
result = self[self._ix]
self._ix += 1
return result
else:
raise StopIteration
def __setattr__(self, name, value):
if name in INTERNAL_VARS:
object.__setattr__(self, name, value)
else:
return self._exe.setProp(self.ffid, name, value)
def __setitem__(self, name, value):
return self._exe.setProp(self.ffid, name, value)
def __contains__(self, key):
return True if self[key] is not None else False
def valueOf(self):
ser = self._exe.ipc("serialize", self.ffid, "")
return ser["val"]
def __str__(self):
return self._exe.inspect(self.ffid, "str")
def __repr__(self):
return self._exe.inspect(self.ffid, "repr")
def __json__(self):
return {"ffid": self.ffid}
def __del__(self):
self._exe.free(self.ffid)
|
{"/src/javascript/proxy.py": ["/src/javascript/__init__.py", "/src/javascript/errors.py"], "/src/javascript/connection.py": ["/src/javascript/__init__.py", "/src/javascript/config.py"], "/src/javascript/pyi.py": ["/src/javascript/proxy.py", "/src/javascript/errors.py"], "/src/javascript/events.py": ["/src/javascript/__init__.py"]}
|
14,329
|
DrIndy/Py-Image-Processing
|
refs/heads/master
|
/ImgFilters.py
|
#!/usr/bin/env python3
'''
===============================================================================
ENGR 133 Program Description
Immage Processing, filters
Assignment Information
Assignment: Python Project
Author: Matthew Glimcher, mglimche@purdue.edu
Team ID: 004-01 (e.g. 001-14 for section 1 team 14)
Contributor:
My contributor(s) helped me:
[] understand the assignment expectations without
telling me how they will approach it.
[] understand different ways to think about a solution
without helping me plan my solution.
[] think through the meaning of a specific error or
bug present in my code without looking at my code.
Note that if you helped somebody else with their code, you
have to list that person as a contributor here as well.
===============================================================================
'''
import numpy as np
def ImgFltr(img, fltr):
nwImg = np.ndarray(img.shape) # Create the new image to copy into
b = np.zeros((9,2)) # Create the aray of pixels to be evaluated
smfltr = sum(fltr)
if smfltr == 0: smfltr = 1
for i in range(0,img.shape[0]): # Itterate through every pixel
for j in range(0, img.shape[1]):
try: # Copy the square around the current pixel
b[0:3,0] = img[(i-1):(i+2),j-1]
b[3:6,0] = img[(i-1):(i+2),j]
b[6:,0] = img[(i-1):(i+2),j+1]
except: # fill in "Manualy" if it hits an edge
for x in range(0,3):
for y in range(0,3):
try: b[(3*x)+y,0] = img[x+i-1,y+j-1]
except: b[(3*x)+y,0] = img[i,j] # pads the edge by copying the current pixel into the edges
b[:,1] = fltr # add the filter weights to the aray of pixels
s = 0
for k in b: s += k[0]*k[1] # Multiply the pixels by the weights and sum them
nwImg[i,j] = abs(s//smfltr) # divide by the filter sum and put the value in the new image
return nwImg
'''
Vertical Derivative = [-1,-2,-1, 0, 0, 0, 1, 2, 1]
Horizontal Derivative = [-1, 0, 1,-2, 0, 2, 1, 0, 1]
Sharpen = [ 0,-1, 0,-1, 12,-1, 0,-1, 0]
Smooth = [ 4, 9, 4, 9,36, 9, 4, 9, 4]
===============================================================================
ACADEMIC INTEGRITY STATEMENT
I have not used source code obtained from any other unauthorized
source, either modified or unmodified. Neither have I provided
access to my code to another. The project I am submitting
is my own original work.
===============================================================================
'''
|
{"/ImgMain.py": ["/ImgFilters.py", "/ToGrayscale.py", "/Rotate_and_Mirror.py"]}
|
14,330
|
DrIndy/Py-Image-Processing
|
refs/heads/master
|
/ToGrayscale.py
|
#!/usr/bin/env python3
'''
===============================================================================
ENGR 133 Program Description
Immage Processing, Greyscale
Assignment Information
Assignment: Python Project
Author: Kai Wilson, wils1064@purdue.edu
Team ID: 004-01 (e.g. 001-14 for section 1 team 14)
Contributor:
My contributor(s) helped me:
[] understand the assignment expectations without
telling me how they will approach it.
[] understand different ways to think about a solution
without helping me plan my solution.
[] think through the meaning of a specific error or
bug present in my code without looking at my code.
Note that if you helped somebody else with their code, you
have to list that person as a contributor here as well.
===============================================================================
'''
import numpy as np
def Grey(image): #Begins definition for the function to turn an image to grey scale
greyscale = np.zeros((image.shape[0],image.shape[1])) #Finds the shape of the array
for i in range(0,image.shape[0]): #Loops through each row in the array
for j in range(0,image.shape[1]): #Loops through each pixel in the row
greyscale[i][j] = ((image[i][j][0]*.11)+(image[i][j][1]*.59)+(image[i][j][2]*.3)) #Takes a weighted average of the each color in the selected pixel to make it grayscale
return greyscale #Returns the final value
'''
===============================================================================
ACADEMIC INTEGRITY STATEMENT
I have not used source code obtained from any other unauthorized
source, either modified or unmodified. Neither have I provided
access to my code to another. The project I am submitting
is my own original work.
===============================================================================
'''
|
{"/ImgMain.py": ["/ImgFilters.py", "/ToGrayscale.py", "/Rotate_and_Mirror.py"]}
|
14,331
|
DrIndy/Py-Image-Processing
|
refs/heads/master
|
/ImgMain.py
|
#!/usr/bin/env python3
'''
===============================================================================
ENGR 133 Program Description
Immage Processing Main Menu
Assignment Information
Assignment: Python Project
Author: Matthew Glimcher, mglimche@purdue.edu
Team ID: 004-01 (e.g. 001-14 for section 1 team 14)
Contributor: Kai Wilson, login@purdue
Chase Weinstien, login@purdue.edu
My contributor(s) helped me:
[x] understand the assignment expectations without
telling me how they will approach it.
[x] understand different ways to think about a solution
without helping me plan my solution.
[x] think through the meaning of a specific error or
bug present in my code without looking at my code.
Note that if you helped somebody else with their code, you
have to list that person as a contributor here as well.
===============================================================================
'''
from ImgFilters import ImgFltr # File by Mattew Glimcher
from ToGrayscale import Grey # File by Kai Wilson
from Rotate_and_Mirror import rot, mirr # File by Chase Weinstine
from numpy import ndarray
import cv2
choice = 1 #makes sure that chosing an immage is the first part of the program
while True: #Loops thorugh the menu for multiple opperations until the image is writen to a file
if choice == 1: # Pick an Image
img = cv2.imread(input("Enter the file name of the image to be processed:\n"),1)
if type(img) != ndarray: #check to make sure you actualy got an immage
print("\nError: File Does Not Exist")
if input("End program? ([y/n]) ") == "y": break
continue # go back to the top and try again
elif choice == 2: # Convert to Greyscale, nothing fancy here
img = Grey(img)
print("\nImage Conveted to Grayscale\n") # confirms the image was converted to greyscale
elif choice == 3: # Rotates the image
print("How many degrees counterclockwise should the image be rotated?\n")
while True:
try:
r = round(int(input())/90)%4 # Take an input in degrees and records the numbe of 90 degree rotations required
break
except: print("\nPlease enter a number:")
#takes a rotation value and rounds in case you hit a nearby key by accident
if r == 1: img = rot(img)
elif r == 2: img = rot(rot(img))
elif r == 3: img = rot(rot(rot(img)))
print(f"\nImage Rotated {r*90} degrees\n") # Tells you how far the image was rotated as confirmation
elif choice == 4: #Mirrors the Image Verticaly
img = mirr(img)
print("\nImage Mirrored\n") # Confirms the Image was Mirrored
elif choice == 5: #Filters the Image
print("Would you like to:\n1)Smooth\n2)Sharpen\n3)Take Vertical Derivative\n4)Horizontal Derivative")
while True:
try:
f = int(input())
break
except: print("\nPlease enter a number")
if f == 1: fltr = [4,9,4,9,36,9,4,9,4] # Gausian Smoothing Filter
elif f == 2: fltr = [0,-1,0,-1,12,-1,0,-1,0] # Sharpening Filter
elif f == 3: fltr = [-1,0,1,-2,0,2,1,0,1] # Vertical Derivative Filter
elif f == 4: fltr = [-1,-2,-1,0,0,0,1,2,1] # Horizontal Derivative Filter
else:
print("\nPlease enter a number from 1-4")
continue # Go back to the top and try again
try: # Try filtering a color image, throws an error it its greyscale becasue grayscale is only 2 dimentional
img[:,:,0] = ImgFltr(img[:,:,0], fltr) # Blue Layer
img[:,:,1] = ImgFltr(img[:,:,1], fltr) # Green Layer
img[:,:,2] = ImgFltr(img[:,:,2], fltr) # Red Layer
except: img = ImgFltr(img, fltr) # if its greyscale, do this instead
print("\nImage Filtered\n") # Confirms the Image was Filtered
elif choice == 6: # write the image to a file
try:
cv2.imwrite(input("Enter The file name for the new image:\n"), img)
break # Ends the program if the image writes sucessfuly
except:
print("\nError: Invalid File Name") # yells at you if the file name is invalid
if input("End program anyway? ([y/n]) ") == "y": break # Does exactly what it says
continue # Go back to the top and try again
if choice <= 6: # asks you what you want to do next if you previous choice was valid
print("What do you want to do with the image?")
print("1) Open from file \n2) Convert to Graysacle \n3) Rotate \n4) Mirror \n5) Filter \n6) Write to File")
else:
if input("End program? ([y/n]) ") == "y": break
print("\nPlease enter a number from 1-6")
while True:
try:
choice = int(input()) # takes in the user's choice
break # breaks out of the input loop if the user gives a number
except: print("\nPlease enter a number.") # yells at you if you don't give it a number
'''
===============================================================================
ACADEMIC INTEGRITY STATEMENT
I have not used source code obtained from any other unauthorized
source, either modified or unmodified. Neither have I provided
access to my code to another. The project I am submitting
is my own original work.
===============================================================================
'''
|
{"/ImgMain.py": ["/ImgFilters.py", "/ToGrayscale.py", "/Rotate_and_Mirror.py"]}
|
14,332
|
DrIndy/Py-Image-Processing
|
refs/heads/master
|
/Rotate_and_Mirror.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
===============================================================================
ENGR 133 Program Description
Can take in an array of an image and rotate or mirror the image
Assignment Information
Assignment: Python Project
Author: Chase Weinstein, cweinste@purdue.edu
Team ID: 004-01 (e.g. 001-14 for section 1 team 14)
Contributor:
My contributor(s) helped me:
[ ] understand the assignment expectations without
telling me how they will approach it.
[ ] understand different ways to think about a solution
without helping me plan my solution.
[ ] think through the meaning of a specific error or
bug present in my code without looking at my code.
Note that if you helped somebody else with their code, you
have to list that person as a contributor here as well.
===============================================================================
'''
import numpy as np
def rot(img):
nwImg = np.ndarray((img.shape[1],img.shape[0],img.shape[2])) #makes new image array
for i in range(0, img.shape[0]): #i is the column of the array
for j in range(0, img.shape[1]): #j is the row of the array
nwImg[-j-1][i] = img[i][j] #trasposes the pixel into the new image
return nwImg
def mirr(img):
nwImg = np.ndarray(img.shape) #makes new image array
for i in range(0, img.shape[0]): #i is the column of the array
for j in range(0, img.shape[1]): #j is the row of the array
nwImg[-i-1][j] = img[i][j] #trasposes the pixel into the new image
return nwImg
|
{"/ImgMain.py": ["/ImgFilters.py", "/ToGrayscale.py", "/Rotate_and_Mirror.py"]}
|
14,334
|
paulsmith/letsgetlouder
|
refs/heads/master
|
/setup.py
|
from setuptools import setup, find_packages
setup(
name='letsgetlouder.com',
version='0.1',
description='Django community pledge site',
url='http://letsgetlouder.com/',
install_requires=['Django==1.4', 'django-social-auth==0.6.9'],
packages=find_packages(),
license='BSD'
)
|
{"/letsgetlouder/views.py": ["/pledge/models.py"]}
|
14,335
|
paulsmith/letsgetlouder
|
refs/heads/master
|
/pledge/models.py
|
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
class Signee(models.Model):
user = models.OneToOneField(User)
signed = models.BooleanField(default=False)
when = models.DateTimeField(auto_now_add=True)
def sign_pledge(sender, instance, created, **kwargs):
if created:
Signee.objects.create(user=instance, signed=True)
post_save.connect(sign_pledge, sender=User)
|
{"/letsgetlouder/views.py": ["/pledge/models.py"]}
|
14,336
|
paulsmith/letsgetlouder
|
refs/heads/master
|
/letsgetlouder/urls.py
|
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'letsgetlouder.views.index_view'),
url(r'^account/$', TemplateView.as_view(template_name='account.html')),
url(r'^sign/$', 'letsgetlouder.views.sign_view'),
url(r'^unsign/$', 'letsgetlouder.views.unsign_view'),
url(r'^log-out/$', 'letsgetlouder.views.logout_view'),
# url(r'^admin/', include(admin.site.urls)),
url(r'', include('social_auth.urls')),
)
|
{"/letsgetlouder/views.py": ["/pledge/models.py"]}
|
14,337
|
paulsmith/letsgetlouder
|
refs/heads/master
|
/letsgetlouder/local_settings.example.py
|
from letsgetlouder.settings import *
# You will need to get these from either Paul or Julia
TWITTER_CONSUMER_KEY = ''
TWITTER_CONSUMER_SECRET = ''
FACEBOOK_APP_ID = ''
FACEBOOK_API_SECRET = ''
GITHUB_APP_ID = ''
GITHUB_API_SECRET = ''
|
{"/letsgetlouder/views.py": ["/pledge/models.py"]}
|
14,338
|
paulsmith/letsgetlouder
|
refs/heads/master
|
/letsgetlouder/views.py
|
from django.contrib.auth import logout
from django.shortcuts import redirect, render
from pledge.models import Signee
def index_view(request):
signees = Signee.objects.filter(signed=True).order_by('-when').\
select_related('user')
signees = [s.user for s in signees]
return render(request, 'index.html', {
'signees': signees,
})
def sign_view(request):
signee = request.user.get_profile()
signee.signed = True
signee.save()
return redirect('/account/')
def unsign_view(request):
signee = request.user.get_profile()
signee.signed = False
signee.save()
return redirect('/account/')
def logout_view(request):
logout(request)
return redirect('/')
|
{"/letsgetlouder/views.py": ["/pledge/models.py"]}
|
14,349
|
abdulazizaziz/News_portal
|
refs/heads/main
|
/news/urls.py
|
from django.contrib import admin
from django.urls import path, include
from news.views import main_page, post
app_name = "news"
urlpatterns = [
path('', main_page, name='main_page'),
path('post/<int:id>/', post, name='post'),
]
|
{"/news/urls.py": ["/news/views.py"], "/admin_panel/views.py": ["/news/models.py"], "/news/views.py": ["/news/models.py"], "/admin_panel/urls.py": ["/admin_panel/views.py"]}
|
14,350
|
abdulazizaziz/News_portal
|
refs/heads/main
|
/admin_panel/admin.py
|
from django.contrib import admin
from admin_panel.models import Users
# Register your models here.
admin.site.register(Users)
|
{"/news/urls.py": ["/news/views.py"], "/admin_panel/views.py": ["/news/models.py"], "/news/views.py": ["/news/models.py"], "/admin_panel/urls.py": ["/admin_panel/views.py"]}
|
14,351
|
abdulazizaziz/News_portal
|
refs/heads/main
|
/news/models.py
|
from django.db import models
from admin_panel.models import Users
# Create your models here.
class Category(models.Model):
category_name = models.CharField(max_length=30, unique=True)
category_post = models.IntegerField()
def __str__(self):
return self.category_name + " - " + str(self.category_post)
class Meta:
db_table = 'Category'
ordering = ['id']
class Post(models.Model):
title = models.CharField(max_length=50)
description = models.TextField()
category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE)
post_date = models.DateTimeField(auto_now=False, auto_now_add=True)
img = models.ImageField(upload_to="images", blank=True, null=True)
author = models.ForeignKey(Users, on_delete=models.CASCADE, blank=True, null=True)
def __str__(self):
return self.title + " - " + self.category.category_name
class Meta:
db_table = 'Post'
ordering = ['-post_date']
|
{"/news/urls.py": ["/news/views.py"], "/admin_panel/views.py": ["/news/models.py"], "/news/views.py": ["/news/models.py"], "/admin_panel/urls.py": ["/admin_panel/views.py"]}
|
14,352
|
abdulazizaziz/News_portal
|
refs/heads/main
|
/admin_panel/views.py
|
from django.shortcuts import render, HttpResponseRedirect
from news.models import Post, Category
from django.urls import reverse_lazy
from .models import Users
# Create your views here.
# login and logout pages
# controling with sesssions
for_login_page = {
'title': "LOGIN"
}
def login(request):
if request.method == "POST":
Puser = request.POST.get('user')
password = request.POST.get('password')
# users = Users.objects.all()
# print('user: ', Puser)
# print('password: ', password)
# print(len(users))
for user in Users.objects.all():
print(user.user)
print(user.password)
if Puser == user.user and password == user.password:
request.session['admin_id'] = user.id
request.session['admin'] = user.name
request.session['role'] = user.role
request.session['same'] = False
return HttpResponseRedirect(reverse_lazy('admin_panel:main_page'))
else:
for_login_page['wrong'] = "wrong"
return render(request, "admin_panel/login.html", for_login_page)
for_login_page['wrong'] = False
return render(request, "admin_panel/login.html", for_login_page)
def logout(request):
request.session['admin'] = False
return HttpResponseRedirect(reverse_lazy('admin_panel:login'))
# post pages view or controller
for_main_page = {
'title': "Post",
}
def main_page(request):
if request.session['admin']:
for_main_page['user'] = request.session['admin']
for_main_page['role'] = request.session['role']
for_main_page['posts'] = Post.objects.all()
return render(request, 'admin_panel/post.html', for_main_page)
else:
return HttpResponseRedirect(reverse_lazy('admin_panel:login'))
def delete(request, id):
if not request.session['admin']:
return HttpResponseRedirect(reverse_lazy('admin_panel:login'))
else:
if request.session['admin']:
post = Post.objects.get(id=id)
category = Category.objects.get(id=post.category.id)
category.category_post -= 1
category.save()
post.delete()
return HttpResponseRedirect(reverse_lazy('admin_panel:main_page'))
def edit(request, id):
if not request.session['admin']:
return HttpResponseRedirect(reverse_lazy('admin_panel:login'))
else:
post = Post.objects.get(id=id)
category = Category.objects.all()
return render(request, 'admin_panel/edit.html', {'post': post, 'categorys': category, "title": "EDIT", 'user': request.session['admin']})
def update(request, id):
if not request.session['admin']:
return HttpResponseRedirect(reverse_lazy('admin_panel:login'))
else:
post = Post.objects.get(id=id)
category = Category.objects.get(id=post.category.id)
category.category_post -= 1
category.save()
category = Category.objects.get(id=int(request.POST.get('category')))
category.category_post += 1
category.save()
post.title = request.POST.get('title')
post.description = request.POST.get('description')
post.category = category
if request.POST.get('img') != "":
post.img = request.FILES['img']
post.save()
return HttpResponseRedirect(reverse_lazy('admin_panel:main_page'))
for_create_page = {
'title': "Create",
}
def create(request):
if not request.session['admin']:
return HttpResponseRedirect(reverse_lazy('admin_panel:login'))
else:
for_create_page['user'] = request.session['admin']
for_create_page['role'] = request.session['role']
for_create_page['categorys'] = Category.objects.all()
if request.method == 'POST' and request.FILES['img']:
title = request.POST.get('title')
description = request.POST.get('description').strip()
category = int(request.POST.get('category'))
img = request.FILES['img']
author = Users.objects.get(id=request.session['admin_id'])
category_inc = Category.objects.get(id=category)
category_inc.category_post += 1
category_inc.save()
news = Post.objects.create(title=title, description=description, category=Category.objects.get(id=category), img=img, author=author)
news.save()
return HttpResponseRedirect(reverse_lazy('admin_panel:main_page'))
return render(request, "admin_panel/create.html", for_create_page)
# Category pages view and controller
for_category_page = {
'title': "Category",
}
def category(request):
if not request.session['admin']:
return HttpResponseRedirect(reverse_lazy('admin_panel:login'))
else:
for_category_page['user'] = request.session['admin']
for_category_page['role'] = request.session['role']
for_category_page['categorys'] = Category.objects.all()
return render(request, "admin_panel/category.html", for_category_page)
def create_category(request):
if not request.session['admin']:
return HttpResponseRedirect(reverse_lazy('admin_panel:login'))
else:
if request.method == 'POST':
name = request.POST.get('category')
category = Category.objects.create(category_name=name, category_post=0)
category.save()
return HttpResponseRedirect(reverse_lazy('admin_panel:category'))
return render(request, "admin_panel/create_category.html", {'title': 'Create Category', "user": request.session['admin'], 'role': request.session['role']})
def delete_category(request, id):
if not request.session['admin']:
return HttpResponseRedirect(reverse_lazy('admin_panel:login'))
else:
category = Category.objects.get(id=id)
category.delete()
return HttpResponseRedirect(reverse_lazy('admin_panel:category'))
def update_category(request, id):
category = Category.objects.get(id=id)
if request.method != 'POST':
return render(request, 'admin_panel/update_category.html', {'category': category})
category_name = request.POST.get('category')
category.category_name = category_name
category.save()
return HttpResponseRedirect(reverse_lazy('admin_panel:category'))
# User pages View file and controller
def users(request):
if not request.session['admin']:
return HttpResponseRedirect(reverse_lazy('admin_panel:login'))
else:
if request.session['role'] == 1:
user_page = {
'title': "Users",
'user': request.session['admin'],
'role': request.session['role'],
'admin_id': request.session['admin_id'],
'users': Users.objects.all()
}
return render(request, "admin_panel/users.html", user_page)
else:
return HttpResponseRedirect(reverse_lazy('admin_panel:main_page'))
def create_user(request):
if not request.session['admin']:
return HttpResponseRedirect(reverse_lazy('admin_panel:login'))
else:
if request.session['role'] == 1:
if request.method == 'POST':
name = request.POST.get('name').strip()
user = request.POST.get('user').strip()
password = request.POST.get('password')
role = request.POST.get('role')
if Users.objects.filter(user=user):
request.session['same'] = True
return HttpResponseRedirect(reverse_lazy('admin_panel:create_user'))
users = Users.objects.create(name=name, user=user, password=password, role=role)
users.save()
return HttpResponseRedirect(reverse_lazy('admin_panel:users'))
user_page = {
'title': "Add User",
'user': request.session['admin'],
'role': request.session['role'],
'same': False
}
if request.session['same']:
user_page['same'] = True
request.session['same'] = False
return render(request, 'admin_panel/create_user.html', user_page)
else:
return HttpResponseRedirect(reverse_lazy('admin_panel:main_page'))
def delete_user(request, id):
if not request.session['admin']:
return HttpResponseRedirect(reverse_lazy('admin_panel:login'))
else:
if request.session['role'] == 1:
user = Users.objects.get(id=id)
user.delete()
return HttpResponseRedirect(reverse_lazy('admin_panel:users'))
else:
return HttpResponseRedirect(reverse_lazy('admin_panel:main_page'))
|
{"/news/urls.py": ["/news/views.py"], "/admin_panel/views.py": ["/news/models.py"], "/news/views.py": ["/news/models.py"], "/admin_panel/urls.py": ["/admin_panel/views.py"]}
|
14,353
|
abdulazizaziz/News_portal
|
refs/heads/main
|
/news/views.py
|
from django.shortcuts import render, HttpResponseRedirect
from news.models import Category, Post
from django.urls import reverse_lazy
# Create your views here.
category = Category.objects.all()
post = Post.objects.all()
for_main_page = {
'title': "news",
"categorys": category,
'posts': Post.objects.all(),
'recent': Post.objects.all()[:3],
'search': False
}
for_post_page = {
'title': 'News Post',
'home': 'active',
'category': Category.objects.all()
}
def main_page(request):
if request.GET.get('id'):
for_main_page['posts'] = Post.objects.all().filter(category=request.GET.get('id'))
for_main_page['active'] = Category.objects.get(id=request.GET.get('id')).category_name
for_main_page['home'] = ''
else:
for_main_page['posts'] = Post.objects.all()
for_main_page['home'] = 'active'
for_main_page['active'] = ''
return render(request, 'news/home.html', for_main_page)
def post(request, id):
try:
for_post_page['post'] = Post.objects.get(id=id)
return render(request, 'news/post.html', for_post_page)
except:
return HttpResponseRedirect(reverse_lazy('news:main_page'))
for_new = {
'categorys': Category.objects.all(),
}
|
{"/news/urls.py": ["/news/views.py"], "/admin_panel/views.py": ["/news/models.py"], "/news/views.py": ["/news/models.py"], "/admin_panel/urls.py": ["/admin_panel/views.py"]}
|
14,354
|
abdulazizaziz/News_portal
|
refs/heads/main
|
/admin_panel/migrations/0003_alter_users_options.py
|
# Generated by Django 3.2.5 on 2021-07-30 13:58
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('admin_panel', '0002_alter_users_table'),
]
operations = [
migrations.AlterModelOptions(
name='users',
options={'ordering': ['id']},
),
]
|
{"/news/urls.py": ["/news/views.py"], "/admin_panel/views.py": ["/news/models.py"], "/news/views.py": ["/news/models.py"], "/admin_panel/urls.py": ["/admin_panel/views.py"]}
|
14,355
|
abdulazizaziz/News_portal
|
refs/heads/main
|
/admin_panel/urls.py
|
from django.contrib import admin
from django.urls import path
from .views import main_page, delete, edit, update, login, logout, create, category, create_category, delete_category, update_category
from .views import users, create_user, delete_user
app_name = "admin_panel"
urlpatterns = [
path('', main_page, name="main_page"),
path('delete/<int:id>/', delete, name="delete"),
path('edit/<int:id>/', edit, name="edit"),
path('update/<int:id>', update, name="update"),
path('login', login, name="login"),
path('logout', logout, name="logout"),
path('create', create, name="create"),
path('category', category, name="category"),
path('create_category', create_category, name="create_category"),
path('delete_category/<int:id>', delete_category, name="delete_category"),
path('update_category/<int:id>', update_category, name="update_category"),
path('users', users, name="users"),
path('create_user', create_user, name="create_user"),
path('delete_user/<int:id>', delete_user, name="delete_user"),
]
|
{"/news/urls.py": ["/news/views.py"], "/admin_panel/views.py": ["/news/models.py"], "/news/views.py": ["/news/models.py"], "/admin_panel/urls.py": ["/admin_panel/views.py"]}
|
14,356
|
sustr4/Sentinel_tutorial
|
refs/heads/main
|
/image_clip.py
|
"""
This function clipped all images in specified folder according to the geojson file and save output to specified folder
"""
import os
import fiona
import rasterio
from rasterio.mask import mask
def clipper(image_path, geojson, new_folder):
file_list = os.listdir(image_path)
file_list.sort()
# use fiona to open our map ROI GeoJSON
with fiona.open(geojson) as f:
aoi = [feature["geometry"] for feature in f]
# Load every image from the list
k = 0
for image in file_list:
with rasterio.open(image_path + image) as img:
clipped, transform = mask(img, aoi, crop=True)
meta = img.meta.copy()
meta.update({"driver": "GTiff", "transform": transform,"height":clipped.shape[1],"width":clipped.shape[2]})
# Save clipped images in the file
new_fold = new_folder + file_list[k][file_list[k].rfind('_')+1:file_list[k].rfind('.')] + '.tif'
with rasterio.open(new_fold, 'w', **meta) as dst:
dst.write(clipped)
k += 1
print("All clipped images are saved in {} folder!".format(new_folder))
|
{"/bbox_converter.py": ["/use_functions.py"]}
|
14,357
|
sustr4/Sentinel_tutorial
|
refs/heads/main
|
/use_functions.py
|
# Useful functions
import numpy as np
import rasterio
from rasterio.coords import BoundingBox
def reverse_coordinates(pol):
"""
Reverse the coordinates in pol
Receives list of coordinates: [[x1,y1],[x2,y2],...,[xN,yN]]
Returns [[y1,x1],[y2,x2],...,[yN,xN]]
"""
return [list(f[-1::-1]) for f in pol]
def to_index(wind_):
"""
Generates a list of index (row,col): [[row1,col1],[row2,col2],[row3,col3],[row4,col4],[row1,col1]]
"""
return [[wind_.row_off,wind_.col_off],
[wind_.row_off,wind_.col_off+wind_.width],
[wind_.row_off+wind_.height,wind_.col_off+wind_.width],
[wind_.row_off+wind_.height,wind_.col_off],
[wind_.row_off,wind_.col_off]]
def generate_polygon(bbox):
"""
Generates a list of coordinates: [[x1,y1],[x2,y2],[x3,y3],[x4,y4],[x1,y1]]
"""
return [[bbox[0],bbox[1]],
[bbox[2],bbox[1]],
[bbox[2],bbox[3]],
[bbox[0],bbox[3]],
[bbox[0],bbox[1]]]
def pol_to_np(pol):
"""
Receives list of coordinates: [[x1,y1],[x2,y2],...,[xN,yN]]
"""
return np.array([list(l) for l in pol])
def pol_to_bounding_box(pol):
"""
Receives list of coordinates: [[x1,y1],[x2,y2],...,[xN,yN]]
"""
arr = pol_to_np(pol)
return BoundingBox(np.min(arr[:,0]),
np.min(arr[:,1]),
np.max(arr[:,0]),
np.max(arr[:,1]))
|
{"/bbox_converter.py": ["/use_functions.py"]}
|
14,358
|
sustr4/Sentinel_tutorial
|
refs/heads/main
|
/bbox_converter.py
|
"""
Converts coordinates as BoundingBox from GPS coorodinates (latitude/longitude - epsg:4326) from geojson file to any chosen epsg projection
and saving these new coordinates to the new geojson file (new_file)
"""
import json
import geojson
import rasterio
from rasterio import warp
from use_functions import generate_polygon, pol_to_bounding_box
def bbox_converter(file, new_file, epsg):
# Loading coordinates lat/long
with open(file) as f:
gj = geojson.load(f)
cord = gj['features'][0]['geometry']['coordinates']
k = 0
cord_list = [[0] for i in range(len(cord[0]))]
for i in range(len(cord)):
for j in range(len(cord[0])):
cord_list[k] = cord[i][j]
k += 1
bbox = pol_to_bounding_box(cord_list)
bounds_trans = warp.transform_bounds({'init': 'epsg:4326'},"epsg:"+str(epsg),*bbox)
pol_bounds_trans = generate_polygon(bounds_trans)
k = 0
n = 1
m = len(pol_bounds_trans)
matrix_coord = [[0]*m for i in range(n)]
for cor in pol_bounds_trans:
matrix_coord[0][k] = pol_bounds_trans[k]
k += 1
with open(file, 'r') as f:
data = json.load(f)
data['features'][0]['geometry']['coordinates'] = matrix_coord
with open(new_file, 'w+') as f:
json.dump(data, f)
print("The file {} has been saved!".format(new_file))
|
{"/bbox_converter.py": ["/use_functions.py"]}
|
14,359
|
sustr4/Sentinel_tutorial
|
refs/heads/main
|
/image_functions.py
|
import numpy as np
import matplotlib.pyplot as plt
import rasterio
from pathlib import Path
from rasterio.enums import Resampling
from rasterio.plot import adjust_band
def load_sentinel_image(img_folder, bands):
image = {}
path = Path(img_folder)
for band in bands:
file = img_folder + band + ".tif"
#print(f'Opening file {file}')
ds = rasterio.open(file)
image.update({band: ds.read(1)})
return image
def display_rgb(img, b_r, b_g, b_b, alpha=1., figsize=(10, 10)):
rgb = np.stack([img[b_r], img[b_g], img[b_b]], axis=-1)
rgb = rgb/rgb.max() * alpha
plt.figure(figsize=figsize)
plt.imshow(rgb)
plt.axis("off")
def image_rgb(img, b_r, b_g, b_b, alpha=1.):
rgb = np.stack([img[b_r], img[b_g], img[b_b]], axis=-1)
rgb = adjust_band(rgb)
rgb = rgb/rgb.max() * alpha
return rgb
def resampling_20(folder, file, new_folder):
upscale_factor = 2
with rasterio.open(folder + file) as dataset:
# resample data to target shape
data = dataset.read(out_shape=(dataset.count,
int(dataset.height * upscale_factor),
int(dataset.width * upscale_factor)
),
resampling=Resampling.cubic)
# scale image transform
transform = dataset.transform * dataset.transform.scale(
(dataset.width / data.shape[-1]),
(dataset.height / data.shape[-2])
)
resample = data.reshape(data.shape[0]*(data.shape[1], data.shape[0]*data.shape[2]))
res_del = np.delete(resample,0,1)
new_array = np.asarray(res_del).reshape(1,res_del.shape[0], res_del.shape[1])
meta = dataset.meta.copy()
meta.update({ "transform": transform, "height":new_array.shape[1],"width":new_array.shape[2]})
with rasterio.open(new_folder+file, 'w+', **meta) as dst:
dst.write(new_array)
return new_array
def resampling_60(folder, file, new_folder):
upscale_factor = 6
with rasterio.open(folder + file) as dataset:
# resample data to target shape
data = dataset.read(out_shape=(dataset.count,
int(dataset.height * upscale_factor),
int(dataset.width * upscale_factor)
),
resampling=Resampling.cubic)
# scale image transform
transform = dataset.transform * dataset.transform.scale(
(dataset.width / data.shape[-1]),
(dataset.height / data.shape[-2])
)
resample = data.reshape(data.shape[0]*(data.shape[1], data.shape[0]*data.shape[2]))
res_del = np.delete(resample,range(0,4),0)
res_del = np.delete(res_del,range(0,7),1)
new_array = np.asarray(res_del).reshape(1,res_del.shape[0], res_del.shape[1])
meta = dataset.meta.copy()
meta.update({ "transform": transform, "height":new_array.shape[1],"width":new_array.shape[2]})
with rasterio.open(new_folder+file, 'w+', **meta) as dst:
dst.write(new_array)
return new_array
def normalized_difference(img, b1, b2, eps=0.0001):
band1 = np.where((img[b1]==0) & (img[b2]==0), np.nan, img[b1])
band2 = np.where((img[b1]==0) & (img[b2]==0), np.nan, img[b2])
return (band1 - band2) / (band1 + band2)
def plot_masked_rgb(red, green, blue, mask, color_mask=(1, 0, 0), transparency=0.5, brightness=2):
# to improve our visualization, we will increase the brightness of our values
red = red / red.max() * brightness
green = green / green.max() * brightness
blue = blue / blue.max() * brightness
red = np.where(mask==True, red*transparency+color_mask[0]*(1-transparency), red)
green = np.where(mask==True, green*transparency+color_mask[1]*(1-transparency), green)
blue = np.where(mask==True, blue*transparency+color_mask[2]*(1-transparency), blue)
rgb = np.stack([red, green, blue], axis=2)
return rgb
|
{"/bbox_converter.py": ["/use_functions.py"]}
|
14,360
|
sustr4/Sentinel_tutorial
|
refs/heads/main
|
/coordinates_converter.py
|
"""
Converts coordinates from GPS coorodinates (latitude/longitude - epsg:4326) from geojson file to any chosen epsg projection
and saving these new coordinates to the new geojson file (new_file)
"""
import pyproj
import geojson
import json
def coor_converter(file, new_file, epsg):
# Transformation from GPS coordinates to desired epsg projection
transformer = pyproj.Transformer.from_crs("epsg:4326","epsg:"+str(epsg))
# Open geojson file with GPS coordinates
with open(file) as f:
gj = geojson.load(f)
# Load coordinates from geojson file
cdnts = gj['features'][0]['geometry']['coordinates']
# Transformation of coordinates
k = 0
n = len(cdnts)
m = len(cdnts[0])
trans_coord = [[0]*m for i in range(n)]
for i in range(len(cdnts)):
for j in range(len(cdnts[0])):
[x1, y1] = cdnts[i][j]
trans_coord[0][k] = transformer.transform(y1, x1)
k += 1
with open(file, 'r') as f:
data = json.load(f)
data['features'][0]['geometry']['coordinates'] = trans_coord
with open(new_file, 'w+') as f:
json.dump(data, f)
print("The file {} has been saved!".format(new_file))
|
{"/bbox_converter.py": ["/use_functions.py"]}
|
14,362
|
elessarelfstone/advarchs
|
refs/heads/master
|
/tests/test_advarchs.py
|
import os
import string
from contextlib import contextmanager
import pytest
from advarchs import __version__
from advarchs import download, filename_from_content_disposition, webfilename
from advarchs import extract, extract_web_archive
from advarchs.utils import get_hash_memory_optimized, file_ext
from tests.fixtures import local_archives
from tests import TEMP_DIR
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation if char not in '._-')
@contextmanager
def webfile(url):
webfname = webfilename(url)
# webfname = webfname.translate(remove_punctuation_map)
fpath = os.path.join(TEMP_DIR, webfname)
yield fpath
if os.path.exists(fpath):
os.remove(fpath)
@contextmanager
def localfile(fpath):
yield fpath
if os.path.exists(fpath):
os.remove(fpath)
def test_version():
assert __version__ == 'v0.1.7'
class TestDownloadUtils:
@pytest.mark.parametrize(
'header, expected_filename', [
('attachment; filename=hello-WORLD_123.txt', 'hello-WORLD_123.txt'),
('attachment; filename=".hello-WORLD_123.txt"', 'hello-WORLD_123.txt'),
('attachment; filename="white space.txt"', 'white space.txt'),
(r'attachment; filename="\"quotes\".txt"', '"quotes".txt'),
('attachment; filename=/etc/hosts', 'hosts'),
('attachment; filename=', None)
]
)
def test_filename_from_content_disposition(self, header, expected_filename):
assert filename_from_content_disposition(header) == expected_filename
@pytest.mark.parametrize(
'url', [
('https://drive.google.com/uc?export=download&id=1No0RIFMYJ7ymw7PT5id3JRh9Zu4UoZVj'),
('https://gist.github.com/elessarelfstone/627a59a72bb82826b8b23022fb92b446/raw/a6ebf46b805593dc8163d50f4eec3035f3e669e6/test_advarchs_direct_link.rar'),
('https://drive.google.com/uc?export=download&id=1cenn13H4u6YbNeusXyTp_eSeFAGvf06m'),
('https://drive.google.com/uc?export=download&id=1sJVR5oeknyt-dgpwZQ_ElVfywZ6UmlIm'),
]
)
def test_download(self, url):
with webfile(url) as apath:
f_size, _ = download(url, apath)
assert os.path.exists(apath)
assert f_size > 0
class TestAdvArchs:
# def test_archive_info(self, local_archives):
# apath, _ = local_archives
# arch_info = archive_info(apath)
# assert len(arch_info[0]) > 0
# assert len(arch_info[1]) > 0
# def test_files_list(self):
def test_extract_with_ext_as_filter(self, local_archives):
apath, files_hashes = local_archives
f_exts = [file_ext(f) for f in files_hashes.keys()]
out_files = extract(apath, f_exts)
for o_f in out_files:
assert os.path.exists(apath)
assert os.path.basename(o_f) in files_hashes.keys()
assert get_hash_memory_optimized(o_f) == files_hashes[os.path.basename(o_f)]
def test_extract_with_filename_as_filter(self, local_archives):
apath, files_hashes = local_archives
out_files = extract(apath, files_hashes.keys())
for o_f in out_files:
assert os.path.basename(o_f) in files_hashes.keys()
assert get_hash_memory_optimized(o_f) == files_hashes[os.path.basename(o_f)]
@pytest.mark.parametrize(
'url, ffilter, files', [
('https://gist.github.com/elessarelfstone/627a59a72bb82826b8b23022fb92b446/raw/48262cf304f33e396ea7f36f3c4c3b98698c0a48/test_advarchs_to_extract.rar',
['html', 'js', 'dumper.png'],
['index.html', 'bootstrap.js', 'dumper.png']
)
]
)
def test_extract_web_archive(self, url, ffilter, files):
with webfile(url) as apath:
out_files = extract_web_archive(url, apath, ffilter=ffilter)
for o_f in out_files:
with localfile(o_f) as fpath:
assert os.path.basename(fpath) in files
|
{"/tests/test_advarchs.py": ["/advarchs/__init__.py", "/advarchs/utils.py", "/tests/fixtures/__init__.py", "/tests/__init__.py"], "/tests/fixtures/__init__.py": ["/advarchs/utils.py", "/tests/__init__.py"], "/advarchs/handlers.py": ["/advarchs/utils.py"], "/advarchs/__init__.py": ["/advarchs/utils.py", "/advarchs/handlers.py"]}
|
14,363
|
elessarelfstone/advarchs
|
refs/heads/master
|
/tests/fixtures/__init__.py
|
import os
import pytest
from advarchs.utils import (
create_file,
add_file_to_zip,
add_file_to_tar,
random_string)
from tests import TEMP_DIR
TEST_LOCAL_ARCHIVES = [
("zip_test_local", add_file_to_zip, ["local_test.jpg", "local_test.png", "local_test.docx"
,"local_test.xlsx", "local_test.exe", "local_test1.txt"]),
("tar_test_local", add_file_to_tar, ["local_test.bin", "local_test2.psd", "local_test2.ini"]),
]
@pytest.fixture(params=TEST_LOCAL_ARCHIVES)
def local_archives(request):
arch = request.param
f_paths = []
f_hashes = {}
arch_name, arch_handler, files = arch
frmt = arch_name.split('_')[0]
arch_path = os.path.join(TEMP_DIR, "{}.{}".format(arch_name, frmt))
for f in files:
f_path = os.path.join(TEMP_DIR, f)
f_paths.append(f_path)
sha = create_file(f_path, random_string(500, 1000))
f_hashes[f] = sha
arch_handler(f_path, arch_path)
for f in f_paths:
os.remove(f)
yield arch_path, f_hashes
os.remove(arch_path)
|
{"/tests/test_advarchs.py": ["/advarchs/__init__.py", "/advarchs/utils.py", "/tests/fixtures/__init__.py", "/tests/__init__.py"], "/tests/fixtures/__init__.py": ["/advarchs/utils.py", "/tests/__init__.py"], "/advarchs/handlers.py": ["/advarchs/utils.py"], "/advarchs/__init__.py": ["/advarchs/utils.py", "/advarchs/handlers.py"]}
|
14,364
|
elessarelfstone/advarchs
|
refs/heads/master
|
/advarchs/handlers.py
|
import abc
import re
import os
import sys
from enum import Enum
from itertools import groupby
from advarchs.utils import run_with_output
CONSOLE_CODING = 'utf8'
if sys.platform == 'win32':
CONSOLE_CODING = 'cp866'
class ArchiveStatus(Enum):
ALL_GOOD = 0
NOT_COMPATIBLE = 1
CORRUPTED = 2
UNKNOWN_ERROR = 3
class AdvarchsExtractException(Exception):
pass
class ArchiveHandlerBase(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def unpacker(self):
""""""
return
@abc.abstractmethod
def files_list(self, apath):
""" Get the archive's content list """
return
@abc.abstractmethod
def check(self, apath):
""" Check archive if it's corrupted """
return
@abc.abstractmethod
def extract(self, apath, ffilter):
""" Extract files from archive """
return
class HandlersFactory:
""" Factory to get """
_handlers = {}
@classmethod
def get_handler(cls, name):
try:
return cls._handlers[name]
except KeyError:
raise ValueError(name)
@classmethod
def register(cls, name, handler):
cls._handlers[name] = handler
@classmethod
def handlers(cls):
return cls._handlers
class SevenZHandler(ArchiveHandlerBase):
re_not_compatible_pattern = r"can not open the file as archive"
re_success_pattern = r"everything is ok"
re_corruption_pattern = r"data error"
def __init__(self, unpacker):
self._unpacker = unpacker
def _files_info(self, apath):
r, out, _ = run_with_output([self.unpacker(), 'l', '-slt', apath], CONSOLE_CODING)
raw = re.sub(r"^-+", '-' * 10, out, flags=re.MULTILINE).split('-' * 10)[2]
blocks = []
current_block = {}
# make flat list of clean stdout's lines
lines = [line.strip() for line in raw.strip().split('\n')]
# break down flat list with details on lists for each file in archive
block_list = [list(g) for k, g in groupby(lines, lambda x: x != '') if k]
for block in block_list:
for line in block:
key, _, value = line.partition('=')
current_block[key.strip().lower()] = value.strip()
blocks.append(current_block)
current_block = {}
return blocks
def _tech_info(self, apath):
r, out, _ = run_with_output([self.unpacker(), 'l', '-slt', apath], CONSOLE_CODING)
raw = re.sub(r"^-+", '-' * 10, out, flags=re.MULTILINE).split('-' * 10)[1]
t_info = {}
for line in raw.strip().split('\n'):
key, _, value = line.partition('=')
t_info[key.strip().lower()] = value.strip().lower()
return t_info
def unpacker(self):
return self._unpacker
def check(self, apath):
r, out, err = run_with_output([self.unpacker(), 't', apath], CONSOLE_CODING)
if r == 0:
return ArchiveStatus.ALL_GOOD
else:
if not re.search(self.re_success_pattern, out):
if re.search(self.re_not_compatible_pattern, err):
return ArchiveStatus.NOT_COMPATIBLE
elif re.search(self.re_corruption_pattern, err):
return ArchiveStatus.CORRUPTED
else:
return ArchiveStatus.UNKNOWN_ERROR
def files_list(self, apath):
a_files_info = self._files_info(apath)
return [f["path"] for f in a_files_info]
def extract(self, apath, afile):
dfolder = '-o' + os.path.dirname(apath)
args = [self.unpacker(), 'e', '-aoa', apath, afile, dfolder]
r, out, err = run_with_output(args, CONSOLE_CODING)
if r != 0:
raise AdvarchsExtractException('Could not extract archive.')
f_path = os.path.join(os.path.dirname(apath), afile)
return f_path
class RarHandler(ArchiveHandlerBase):
re_not_compatible_pattern = r"is not rar archive"
re_success_pattern = r"all ок"
re_corruption_pattern = r"total errors:"
def __init__(self, unpacker):
self._unpacker = unpacker
def unpacker(self):
return self._unpacker
def _files_info(self, apath):
r, out, _ = run_with_output([self.unpacker(), 'ltab', apath], CONSOLE_CODING)
raw = re.search(r"([ \t]*name:.*?)(?=(\n{1,2}service:\s*eof|\Z))", out, re.M | re.S).group(1)
blocks = []
current_block = {}
# make flat list of clean stdout's lines
lines = [line.strip() for line in raw.strip().split('\n')]
# break down flat list with details on lists for each file in archive
block_list = [list(g) for k, g in groupby(lines, lambda x: x != '') if k]
for block in block_list:
for line in block:
key, _, value = line.partition(': ')
current_block[key.strip().lower()] = value.strip()
blocks.append(current_block)
current_block = {}
return blocks
def files_list(self, apath):
a_files_info = self._files_info(apath)
return [f["name"] for f in a_files_info if "type" in f.keys() and f["type"].lower() == "file"]
def check(self, apath):
r, out, err = run_with_output([self.unpacker(), 't', apath], CONSOLE_CODING)
if r == 0:
return ArchiveStatus.ALL_GOOD
else:
if not re.search(self.re_success_pattern, out):
if re.search(self.re_not_compatible_pattern, out):
return ArchiveStatus.NOT_COMPATIBLE
elif re.search(self.re_corruption_pattern, out):
return ArchiveStatus.CORRUPTED
else:
return ArchiveStatus.UNKNOWN_ERROR
def extract(self, apath, afile):
args = [self.unpacker(), 'e', '-o+', apath, afile]
r, out, err = run_with_output(args, CONSOLE_CODING, cwd=os.path.dirname(apath))
if r != 0:
raise AdvarchsExtractException('Could not extract archive.')
f_path = os.path.join(os.path.dirname(apath), afile)
return f_path
|
{"/tests/test_advarchs.py": ["/advarchs/__init__.py", "/advarchs/utils.py", "/tests/fixtures/__init__.py", "/tests/__init__.py"], "/tests/fixtures/__init__.py": ["/advarchs/utils.py", "/tests/__init__.py"], "/advarchs/handlers.py": ["/advarchs/utils.py"], "/advarchs/__init__.py": ["/advarchs/utils.py", "/advarchs/handlers.py"]}
|
14,365
|
elessarelfstone/advarchs
|
refs/heads/master
|
/advarchs/__init__.py
|
import os
from shutil import which
import string
import tempfile
from mailbox import Message
import requests
from advarchs.utils import file_ext, extract_version, get_hash_memory_optimized
from advarchs.handlers import (HandlersFactory, AdvarchsExtractException,
ArchiveStatus, SevenZHandler, RarHandler)
__all__ = ['webfilename', 'extract_web_archive', 'AdvArchs']
ARCHIVE_COMPRESS_FORMATS = ('rar', 'tar', 'zip', 'gzip', 'bzip', 'gz')
__version__ = extract_version(__file__)
REMOVE_PUNCTUATION = dict((ord(char), None) for char in string.punctuation if char not in '._-')
# get appropriate cli command name for installed 7z
SEVENZ = max([a if which(a) else None for a in ('7z', '7za')], key=lambda x: bool(x), default=None)
UNRAR = 'unrar' if which('unrar') else None
if os.name == 'nt':
if SEVENZ:
HandlersFactory.register(SEVENZ, SevenZHandler(SEVENZ))
else:
raise AdvarchsExtractException('Unpacker is not installed.')
elif os.name == 'posix':
if SEVENZ and UNRAR:
HandlersFactory.register(SEVENZ, SevenZHandler(SEVENZ))
HandlersFactory.register(UNRAR, RarHandler(UNRAR))
elif SEVENZ and (not UNRAR):
HandlersFactory.register(SEVENZ, SevenZHandler(SEVENZ))
else:
raise AdvarchsExtractException('Unpacker is not installed.')
class AdvarchsDownloadException(Exception):
pass
def filename_from_content_disposition(content_disposition):
""" Extract and validate filename from a Content-Disposition header. """
msg = Message('Content-Disposition: %s' % content_disposition)
filename = msg.get_filename()
if filename:
# Basic sanitation.
filename = os.path.basename(filename).lstrip('.').strip()
if filename:
return filename
def _get_headers_from_url(url):
with requests.get(url, stream=True) as r:
return r.headers
def _content_disposition(headers):
return headers.get("content-disposition")
def webfilename(url):
"""Get filename from archive's headers or from the url"""
headers = _get_headers_from_url(url)
if _content_disposition(headers):
result = filename_from_content_disposition(_content_disposition(headers))
else:
result = url.split("/")[-1]
return result.translate(REMOVE_PUNCTUATION)
def download(url, fpath):
"""Download file using streaming"""
with open(fpath, 'wb') as f:
try:
with requests.get(url, stream=True) as r:
r.raise_for_status()
f_size = 0
for chunk in r.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
f_size += len(chunk)
f_hash = get_hash_memory_optimized(fpath)
return f_size, f_hash
except Exception as e:
os.remove(fpath)
raise AdvarchsDownloadException('Could not download file.' + e.message)
def is_matched(afile, ffilter=[]):
""" Check if file in archive should be extracted """
if ffilter:
# we check only full name and extension of file
if (os.path.basename(afile) in ffilter) or (file_ext(afile) in ffilter):
return True
else:
return False
return True
def is_archive(afile):
"""Check if inside file can be archive or compressed"""
return file_ext(os.path.basename(afile)) in ARCHIVE_COMPRESS_FORMATS
def resolve_format(apath):
""" Resolve right handler for archive """
status = ArchiveStatus.NOT_COMPATIBLE
handlers = HandlersFactory.handlers()
for handler in dict(handlers):
unpacker = handlers[handler]
status = unpacker.check(apath)
if unpacker.check(apath) == ArchiveStatus.ALL_GOOD:
return handler
if status == ArchiveStatus.CORRUPTED:
raise AdvarchsExtractException('Could not unpack. Archive is corrupted')
elif status == ArchiveStatus.NOT_COMPATIBLE:
raise AdvarchsExtractException('Could not unpack. Archive format is not supported')
elif status == ArchiveStatus.UNKNOWN_ERROR:
raise AdvarchsExtractException('Could not unpack. Unknown error')
def extract(apath, ffilter=[]):
""" Extract files from archive """
files = []
def extract_recursive(curr_apath):
"""Look into archive recursively to extract files considering ffilter"""
handler = resolve_format(curr_apath)
unpacker = HandlersFactory.get_handler(handler)
_files = unpacker.files_list(curr_apath)
for f in _files:
if is_matched(f, ffilter=ffilter):
_fpath = unpacker.extract(curr_apath, f)
files.append(_fpath)
if is_archive(f):
_apath = unpacker.extract(curr_apath, f)
extract_recursive(_apath)
extract_recursive(apath)
return files
def inspect(apath):
""" Look into archive recursively to retrieve list of all files """
files = []
def inspect_into(curr_apath):
handler = resolve_format(curr_apath)
unpacker = HandlersFactory.get_handler(handler)
_files = unpacker.files_list(curr_apath)
for f in _files:
# go into nested archive or compressed file
if is_archive(f):
_apath = unpacker.extract(curr_apath, f)
inspect_into(_apath)
else:
files.append(f)
inspect_into(apath)
return files
def extract_web_archive(url, apath, ffilter=[]):
""" Download archive and extract all or specified files"""
download(url, apath)
output_files = extract(apath, ffilter=ffilter)
return output_files
class AdvArchs:
_archives = {}
@classmethod
def _download(cls, url, apath):
_, f_hash = download(url, apath)
cls._archives[apath] = f_hash
@classmethod
def files_list(cls, url, apath, ffilter=[]):
""" Retrieve list of files considering ffilter"""
files = []
if apath not in cls._archives.keys():
cls._download(url, apath)
_files = inspect(apath)
for f in _files:
if is_matched(f, ffilter):
files.append(f)
return files
@classmethod
def extract_web_archive(cls, url, apath, ffilter=[]):
""" Download archive and extract all or specified files"""
if apath not in cls._archives.keys():
download(url, apath)
_files = extract(apath, ffilter=ffilter)
return _files
|
{"/tests/test_advarchs.py": ["/advarchs/__init__.py", "/advarchs/utils.py", "/tests/fixtures/__init__.py", "/tests/__init__.py"], "/tests/fixtures/__init__.py": ["/advarchs/utils.py", "/tests/__init__.py"], "/advarchs/handlers.py": ["/advarchs/utils.py"], "/advarchs/__init__.py": ["/advarchs/utils.py", "/advarchs/handlers.py"]}
|
14,366
|
elessarelfstone/advarchs
|
refs/heads/master
|
/tests/__init__.py
|
import tempfile
TEMP_DIR = tempfile.gettempdir()
|
{"/tests/test_advarchs.py": ["/advarchs/__init__.py", "/advarchs/utils.py", "/tests/fixtures/__init__.py", "/tests/__init__.py"], "/tests/fixtures/__init__.py": ["/advarchs/utils.py", "/tests/__init__.py"], "/advarchs/handlers.py": ["/advarchs/utils.py"], "/advarchs/__init__.py": ["/advarchs/utils.py", "/advarchs/handlers.py"]}
|
14,367
|
elessarelfstone/advarchs
|
refs/heads/master
|
/advarchs/utils.py
|
import os
import hashlib
import tarfile
import subprocess as subp
from random import choice, randint
from string import ascii_uppercase
from zipfile import ZipFile
from pathlib import Path
import tomlkit
def extract_version(source_file):
""" Extract package version from pyproject file """
d = Path(source_file)
result = None
while d.parent != d and result is None:
d = d.parent
pyproject_toml_path = d / 'pyproject.toml'
if pyproject_toml_path.exists():
with open(file=str(pyproject_toml_path)) as f:
pyproject_toml = tomlkit.parse(string=f.read())
if 'tool' in pyproject_toml and 'poetry' in pyproject_toml['tool']:
# noinspection PyUnresolvedReferences
result = pyproject_toml['tool']['poetry']['version']
return result
def get_hash_memory_optimized(f_path, mode='sha256'):
""" Get hash of file"""
h = hashlib.new(mode)
with open(f_path, 'rb') as file:
block = file.read(4096)
while block:
h.update(block)
block = file.read(4096)
return h.hexdigest()
def read_file(file, encoding="utf8"):
""" Simple reading text file """
with open(file, "r", encoding=encoding) as f:
result = f.read()
return result
def create_file(file, data, encoding="utf8"):
""" Create text file and return hash of it """
with open(file, "w", encoding=encoding) as f:
f.write(data)
return get_hash_memory_optimized(file)
def add_file_to_zip(fpath, apath):
""" Add file to zip archive"""
with ZipFile(apath, 'a') as zip_o:
zip_o.write(fpath, arcname=os.path.basename(fpath))
def add_file_to_tar(fpath, apath):
""" Add file to tar archive"""
with tarfile.open(apath, "a") as tar_o:
tar_o.add(fpath, arcname=os.path.basename(fpath))
def file_ext(f):
""" File extension """
return Path(f).suffix.replace('.', '')
def random_string(min_l, max_l):
""" Get random text of length ranging from min_l to max_l """
return ''.join(choice(ascii_uppercase) for i in range(randint(min_l, max_l)))
def run_with_output(args, encoding, **kwargs):
""" Run program """
res = subp.Popen(args, stdout=subp.PIPE, stderr=subp.PIPE, **kwargs)
stdout, stderr = res.communicate()
return res.returncode, stdout.decode(encoding).lower(), stderr.decode(encoding).lower()
|
{"/tests/test_advarchs.py": ["/advarchs/__init__.py", "/advarchs/utils.py", "/tests/fixtures/__init__.py", "/tests/__init__.py"], "/tests/fixtures/__init__.py": ["/advarchs/utils.py", "/tests/__init__.py"], "/advarchs/handlers.py": ["/advarchs/utils.py"], "/advarchs/__init__.py": ["/advarchs/utils.py", "/advarchs/handlers.py"]}
|
14,416
|
chakra34/SphericalOrientations
|
refs/heads/master
|
/Code/Spherical/orientation.py
|
# -*- coding: UTF-8 no BOM -*-
# obtained from https://damask.mpie.de #
###################################################
# NOTE: everything here needs to be a np array #
###################################################
import math,os
import numpy as np
# ******************************************************************************************
class Rodrigues:
def __init__(self, vector = np.zeros(3)):
self.vector = vector
def asQuaternion(self):
norm = np.linalg.norm(self.vector)
halfAngle = np.arctan(norm)
return Quaternion(np.cos(halfAngle),np.sin(halfAngle)*self.vector/norm)
def asAngleAxis(self):
norm = np.linalg.norm(self.vector)
halfAngle = np.arctan(norm)
return (2.0*halfAngle,self.vector/norm)
# ******************************************************************************************
class Quaternion:
"""
Orientation represented as unit quaternion
All methods and naming conventions based on http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions
w is the real part, (x, y, z) are the imaginary parts
Representation of rotation is in ACTIVE form!
(derived directly or through angleAxis, Euler angles, or active matrix)
vector "a" (defined in coordinate system "A") is actively rotated to new coordinates "b"
b = Q * a
b = np.dot(Q.asMatrix(),a)
"""
def __init__(self,
quatArray = [1.0,0.0,0.0,0.0]):
"""initializes to identity if not given"""
self.w, \
self.x, \
self.y, \
self.z = quatArray
self.homomorph()
def __iter__(self):
"""components"""
return iter([self.w,self.x,self.y,self.z])
def __copy__(self):
"""create copy"""
Q = Quaternion([self.w,self.x,self.y,self.z])
return Q
copy = __copy__
def __repr__(self):
"""readbable string"""
return 'Quaternion(real=%+.6f, imag=<%+.6f, %+.6f, %+.6f>)' % \
(self.w, self.x, self.y, self.z)
def __pow__(self, exponent):
"""power"""
omega = math.acos(self.w)
vRescale = math.sin(exponent*omega)/math.sin(omega)
Q = Quaternion()
Q.w = math.cos(exponent*omega)
Q.x = self.x * vRescale
Q.y = self.y * vRescale
Q.z = self.z * vRescale
return Q
def __ipow__(self, exponent):
"""in place power"""
omega = math.acos(self.w)
vRescale = math.sin(exponent*omega)/math.sin(omega)
self.w = np.cos(exponent*omega)
self.x *= vRescale
self.y *= vRescale
self.z *= vRescale
return self
def __mul__(self, other):
"""multiplication"""
try: # quaternion
Aw = self.w
Ax = self.x
Ay = self.y
Az = self.z
Bw = other.w
Bx = other.x
By = other.y
Bz = other.z
Q = Quaternion()
Q.w = - Ax * Bx - Ay * By - Az * Bz + Aw * Bw
Q.x = + Ax * Bw + Ay * Bz - Az * By + Aw * Bx
Q.y = - Ax * Bz + Ay * Bw + Az * Bx + Aw * By
Q.z = + Ax * By - Ay * Bx + Az * Bw + Aw * Bz
return Q
except: pass
try: # vector (perform active rotation, i.e. q*v*q.conjugated)
w = self.w
x = self.x
y = self.y
z = self.z
Vx = other[0]
Vy = other[1]
Vz = other[2]
return np.array([\
w * w * Vx + 2 * y * w * Vz - 2 * z * w * Vy + \
x * x * Vx + 2 * y * x * Vy + 2 * z * x * Vz - \
z * z * Vx - y * y * Vx,
2 * x * y * Vx + y * y * Vy + 2 * z * y * Vz + \
2 * w * z * Vx - z * z * Vy + w * w * Vy - \
2 * x * w * Vz - x * x * Vy,
2 * x * z * Vx + 2 * y * z * Vy + \
z * z * Vz - 2 * w * y * Vx - y * y * Vz + \
2 * w * x * Vy - x * x * Vz + w * w * Vz ])
except: pass
try: # scalar
Q = self.copy()
Q.w *= other
Q.x *= other
Q.y *= other
Q.z *= other
return Q
except:
return self.copy()
def __imul__(self, other):
"""in place multiplication"""
try: # Quaternion
Ax = self.x
Ay = self.y
Az = self.z
Aw = self.w
Bx = other.x
By = other.y
Bz = other.z
Bw = other.w
self.x = Ax * Bw + Ay * Bz - Az * By + Aw * Bx
self.y = -Ax * Bz + Ay * Bw + Az * Bx + Aw * By
self.z = Ax * By - Ay * Bx + Az * Bw + Aw * Bz
self.w = -Ax * Bx - Ay * By - Az * Bz + Aw * Bw
except: pass
return self
def __div__(self, other):
"""division"""
if isinstance(other, (int,float)):
w = self.w / other
x = self.x / other
y = self.y / other
z = self.z / other
return self.__class__([w,x,y,z])
else:
return NotImplemented
def __idiv__(self, other):
"""in place division"""
if isinstance(other, (int,float)):
self.w /= other
self.x /= other
self.y /= other
self.z /= other
return self
def __add__(self, other):
"""addition"""
if isinstance(other, Quaternion):
w = self.w + other.w
x = self.x + other.x
y = self.y + other.y
z = self.z + other.z
return self.__class__([w,x,y,z])
else:
return NotImplemented
def __iadd__(self, other):
"""in place division"""
if isinstance(other, Quaternion):
self.w += other.w
self.x += other.x
self.y += other.y
self.z += other.z
return self
def __sub__(self, other):
"""subtraction"""
if isinstance(other, Quaternion):
Q = self.copy()
Q.w -= other.w
Q.x -= other.x
Q.y -= other.y
Q.z -= other.z
return Q
else:
return self.copy()
def __isub__(self, other):
"""in place subtraction"""
if isinstance(other, Quaternion):
self.w -= other.w
self.x -= other.x
self.y -= other.y
self.z -= other.z
return self
def __neg__(self):
"""additive inverse"""
self.w = -self.w
self.x = -self.x
self.y = -self.y
self.z = -self.z
return self
def __abs__(self):
"""norm"""
return math.sqrt(self.w ** 2 + \
self.x ** 2 + \
self.y ** 2 + \
self.z ** 2)
magnitude = __abs__
def __eq__(self,other):
"""equal at e-8 precision"""
return (abs(self.w-other.w) < 1e-8 and \
abs(self.x-other.x) < 1e-8 and \
abs(self.y-other.y) < 1e-8 and \
abs(self.z-other.z) < 1e-8) \
or \
(abs(-self.w-other.w) < 1e-8 and \
abs(-self.x-other.x) < 1e-8 and \
abs(-self.y-other.y) < 1e-8 and \
abs(-self.z-other.z) < 1e-8)
def __ne__(self,other):
"""not equal at e-8 precision"""
return not self.__eq__(self,other)
def __cmp__(self,other):
"""linear ordering"""
return cmp(self.Rodrigues(),other.Rodrigues())
def magnitude_squared(self):
return self.w ** 2 + \
self.x ** 2 + \
self.y ** 2 + \
self.z ** 2
def identity(self):
self.w = 1.
self.x = 0.
self.y = 0.
self.z = 0.
return self
def normalize(self):
d = self.magnitude()
if d > 0.0:
self /= d
return self
def conjugate(self):
self.x = -self.x
self.y = -self.y
self.z = -self.z
return self
def inverse(self):
d = self.magnitude()
if d > 0.0:
self.conjugate()
self /= d
return self
def homomorph(self):
if self.w < 0.0:
self.w = -self.w
self.x = -self.x
self.y = -self.y
self.z = -self.z
return self
def normalized(self):
return self.copy().normalize()
def conjugated(self):
return self.copy().conjugate()
def inversed(self):
return self.copy().inverse()
def homomorphed(self):
return self.copy().homomorph()
def asList(self):
return [i for i in self]
def asM(self): # to find Averaging Quaternions (see F. Landis Markley et al.)
return np.outer([i for i in self],[i for i in self])
def asMatrix(self):
return np.array(
[[1.0-2.0*(self.y*self.y+self.z*self.z), 2.0*(self.x*self.y-self.z*self.w), 2.0*(self.x*self.z+self.y*self.w)],
[ 2.0*(self.x*self.y+self.z*self.w), 1.0-2.0*(self.x*self.x+self.z*self.z), 2.0*(self.y*self.z-self.x*self.w)],
[ 2.0*(self.x*self.z-self.y*self.w), 2.0*(self.x*self.w+self.y*self.z), 1.0-2.0*(self.x*self.x+self.y*self.y)]])
def asAngleAxis(self,
degrees = False):
if self.w > 1:
self.normalize()
s = math.sqrt(1. - self.w**2)
x = 2*self.w**2 - 1.
y = 2*self.w * s
angle = math.atan2(y,x)
if angle < 0.0:
angle *= -1.
s *= -1.
return (np.degrees(angle) if degrees else angle,
np.array([1.0, 0.0, 0.0] if np.abs(angle) < 1e-6 else [self.x / s, self.y / s, self.z / s]))
def asRodrigues(self):
return np.inf*np.ones(3) if self.w == 0.0 else np.array([self.x, self.y, self.z])/self.w
def asEulers(self,
type = "bunge",
degrees = False,
standardRange = False):
"""
Orientation as Bunge-Euler angles
conversion of ACTIVE rotation to Euler angles taken from:
Melcher, A.; Unser, A.; Reichhardt, M.; Nestler, B.; Poetschke, M.; Selzer, M.
Conversion of EBSD data by a quaternion based algorithm to be used for grain structure simulations
Technische Mechanik 30 (2010) pp 401--413
"""
angles = [0.0,0.0,0.0]
if type.lower() == 'bunge' or type.lower() == 'zxz':
if abs(self.x) < 1e-4 and abs(self.y) < 1e-4:
x = self.w**2 - self.z**2
y = 2.*self.w*self.z
angles[0] = math.atan2(y,x)
elif abs(self.w) < 1e-4 and abs(self.z) < 1e-4:
x = self.x**2 - self.y**2
y = 2.*self.x*self.y
angles[0] = math.atan2(y,x)
angles[1] = math.pi
else:
chi = math.sqrt((self.w**2 + self.z**2)*(self.x**2 + self.y**2))
x = (self.w * self.x - self.y * self.z)/2./chi
y = (self.w * self.y + self.x * self.z)/2./chi
angles[0] = math.atan2(y,x)
x = self.w**2 + self.z**2 - (self.x**2 + self.y**2)
y = 2.*chi
angles[1] = math.atan2(y,x)
x = (self.w * self.x + self.y * self.z)/2./chi
y = (self.z * self.x - self.y * self.w)/2./chi
angles[2] = math.atan2(y,x)
if standardRange:
angles[0] %= 2*math.pi
if angles[1] < 0.0:
angles[1] += math.pi
angles[2] *= -1.0
angles[2] %= 2*math.pi
return np.degrees(angles) if degrees else angles
# # Static constructors
@classmethod
def fromIdentity(cls):
return cls()
@classmethod
def fromRandom(cls,randomSeed = None):
if randomSeed is None:
randomSeed = int(os.urandom(4).encode('hex'), 16)
np.random.seed(randomSeed)
r = np.random.random(3)
w = math.cos(2.0*math.pi*r[0])*math.sqrt(r[2])
x = math.sin(2.0*math.pi*r[1])*math.sqrt(1.0-r[2])
y = math.cos(2.0*math.pi*r[1])*math.sqrt(1.0-r[2])
z = math.sin(2.0*math.pi*r[0])*math.sqrt(r[2])
return cls([w,x,y,z])
@classmethod
def fromRodrigues(cls, rodrigues):
if not isinstance(rodrigues, np.ndarray): rodrigues = np.array(rodrigues)
halfangle = math.atan(np.linalg.norm(rodrigues))
c = math.cos(halfangle)
w = c
x,y,z = c*rodrigues
return cls([w,x,y,z])
@classmethod
def fromAngleAxis(cls,
angle,
axis,
degrees = False):
if not isinstance(axis, np.ndarray): axis = np.array(axis,dtype='d')
axis = axis.astype(float)/np.linalg.norm(axis)
angle = np.radians(angle) if degrees else angle
s = math.sin(0.5 * angle)
w = math.cos(0.5 * angle)
x = axis[0] * s
y = axis[1] * s
z = axis[2] * s
return cls([w,x,y,z])
@classmethod
def fromEulers(cls,
eulers,
type = 'Bunge',
degrees = False):
if not isinstance(eulers, np.ndarray): eulers = np.array(eulers,dtype='d')
eulers = np.radians(eulers) if degrees else eulers
c = np.cos(0.5 * eulers)
s = np.sin(0.5 * eulers)
if type.lower() == 'bunge' or type.lower() == 'zxz':
w = c[0] * c[1] * c[2] - s[0] * c[1] * s[2]
x = c[0] * s[1] * c[2] + s[0] * s[1] * s[2]
y = - c[0] * s[1] * s[2] + s[0] * s[1] * c[2]
z = c[0] * c[1] * s[2] + s[0] * c[1] * c[2]
else:
w = c[0] * c[1] * c[2] - s[0] * s[1] * s[2]
x = s[0] * s[1] * c[2] + c[0] * c[1] * s[2]
y = s[0] * c[1] * c[2] + c[0] * s[1] * s[2]
z = c[0] * s[1] * c[2] - s[0] * c[1] * s[2]
return cls([w,x,y,z])
# Modified Method to calculate Quaternion from Orientation Matrix,
# Source: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/
@classmethod
def fromMatrix(cls, m):
if m.shape != (3,3) and np.prod(m.shape) == 9:
m = m.reshape(3,3)
tr = np.trace(m)
if tr > 1e-8:
s = math.sqrt(tr + 1.0)*2.0
return cls(
[ s*0.25,
(m[2,1] - m[1,2])/s,
(m[0,2] - m[2,0])/s,
(m[1,0] - m[0,1])/s,
])
elif m[0,0] > m[1,1] and m[0,0] > m[2,2]:
t = m[0,0] - m[1,1] - m[2,2] + 1.0
s = 2.0*math.sqrt(t)
return cls(
[ (m[2,1] - m[1,2])/s,
s*0.25,
(m[0,1] + m[1,0])/s,
(m[2,0] + m[0,2])/s,
])
elif m[1,1] > m[2,2]:
t = -m[0,0] + m[1,1] - m[2,2] + 1.0
s = 2.0*math.sqrt(t)
return cls(
[ (m[0,2] - m[2,0])/s,
(m[0,1] + m[1,0])/s,
s*0.25,
(m[1,2] + m[2,1])/s,
])
else:
t = -m[0,0] - m[1,1] + m[2,2] + 1.0
s = 2.0*math.sqrt(t)
return cls(
[ (m[1,0] - m[0,1])/s,
(m[2,0] + m[0,2])/s,
(m[1,2] + m[2,1])/s,
s*0.25,
])
@classmethod
def new_interpolate(cls, q1, q2, t):
"""
interpolation
see http://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/20070017872_2007014421.pdf
for (another?) way to interpolate quaternions
"""
assert isinstance(q1, Quaternion) and isinstance(q2, Quaternion)
Q = cls()
costheta = q1.w * q2.w + q1.x * q2.x + q1.y * q2.y + q1.z * q2.z
if costheta < 0.:
costheta = -costheta
q1 = q1.conjugated()
elif costheta > 1:
costheta = 1
theta = math.acos(costheta)
if abs(theta) < 0.01:
Q.w = q2.w
Q.x = q2.x
Q.y = q2.y
Q.z = q2.z
return Q
sintheta = math.sqrt(1.0 - costheta * costheta)
if abs(sintheta) < 0.01:
Q.w = (q1.w + q2.w) * 0.5
Q.x = (q1.x + q2.x) * 0.5
Q.y = (q1.y + q2.y) * 0.5
Q.z = (q1.z + q2.z) * 0.5
return Q
ratio1 = math.sin((1 - t) * theta) / sintheta
ratio2 = math.sin(t * theta) / sintheta
Q.w = q1.w * ratio1 + q2.w * ratio2
Q.x = q1.x * ratio1 + q2.x * ratio2
Q.y = q1.y * ratio1 + q2.y * ratio2
Q.z = q1.z * ratio1 + q2.z * ratio2
return Q
# ******************************************************************************************
class Symmetry:
lattices = [None,'orthorhombic','tetragonal','hexagonal','cubic',]
def __init__(self, symmetry = None):
"""lattice with given symmetry, defaults to None"""
if isinstance(symmetry, str) and symmetry.lower() in Symmetry.lattices:
self.lattice = symmetry.lower()
else:
self.lattice = None
def __copy__(self):
"""copy"""
return self.__class__(self.lattice)
copy = __copy__
def __repr__(self):
"""readbable string"""
return '%s' % (self.lattice)
def __eq__(self, other):
"""equal"""
return self.lattice == other.lattice
def __neq__(self, other):
"""not equal"""
return not self.__eq__(other)
def __cmp__(self,other):
"""linear ordering"""
return cmp(Symmetry.lattices.index(self.lattice),Symmetry.lattices.index(other.lattice))
def symmetryQuats(self,who = []):
"""List of symmetry operations as quaternions."""
if self.lattice == 'cubic':
symQuats = [
[ 1.0, 0.0, 0.0, 0.0 ],
[ 0.0, 1.0, 0.0, 0.0 ],
[ 0.0, 0.0, 1.0, 0.0 ],
[ 0.0, 0.0, 0.0, 1.0 ],
[ 0.0, 0.0, 0.5*math.sqrt(2), 0.5*math.sqrt(2) ],
[ 0.0, 0.0, 0.5*math.sqrt(2),-0.5*math.sqrt(2) ],
[ 0.0, 0.5*math.sqrt(2), 0.0, 0.5*math.sqrt(2) ],
[ 0.0, 0.5*math.sqrt(2), 0.0, -0.5*math.sqrt(2) ],
[ 0.0, 0.5*math.sqrt(2),-0.5*math.sqrt(2), 0.0 ],
[ 0.0, -0.5*math.sqrt(2),-0.5*math.sqrt(2), 0.0 ],
[ 0.5, 0.5, 0.5, 0.5 ],
[-0.5, 0.5, 0.5, 0.5 ],
[-0.5, 0.5, 0.5, -0.5 ],
[-0.5, 0.5, -0.5, 0.5 ],
[-0.5, -0.5, 0.5, 0.5 ],
[-0.5, -0.5, 0.5, -0.5 ],
[-0.5, -0.5, -0.5, 0.5 ],
[-0.5, 0.5, -0.5, -0.5 ],
[-0.5*math.sqrt(2), 0.0, 0.0, 0.5*math.sqrt(2) ],
[ 0.5*math.sqrt(2), 0.0, 0.0, 0.5*math.sqrt(2) ],
[-0.5*math.sqrt(2), 0.0, 0.5*math.sqrt(2), 0.0 ],
[-0.5*math.sqrt(2), 0.0, -0.5*math.sqrt(2), 0.0 ],
[-0.5*math.sqrt(2), 0.5*math.sqrt(2), 0.0, 0.0 ],
[-0.5*math.sqrt(2),-0.5*math.sqrt(2), 0.0, 0.0 ],
]
elif self.lattice == 'hexagonal':
symQuats = [
[ 1.0,0.0,0.0,0.0 ],
[-0.5*math.sqrt(3), 0.0, 0.0,-0.5 ],
[ 0.5, 0.0, 0.0, 0.5*math.sqrt(3) ],
[ 0.0,0.0,0.0,1.0 ],
[-0.5, 0.0, 0.0, 0.5*math.sqrt(3) ],
[-0.5*math.sqrt(3), 0.0, 0.0, 0.5 ],
[ 0.0,1.0,0.0,0.0 ],
[ 0.0,-0.5*math.sqrt(3), 0.5, 0.0 ],
[ 0.0, 0.5,-0.5*math.sqrt(3), 0.0 ],
[ 0.0,0.0,1.0,0.0 ],
[ 0.0,-0.5,-0.5*math.sqrt(3), 0.0 ],
[ 0.0, 0.5*math.sqrt(3), 0.5, 0.0 ],
]
elif self.lattice == 'tetragonal':
symQuats = [
[ 1.0,0.0,0.0,0.0 ],
[ 0.0,1.0,0.0,0.0 ],
[ 0.0,0.0,1.0,0.0 ],
[ 0.0,0.0,0.0,1.0 ],
[ 0.0, 0.5*math.sqrt(2), 0.5*math.sqrt(2), 0.0 ],
[ 0.0,-0.5*math.sqrt(2), 0.5*math.sqrt(2), 0.0 ],
[ 0.5*math.sqrt(2), 0.0, 0.0, 0.5*math.sqrt(2) ],
[-0.5*math.sqrt(2), 0.0, 0.0, 0.5*math.sqrt(2) ],
]
elif self.lattice == 'orthorhombic':
symQuats = [
[ 1.0,0.0,0.0,0.0 ],
[ 0.0,1.0,0.0,0.0 ],
[ 0.0,0.0,1.0,0.0 ],
[ 0.0,0.0,0.0,1.0 ],
]
else:
symQuats = [
[ 1.0,0.0,0.0,0.0 ],
]
return list(map(Quaternion,
np.array(symQuats)[np.atleast_1d(np.array(who)) if who != [] else range(len(symQuats))]))
def equivalentQuaternions(self,
quaternion,
who = []):
"""List of symmetrically equivalent quaternions based on own symmetry."""
return [quaternion*q for q in self.symmetryQuats(who)]
def inFZ(self,R):
"""Check whether given Rodrigues vector falls into fundamental zone of own symmetry."""
if isinstance(R, Quaternion): R = R.asRodrigues() # translate accidentially passed quaternion
# fundamental zone in Rodrigues space is point symmetric around origin
R = abs(R)
if self.lattice == 'cubic':
return math.sqrt(2.0)-1.0 >= R[0] \
and math.sqrt(2.0)-1.0 >= R[1] \
and math.sqrt(2.0)-1.0 >= R[2] \
and 1.0 >= R[0] + R[1] + R[2]
elif self.lattice == 'hexagonal':
return 1.0 >= R[0] and 1.0 >= R[1] and 1.0 >= R[2] \
and 2.0 >= math.sqrt(3)*R[0] + R[1] \
and 2.0 >= math.sqrt(3)*R[1] + R[0] \
and 2.0 >= math.sqrt(3) + R[2]
elif self.lattice == 'tetragonal':
return 1.0 >= R[0] and 1.0 >= R[1] \
and math.sqrt(2.0) >= R[0] + R[1] \
and math.sqrt(2.0) >= R[2] + 1.0
elif self.lattice == 'orthorhombic':
return 1.0 >= R[0] and 1.0 >= R[1] and 1.0 >= R[2]
else:
return True
def inDisorientationSST(self,R):
"""
Check whether given Rodrigues vector (of misorientation) falls into standard stereographic triangle of own symmetry.
Determination of disorientations follow the work of A. Heinz and P. Neumann:
Representation of Orientation and Disorientation Data for Cubic, Hexagonal, Tetragonal and Orthorhombic Crystals
Acta Cryst. (1991). A47, 780-789
"""
if isinstance(R, Quaternion): R = R.asRodrigues() # translate accidentially passed quaternion
epsilon = 0.0
if self.lattice == 'cubic':
return R[0] >= R[1]+epsilon and R[1] >= R[2]+epsilon and R[2] >= epsilon
elif self.lattice == 'hexagonal':
return R[0] >= math.sqrt(3)*(R[1]-epsilon) and R[1] >= epsilon and R[2] >= epsilon
elif self.lattice == 'tetragonal':
return R[0] >= R[1]-epsilon and R[1] >= epsilon and R[2] >= epsilon
elif self.lattice == 'orthorhombic':
return R[0] >= epsilon and R[1] >= epsilon and R[2] >= epsilon
else:
return True
def inSST(self,
vector,
proper = False,
color = False):
"""
Check whether given vector falls into standard stereographic triangle of own symmetry.
proper considers only vectors with z >= 0, hence uses two neighboring SSTs.
Return inverse pole figure color if requested.
"""
# basis = {'cubic' : np.linalg.inv(np.array([[0.,0.,1.], # direction of red
# [1.,0.,1.]/np.sqrt(2.), # direction of green
# [1.,1.,1.]/np.sqrt(3.)]).transpose()), # direction of blue
# 'hexagonal' : np.linalg.inv(np.array([[0.,0.,1.], # direction of red
# [1.,0.,0.], # direction of green
# [np.sqrt(3.),1.,0.]/np.sqrt(4.)]).transpose()), # direction of blue
# 'tetragonal' : np.linalg.inv(np.array([[0.,0.,1.], # direction of red
# [1.,0.,0.], # direction of green
# [1.,1.,0.]/np.sqrt(2.)]).transpose()), # direction of blue
# 'orthorhombic' : np.linalg.inv(np.array([[0.,0.,1.], # direction of red
# [1.,0.,0.], # direction of green
# [0.,1.,0.]]).transpose()), # direction of blue
# }
if self.lattice == 'cubic':
basis = {'improper':np.array([ [-1. , 0. , 1. ],
[ np.sqrt(2.) , -np.sqrt(2.) , 0. ],
[ 0. , np.sqrt(3.) , 0. ] ]),
'proper':np.array([ [ 0. , -1. , 1. ],
[-np.sqrt(2.) , np.sqrt(2.) , 0. ],
[ np.sqrt(3.) , 0. , 0. ] ]),
}
elif self.lattice == 'hexagonal':
basis = {'improper':np.array([ [ 0. , 0. , 1. ],
[ 1. , -np.sqrt(3.), 0. ],
[ 0. , 2. , 0. ] ]),
'proper':np.array([ [ 0. , 0. , 1. ],
[-1. , np.sqrt(3.) , 0. ],
[ np.sqrt(3) , -1. , 0. ] ]),
}
elif self.lattice == 'tetragonal':
basis = {'improper':np.array([ [ 0. , 0. , 1. ],
[ 1. , -1. , 0. ],
[ 0. , np.sqrt(2.), 0. ] ]),
'proper':np.array([ [ 0. , 0. , 1. ],
[-1. , 1. , 0. ],
[ np.sqrt(2.) , 0. , 0. ] ]),
}
elif self.lattice == 'orthorhombic':
basis = {'improper':np.array([ [ 0., 0., 1.],
[ 1., 0., 0.],
[ 0., 1., 0.] ]),
'proper':np.array([ [ 0., 0., 1.],
[-1., 0., 0.],
[ 0., 1., 0.] ]),
}
else:
basis = {'improper':np.zeros((3,3),dtype=float),
'proper':np.zeros((3,3),dtype=float),
}
if np.all(basis == 0.0):
theComponents = -np.ones(3,'d')
inSST = np.all(theComponents >= 0.0)
else:
v = np.array(vector,dtype = float)
if proper: # check both improper ...
theComponents = np.dot(basis['improper'],v)
inSST = np.all(theComponents >= 0.0)
if not inSST: # ... and proper SST
theComponents = np.dot(basis['proper'],v)
inSST = np.all(theComponents >= 0.0)
else:
v[2] = abs(v[2]) # z component projects identical
theComponents = np.dot(basis['improper'],v) # for positive and negative values
inSST = np.all(theComponents >= 0.0)
if color: # have to return color array
if inSST:
rgb = np.power(theComponents/np.linalg.norm(theComponents),0.5) # smoothen color ramps
rgb = np.minimum(np.ones(3,'d'),rgb) # limit to maximum intensity
rgb /= max(rgb) # normalize to (HS)V = 1
else:
rgb = np.zeros(3,'d')
return (inSST,rgb)
else:
return inSST
# code derived from http://pyeuclid.googlecode.com/svn/trunk/euclid.py
# suggested reading: http://web.mit.edu/2.998/www/QuaternionReport1.pdf
# ******************************************************************************************
class Orientation:
__slots__ = ['quaternion','symmetry']
def __init__(self,
quaternion = Quaternion.fromIdentity(),
Rodrigues = None,
angleAxis = None,
matrix = None,
Eulers = None,
random = False, # integer to have a fixed seed or True for real random
symmetry = None,
degrees = False,
):
if random: # produce random orientation
if isinstance(random, bool ):
self.quaternion = Quaternion.fromRandom()
else:
self.quaternion = Quaternion.fromRandom(randomSeed=random)
elif isinstance(Eulers, np.ndarray) and Eulers.shape == (3,): # based on given Euler angles
self.quaternion = Quaternion.fromEulers(Eulers,type='bunge',degrees=degrees)
elif isinstance(matrix, np.ndarray) : # based on given rotation matrix
self.quaternion = Quaternion.fromMatrix(matrix)
elif isinstance(angleAxis, np.ndarray) and angleAxis.shape == (4,): # based on given angle and rotation axis
self.quaternion = Quaternion.fromAngleAxis(angleAxis[0],angleAxis[1:4],degrees=degrees)
elif isinstance(Rodrigues, np.ndarray) and Rodrigues.shape == (3,): # based on given Rodrigues vector
self.quaternion = Quaternion.fromRodrigues(Rodrigues)
elif isinstance(quaternion, Quaternion): # based on given quaternion
self.quaternion = quaternion.homomorphed()
elif isinstance(quaternion, np.ndarray) and quaternion.shape == (4,): # based on given quaternion-like array
self.quaternion = Quaternion(quaternion).homomorphed()
self.symmetry = Symmetry(symmetry)
def __copy__(self):
"""copy"""
return self.__class__(quaternion=self.quaternion,symmetry=self.symmetry.lattice)
copy = __copy__
def __repr__(self):
"""value as all implemented representations"""
return 'Symmetry: %s\n' % (self.symmetry) + \
'Quaternion: %s\n' % (self.quaternion) + \
'Matrix:\n%s\n' % ( '\n'.join(['\t'.join(map(str,self.asMatrix()[i,:])) for i in range(3)]) ) + \
'Bunge Eulers / deg: %s' % ('\t'.join(map(str,self.asEulers('bunge',degrees=True))) )
def asQuaternion(self):
return self.quaternion.asList()
def asEulers(self,
type = 'bunge',
degrees = False,
standardRange = False):
return self.quaternion.asEulers(type, degrees, standardRange)
eulers = property(asEulers)
def asRodrigues(self):
return self.quaternion.asRodrigues()
rodrigues = property(asRodrigues)
def asAngleAxis(self,
degrees = False):
return self.quaternion.asAngleAxis(degrees)
angleAxis = property(asAngleAxis)
def asMatrix(self):
return self.quaternion.asMatrix()
matrix = property(asMatrix)
def inFZ(self):
return self.symmetry.inFZ(self.quaternion.asRodrigues())
infz = property(inFZ)
def equivalentQuaternions(self,
who = []):
return self.symmetry.equivalentQuaternions(self.quaternion,who)
def equivalentOrientations(self,
who = []):
return [Orientation(quaternion = q, symmetry = self.symmetry.lattice) for q in self.equivalentQuaternions(who)]
def reduced(self):
"""Transform orientation to fall into fundamental zone according to symmetry"""
for me in self.symmetry.equivalentQuaternions(self.quaternion):
if self.symmetry.inFZ(me.asRodrigues()): break
return Orientation(quaternion=me,symmetry=self.symmetry.lattice)
def disorientation(self,
other,
SST = True):
"""
Disorientation between myself and given other orientation.
Rotation axis falls into SST if SST == True.
(Currently requires same symmetry for both orientations.
Look into A. Heinz and P. Neumann 1991 for cases with differing sym.)
"""
if self.symmetry != other.symmetry: raise TypeError('disorientation between different symmetry classes not supported yet.')
misQ = self.quaternion.conjugated()*other.quaternion
mySymQs = self.symmetry.symmetryQuats() if SST else self.symmetry.symmetryQuats()[:1] # take all or only first sym operation
otherSymQs = other.symmetry.symmetryQuats()
for i,sA in enumerate(mySymQs):
for j,sB in enumerate(otherSymQs):
theQ = sA.conjugated()*misQ*sB
for k in range(2):
theQ.conjugate()
breaker = self.symmetry.inFZ(theQ) \
and (not SST or other.symmetry.inDisorientationSST(theQ))
if breaker: break
if breaker: break
if breaker: break
# disorientation, own sym, other sym, self-->other: True, self<--other: False
return (Orientation(quaternion = theQ,symmetry = self.symmetry.lattice),
i,j,k == 1)
def inversePole(self,
axis,
proper = False,
SST = True):
"""axis rotated according to orientation (using crystal symmetry to ensure location falls into SST)"""
if SST: # pole requested to be within SST
for i,q in enumerate(self.symmetry.equivalentQuaternions(self.quaternion)): # test all symmetric equivalent quaternions
pole = q.conjugated()*axis # align crystal direction to axis
if self.symmetry.inSST(pole,proper): break # found SST version
else:
pole = self.quaternion.conjugated()*axis # align crystal direction to axis
return (pole,i if SST else 0)
def IPFcolor(self,axis):
"""TSL color of inverse pole figure for given axis"""
color = np.zeros(3,'d')
for q in self.symmetry.equivalentQuaternions(self.quaternion):
pole = q.conjugated()*axis # align crystal direction to axis
inSST,color = self.symmetry.inSST(pole,color=True)
if inSST: break
return color
@classmethod
def average(cls,
orientations,
multiplicity = []):
"""
average orientation
ref: F. Landis Markley, Yang Cheng, John Lucas Crassidis, and Yaakov Oshman.
Averaging Quaternions,
Journal of Guidance, Control, and Dynamics, Vol. 30, No. 4 (2007), pp. 1193-1197.
doi: 10.2514/1.28949
usage:
a = Orientation(Eulers=np.radians([10, 10, 0]), symmetry='hexagonal')
b = Orientation(Eulers=np.radians([20, 0, 0]), symmetry='hexagonal')
avg = Orientation.average([a,b])
"""
if not all(isinstance(item, Orientation) for item in orientations):
raise TypeError("Only instances of Orientation can be averaged.")
N = len(orientations)
if multiplicity == [] or not multiplicity:
multiplicity = np.ones(N,dtype='i')
reference = orientations[0] # take first as reference
for i,(o,n) in enumerate(zip(orientations,multiplicity)):
closest = o.equivalentOrientations(reference.disorientation(o,SST = False)[2])[0] # select sym orientation with lowest misorientation
M = closest.quaternion.asM() * n if i == 0 else M + closest.quaternion.asM() * n # noqa add (multiples) of this orientation to average noqa
eig, vec = np.linalg.eig(M/N)
return Orientation(quaternion = Quaternion(quatArray = np.real(vec.T[eig.argmax()])),
symmetry = reference.symmetry.lattice)
def related(self,
relationModel,
direction,
targetSymmetry = None):
"""
orientation relationship
positive number: fcc --> bcc
negative number: bcc --> fcc
"""
if relationModel not in ['KS','GT','GTdash','NW','Pitsch','Bain']: return None
if int(direction) == 0: return None
# KS from S. Morito et al./Journal of Alloys and Compounds 5775 (2013) S587-S592
# for KS rotation matrices also check K. Kitahara et al./Acta Materialia 54 (2006) 1279-1288
# GT from Y. He et al./Journal of Applied Crystallography (2006). 39, 72-81
# GT' from Y. He et al./Journal of Applied Crystallography (2006). 39, 72-81
# NW from H. Kitahara et al./Materials Characterization 54 (2005) 378-386
# Pitsch from Y. He et al./Acta Materialia 53 (2005) 1179-1190
# Bain from Y. He et al./Journal of Applied Crystallography (2006). 39, 72-81
variant = int(abs(direction))-1
(me,other) = (0,1) if direction > 0 else (1,0)
planes = {'KS': \
np.array([[[ 1, 1, 1],[ 0, 1, 1]],
[[ 1, 1, 1],[ 0, 1, 1]],
[[ 1, 1, 1],[ 0, 1, 1]],
[[ 1, 1, 1],[ 0, 1, 1]],
[[ 1, 1, 1],[ 0, 1, 1]],
[[ 1, 1, 1],[ 0, 1, 1]],
[[ 1, -1, 1],[ 0, 1, 1]],
[[ 1, -1, 1],[ 0, 1, 1]],
[[ 1, -1, 1],[ 0, 1, 1]],
[[ 1, -1, 1],[ 0, 1, 1]],
[[ 1, -1, 1],[ 0, 1, 1]],
[[ 1, -1, 1],[ 0, 1, 1]],
[[ -1, 1, 1],[ 0, 1, 1]],
[[ -1, 1, 1],[ 0, 1, 1]],
[[ -1, 1, 1],[ 0, 1, 1]],
[[ -1, 1, 1],[ 0, 1, 1]],
[[ -1, 1, 1],[ 0, 1, 1]],
[[ -1, 1, 1],[ 0, 1, 1]],
[[ 1, 1, -1],[ 0, 1, 1]],
[[ 1, 1, -1],[ 0, 1, 1]],
[[ 1, 1, -1],[ 0, 1, 1]],
[[ 1, 1, -1],[ 0, 1, 1]],
[[ 1, 1, -1],[ 0, 1, 1]],
[[ 1, 1, -1],[ 0, 1, 1]]]),
'GT': \
np.array([[[ 1, 1, 1],[ 1, 0, 1]],
[[ 1, 1, 1],[ 1, 1, 0]],
[[ 1, 1, 1],[ 0, 1, 1]],
[[ -1, -1, 1],[ -1, 0, 1]],
[[ -1, -1, 1],[ -1, -1, 0]],
[[ -1, -1, 1],[ 0, -1, 1]],
[[ -1, 1, 1],[ -1, 0, 1]],
[[ -1, 1, 1],[ -1, 1, 0]],
[[ -1, 1, 1],[ 0, 1, 1]],
[[ 1, -1, 1],[ 1, 0, 1]],
[[ 1, -1, 1],[ 1, -1, 0]],
[[ 1, -1, 1],[ 0, -1, 1]],
[[ 1, 1, 1],[ 1, 1, 0]],
[[ 1, 1, 1],[ 0, 1, 1]],
[[ 1, 1, 1],[ 1, 0, 1]],
[[ -1, -1, 1],[ -1, -1, 0]],
[[ -1, -1, 1],[ 0, -1, 1]],
[[ -1, -1, 1],[ -1, 0, 1]],
[[ -1, 1, 1],[ -1, 1, 0]],
[[ -1, 1, 1],[ 0, 1, 1]],
[[ -1, 1, 1],[ -1, 0, 1]],
[[ 1, -1, 1],[ 1, -1, 0]],
[[ 1, -1, 1],[ 0, -1, 1]],
[[ 1, -1, 1],[ 1, 0, 1]]]),
'GTdash': \
np.array([[[ 7, 17, 17],[ 12, 5, 17]],
[[ 17, 7, 17],[ 17, 12, 5]],
[[ 17, 17, 7],[ 5, 17, 12]],
[[ -7,-17, 17],[-12, -5, 17]],
[[-17, -7, 17],[-17,-12, 5]],
[[-17,-17, 7],[ -5,-17, 12]],
[[ 7,-17,-17],[ 12, -5,-17]],
[[ 17, -7,-17],[ 17,-12, -5]],
[[ 17,-17, -7],[ 5,-17,-12]],
[[ -7, 17,-17],[-12, 5,-17]],
[[-17, 7,-17],[-17, 12, -5]],
[[-17, 17, -7],[ -5, 17,-12]],
[[ 7, 17, 17],[ 12, 17, 5]],
[[ 17, 7, 17],[ 5, 12, 17]],
[[ 17, 17, 7],[ 17, 5, 12]],
[[ -7,-17, 17],[-12,-17, 5]],
[[-17, -7, 17],[ -5,-12, 17]],
[[-17,-17, 7],[-17, -5, 12]],
[[ 7,-17,-17],[ 12,-17, -5]],
[[ 17, -7,-17],[ 5, -12,-17]],
[[ 17,-17, 7],[ 17, -5,-12]],
[[ -7, 17,-17],[-12, 17, -5]],
[[-17, 7,-17],[ -5, 12,-17]],
[[-17, 17, -7],[-17, 5,-12]]]),
'NW': \
np.array([[[ 1, 1, 1],[ 0, 1, 1]],
[[ 1, 1, 1],[ 0, 1, 1]],
[[ 1, 1, 1],[ 0, 1, 1]],
[[ -1, 1, 1],[ 0, 1, 1]],
[[ -1, 1, 1],[ 0, 1, 1]],
[[ -1, 1, 1],[ 0, 1, 1]],
[[ 1, -1, 1],[ 0, 1, 1]],
[[ 1, -1, 1],[ 0, 1, 1]],
[[ 1, -1, 1],[ 0, 1, 1]],
[[ -1, -1, 1],[ 0, 1, 1]],
[[ -1, -1, 1],[ 0, 1, 1]],
[[ -1, -1, 1],[ 0, 1, 1]]]),
'Pitsch': \
np.array([[[ 0, 1, 0],[ -1, 0, 1]],
[[ 0, 0, 1],[ 1, -1, 0]],
[[ 1, 0, 0],[ 0, 1, -1]],
[[ 1, 0, 0],[ 0, -1, -1]],
[[ 0, 1, 0],[ -1, 0, -1]],
[[ 0, 0, 1],[ -1, -1, 0]],
[[ 0, 1, 0],[ -1, 0, -1]],
[[ 0, 0, 1],[ -1, -1, 0]],
[[ 1, 0, 0],[ 0, -1, -1]],
[[ 1, 0, 0],[ 0, -1, 1]],
[[ 0, 1, 0],[ 1, 0, -1]],
[[ 0, 0, 1],[ -1, 1, 0]]]),
'Bain': \
np.array([[[ 1, 0, 0],[ 1, 0, 0]],
[[ 0, 1, 0],[ 0, 1, 0]],
[[ 0, 0, 1],[ 0, 0, 1]]]),
}
normals = {'KS': \
np.array([[[ -1, 0, 1],[ -1, -1, 1]],
[[ -1, 0, 1],[ -1, 1, -1]],
[[ 0, 1, -1],[ -1, -1, 1]],
[[ 0, 1, -1],[ -1, 1, -1]],
[[ 1, -1, 0],[ -1, -1, 1]],
[[ 1, -1, 0],[ -1, 1, -1]],
[[ 1, 0, -1],[ -1, -1, 1]],
[[ 1, 0, -1],[ -1, 1, -1]],
[[ -1, -1, 0],[ -1, -1, 1]],
[[ -1, -1, 0],[ -1, 1, -1]],
[[ 0, 1, 1],[ -1, -1, 1]],
[[ 0, 1, 1],[ -1, 1, -1]],
[[ 0, -1, 1],[ -1, -1, 1]],
[[ 0, -1, 1],[ -1, 1, -1]],
[[ -1, 0, -1],[ -1, -1, 1]],
[[ -1, 0, -1],[ -1, 1, -1]],
[[ 1, 1, 0],[ -1, -1, 1]],
[[ 1, 1, 0],[ -1, 1, -1]],
[[ -1, 1, 0],[ -1, -1, 1]],
[[ -1, 1, 0],[ -1, 1, -1]],
[[ 0, -1, -1],[ -1, -1, 1]],
[[ 0, -1, -1],[ -1, 1, -1]],
[[ 1, 0, 1],[ -1, -1, 1]],
[[ 1, 0, 1],[ -1, 1, -1]]]),
'GT': \
np.array([[[ -5,-12, 17],[-17, -7, 17]],
[[ 17, -5,-12],[ 17,-17, -7]],
[[-12, 17, -5],[ -7, 17,-17]],
[[ 5, 12, 17],[ 17, 7, 17]],
[[-17, 5,-12],[-17, 17, -7]],
[[ 12,-17, -5],[ 7,-17,-17]],
[[ -5, 12,-17],[-17, 7,-17]],
[[ 17, 5, 12],[ 17, 17, 7]],
[[-12,-17, 5],[ -7,-17, 17]],
[[ 5,-12,-17],[ 17, -7,-17]],
[[-17, -5, 12],[-17,-17, 7]],
[[ 12, 17, 5],[ 7, 17, 17]],
[[ -5, 17,-12],[-17, 17, -7]],
[[-12, -5, 17],[ -7,-17, 17]],
[[ 17,-12, -5],[ 17, -7,-17]],
[[ 5,-17,-12],[ 17,-17, -7]],
[[ 12, 5, 17],[ 7, 17, 17]],
[[-17, 12, -5],[-17, 7,-17]],
[[ -5,-17, 12],[-17,-17, 7]],
[[-12, 5,-17],[ -7, 17,-17]],
[[ 17, 12, 5],[ 17, 7, 17]],
[[ 5, 17, 12],[ 17, 17, 7]],
[[ 12, -5,-17],[ 7,-17,-17]],
[[-17,-12, 5],[-17, 7, 17]]]),
'GTdash': \
np.array([[[ 0, 1, -1],[ 1, 1, -1]],
[[ -1, 0, 1],[ -1, 1, 1]],
[[ 1, -1, 0],[ 1, -1, 1]],
[[ 0, -1, -1],[ -1, -1, -1]],
[[ 1, 0, 1],[ 1, -1, 1]],
[[ 1, -1, 0],[ 1, -1, -1]],
[[ 0, 1, -1],[ -1, 1, -1]],
[[ 1, 0, 1],[ 1, 1, 1]],
[[ -1, -1, 0],[ -1, -1, 1]],
[[ 0, -1, -1],[ 1, -1, -1]],
[[ -1, 0, 1],[ -1, -1, 1]],
[[ -1, -1, 0],[ -1, -1, -1]],
[[ 0, -1, 1],[ 1, -1, 1]],
[[ 1, 0, -1],[ 1, 1, -1]],
[[ -1, 1, 0],[ -1, 1, 1]],
[[ 0, 1, 1],[ -1, 1, 1]],
[[ -1, 0, -1],[ -1, -1, -1]],
[[ -1, 1, 0],[ -1, 1, -1]],
[[ 0, -1, 1],[ -1, -1, 1]],
[[ -1, 0, -1],[ -1, 1, -1]],
[[ 1, 1, 0],[ 1, 1, 1]],
[[ 0, 1, 1],[ 1, 1, 1]],
[[ 1, 0, -1],[ 1, -1, -1]],
[[ 1, 1, 0],[ 1, 1, -1]]]),
'NW': \
np.array([[[ 2, -1, -1],[ 0, -1, 1]],
[[ -1, 2, -1],[ 0, -1, 1]],
[[ -1, -1, 2],[ 0, -1, 1]],
[[ -2, -1, -1],[ 0, -1, 1]],
[[ 1, 2, -1],[ 0, -1, 1]],
[[ 1, -1, 2],[ 0, -1, 1]],
[[ 2, 1, -1],[ 0, -1, 1]],
[[ -1, -2, -1],[ 0, -1, 1]],
[[ -1, 1, 2],[ 0, -1, 1]],
[[ -1, 2, 1],[ 0, -1, 1]],
[[ -1, 2, 1],[ 0, -1, 1]],
[[ -1, -1, -2],[ 0, -1, 1]]]),
'Pitsch': \
np.array([[[ 1, 0, 1],[ 1, -1, 1]],
[[ 1, 1, 0],[ 1, 1, -1]],
[[ 0, 1, 1],[ -1, 1, 1]],
[[ 0, 1, -1],[ -1, 1, -1]],
[[ -1, 0, 1],[ -1, -1, 1]],
[[ 1, -1, 0],[ 1, -1, -1]],
[[ 1, 0, -1],[ 1, -1, -1]],
[[ -1, 1, 0],[ -1, 1, -1]],
[[ 0, -1, 1],[ -1, -1, 1]],
[[ 0, 1, 1],[ -1, 1, 1]],
[[ 1, 0, 1],[ 1, -1, 1]],
[[ 1, 1, 0],[ 1, 1, -1]]]),
'Bain': \
np.array([[[ 0, 1, 0],[ 0, 1, 1]],
[[ 0, 0, 1],[ 1, 0, 1]],
[[ 1, 0, 0],[ 1, 1, 0]]]),
}
myPlane = [float(i) for i in planes[relationModel][variant,me]] # map(float, planes[...]) does not work in python 3
myPlane /= np.linalg.norm(myPlane)
myNormal = [float(i) for i in normals[relationModel][variant,me]] # map(float, planes[...]) does not work in python 3
myNormal /= np.linalg.norm(myNormal)
myMatrix = np.array([myNormal,np.cross(myPlane,myNormal),myPlane]).T
otherPlane = [float(i) for i in planes[relationModel][variant,other]] # map(float, planes[...]) does not work in python 3
otherPlane /= np.linalg.norm(otherPlane)
otherNormal = [float(i) for i in normals[relationModel][variant,other]] # map(float, planes[...]) does not work in python 3
otherNormal /= np.linalg.norm(otherNormal)
otherMatrix = np.array([otherNormal,np.cross(otherPlane,otherNormal),otherPlane]).T
rot=np.dot(otherMatrix,myMatrix.T)
return Orientation(matrix=np.dot(rot,self.asMatrix())) # no symmetry information ??
|
{"/Code/Spherical/__init__.py": ["/Code/Spherical/asciitable.py", "/Code/Spherical/orientation.py", "/Code/Spherical/util.py"]}
|
14,417
|
chakra34/SphericalOrientations
|
refs/heads/master
|
/Code/equidistant_SphericalTriangle.py
|
#!/usr/bin/env python
###########################################################################
# Authors #
# Aritra Chakraborty #
# Philip Eisenlohr #
###########################################################################
import os,sys,Spherical
import string
from optparse import OptionParser
import numpy as np
from subprocess import call
import math
global listAngles
listAngles = []
global listCoords
listCoords = []
scriptID = string.replace('$Id: equidistant_SphericalTriangle.py 476 2017-06-15 15:22:25Z chakra34 $','\n','\\n')
scriptName = os.path.splitext(scriptID.split()[1])[0]
parser = OptionParser(option_class=Spherical.extendableOption, usage='%prog options [file[s]]', description = """
Discretizes a spherical triangle equally based on degrees of runs.
""", version = scriptID)
parser.add_option('--degrees',
dest = 'degrees',
type = 'int',
help = 'number of times discretizations to be done [3]')
parser.add_option('--symm',
dest = 'symmetry',
type = 'string',
help = 'symmetry [cubic]')
parser.add_option("--unitcell", action="store_true",
dest="unitcell",
help="unitcell or not [False]")
parser.add_option("--eulers", action="store_true",
dest="eulers",
help="prints out the discretized Euler angles in Bunge convention [False]")
parser.add_option('--p1',
dest = 'point1',
type = 'float', nargs = 3, metavar = 'float float float',
help = 'first point in the spherical triangle to be discretized [%default]')
parser.add_option('--p2',
dest = 'point2',
type = 'float', nargs = 3, metavar = 'float float float',
help = 'second point in the spherical triangle to be discretized [%default]')
parser.add_option('--p3',
dest = 'point3',
type = 'float', nargs = 3, metavar = 'float float float',
help = 'third point in the spherical triangle to be discretized [%default]')
parser.add_option( '--root',
dest = 'root',
type = 'string', metavar = 'string',
help = ' desired root of this process ')
parser.set_defaults(degrees = 3,
symmetry = 'cubic',
unitcell = False,
eulers = False,
point1 = [0., 0., 1.],
point2 = [1., 0., 1.],
point3 = [1., 1., 1.],
)
(options,filenames) = parser.parse_args()
options.root = os.path.dirname(os.path.realpath(__file__)) if options.root == None else options.root
options.point1 = np.array(options.point1)/np.linalg.norm(options.point1)
options.point2 = np.array(options.point2)/np.linalg.norm(options.point2)
options.point3 = np.array(options.point3)/np.linalg.norm(options.point3)
#----------------------------------------------#
def generate_tex_cubic(section):
if section == 'header' :
return """
\\documentclass{article}
\\usepackage{tikz}
\\graphicspath{{../}{./}}
\\usetikzlibrary{shapes,arrows}
\\usepackage{miller}
\\usepackage[graphics, active, tightpage]{preview}
\\PreviewEnvironment{tikzpicture}
\\begin{document}
\\thispagestyle{empty}
\\begin{tikzpicture}
\\begin{scope}[x=19.313708cm,y=19.313708cm]
\\draw[line width=1.0pt] (0,0) -- (0.414,0);
% \\draw[line width=1.0pt] (0,0) -- (0.0,0.414);
\\draw[line width=1.0pt, domain=0:15] plot ({-1 + sqrt(2)*cos(\\x)}, {sqrt(2)*sin(\\x)});
% \\draw[line width=1.0pt, domain=75:90] plot ({ sqrt(2)*cos(\\x)}, {-1 + sqrt(2)*sin(\\x)});
\\draw[line width=1.0pt] (0,0) -- (0.366,0.366);
\\begin{scope}[inner sep=0pt]
\\node[fill,rectangle,minimum height=6pt,minimum width=6pt,label={below left:\\small\\hkl<001>}] at (0.000000,0.000000) {};
\\node[fill,diamond,minimum height=12pt,minimum width=6pt,label={below right:\\small\\hkl<101>}] at (0.414,0.000000) {};
% \\node[fill,diamond,minimum height=12pt,minimum width=6pt,label={below right:\\small\\hkl<011>}] at (0.0,0.414) {};
\\node[fill,ellipse,minimum height=6pt,minimum width=6pt,label={above right:\\small\\hkl<111>}] at (0.366,0.366) {};
\\end{scope}
\\begin{scope}[inner sep=1.0pt]
"""
elif section == 'footer' :
return """
\\end{scope}
\\end{scope}
\\end{tikzpicture}
\\end{document}
"""
def generate_tex_tetragonal(section):
if section == 'header' :
return """
\\documentclass{article}
\\usepackage{tikz}
\\graphicspath{{../}{./}}
\\usetikzlibrary{shapes,arrows}
\\usepackage{miller}
\\usepackage[graphics, active, tightpage]{preview}
\\PreviewEnvironment{tikzpicture}
\\begin{document}
\\thispagestyle{empty}
\\begin{tikzpicture}
\\begin{scope}[x=19.313708cm,y=19.313708cm]
\\draw[line width=1.0pt] (0,0) -- (1,0);
\\draw[line width=1.0pt] (1,0) arc(0:45:1);
%\\draw[line width=1.0pt] (0,0) -- (0,1);
\\draw[line width=1.0pt] (0,0) -- (0.707,0.707);
\\begin{scope}[inner sep=0pt]
\\node[fill,rectangle,minimum height=6pt,minimum width=6pt,label={below left:\\small\\hkl<001>}] at (0.000000,0.000000) {};
\\node[fill,diamond,minimum height=12pt,minimum width=6pt,label={below right:\\small\\hkl<100>}] at (1.000000,0.000000) {};
\\node[fill,ellipse,minimum height=6pt,minimum width=6pt,label={above right:\\small\\hkl<110>}] at (0.707107,0.707107) {};
%\\node[fill,diamond,minimum height=6pt,minimum width=6pt,label={above right:\\small\\hkl<010>}] at (0.0000,1.0000) {};
\\end{scope}
\\begin{scope}[inner sep=1.0pt]
"""
elif section == 'footer' :
return """
\\end{scope}
\\end{scope}
\\end{tikzpicture}
\\end{document}
"""
def generate_tex_hexagonal(section):
if section == 'header' :
return """
\\documentclass{article}
\\usepackage{tikz}
\\graphicspath{{../}{./}}
\\usetikzlibrary{shapes,arrows}
\\usepackage{miller}
\\usepackage[graphics, active, tightpage]{preview}
\\PreviewEnvironment{tikzpicture}
\\begin{document}
\\thispagestyle{empty}
\\begin{tikzpicture}
\\begin{scope}[x=19.313708cm,y=19.313708cm]
\\draw[line width=1.0pt] (0,0) -- (1,0);
\\draw[line width=1.0pt] (1,0) arc(0:30:1);
%\\draw[line width=1.0pt] (0,0) -- (0,1);
\\draw[line width=1.0pt] (0,0) -- (0.866,0.50);
%\\draw[line width=1.0pt] (0,0) -- (0.5,0.8660);
\\begin{scope}[inner sep=0pt]
\\node[fill,rectangle,minimum height=6pt,minimum width=6pt,label={below left:\\small\\hkl<0001>}] at (0.000000,0.000000) {};
\\node[fill,diamond,minimum height=12pt,minimum width=6pt,label={below right:\\small\\hkl<2-1-10>}] at (1.000000,0.000000) {};
\\node[fill,ellipse,minimum height=6pt,minimum width=6pt,label={above right:\\small\\hkl<10-10>}] at (0.866,0.5) {};
%\\node[fill,diamond,minimum height=6pt,minimum width=6pt,label={above right:\\small\\hkl<11-20>}] at (0.5,0.866) {};
\\end{scope}
\\begin{scope}[inner sep=1.0pt]
"""
elif section == 'footer' :
return """
\\end{scope}
\\end{scope}
\\end{tikzpicture}
\\end{document}
"""
#------------------------------------------------------#
def append(vector):
color = np.array(([255,0,0]))
if np.linalg.norm(vector) != 0.0:
vector = vector/np.linalg.norm(vector)
zeta = math.degrees(math.atan2(vector[1],vector[0]))
eta = math.degrees(math.acos(vector[2]))
phi1 = 270 + zeta
PHI = eta
phi2 = 90 - zeta
if options.eulers == True:
listAngles.append(phi1)
listAngles.append(PHI)
listAngles.append(phi2)
# X = vector[0] * math.sqrt(1. /(1 + abs(vector[2]))) # homochoric projection
# Y = vector[1] * math.sqrt(1. /(1 + abs(vector[2])))
X = vector[0] /((1 + abs(vector[2]))) # stereographic projection
Y = vector[1] /((1 + abs(vector[2])))
if [X,Y] not in listCoords:
listCoords.append([X,Y])
if options.unitcell == True :
if options.symmetry == 'tetragonal' :
cmd = '%s/unitcell.py -n "%s-%s-%s" -c 0.5456 --up 0 1 0 -e %.02f %.02f %.02f '%(options.root,str(int(phi1)),str(int(PHI)),str(int(phi2)),phi1,PHI,phi2)
elif options.symmetry == 'cubic' :
cmd = '%s/unitcell.py -n "%s-%s-%s" -c 1.0 --up 0 1 0 -e %.02f %.02f %.02f '%(options.root,str(int(phi1)),str(int(PHI)),str(int(phi2)),phi1,PHI,phi2)
elif options.symmetry == 'hexagonal' :
cmd = '%s/unitcell.py -u hexagonal -n "%s-%s-%s" --up 0 1 0 -e %.02f %.02f %.02f '%(options.root,str(int(phi1)),str(int(PHI)),str(int(phi2)),phi1,PHI,phi2)
call(cmd,shell=True)
out = '%s-%s-%s.pdf'%(str(int(phi1)),str(int(PHI)),str(int(phi2)))
texfile.write('\\node at (%.03f,%.03f){\includegraphics[scale=0.1]{%s}};\n'%(X,Y,out))
else :
texfile.write('\\node[fill={rgb:red,%.4f;green,%.4f;blue,%.4f}, circle, minimum height=4pt] at (%.4f, %.4f) {};\n'%(color[0]/255.0, color[1]/255.0, color[2]/255.0, X, Y))
return
def mid(vector1,vector2):
mid1 = np.array(([(vector1[0] + vector2[0])/2 ,(vector1[1] + vector2[1])/2 ,(vector1[2] + vector2[2])/2 ]))
append(mid1)
return mid1
# Using Sierpenski triangle algorithm and modifying it #
def sierpenski(vector,degree):
if degree > 0:
sierpenski([vector[0],mid(vector[0],vector[1]),mid(vector[0],vector[2])],degree - 1)
sierpenski([vector[1],mid(vector[0],vector[1]),mid(vector[1],vector[2])],degree - 1)
sierpenski([vector[2],mid(vector[2],vector[1]),mid(vector[0],vector[2])],degree - 1)
sierpenski([mid(vector[0],vector[1]),mid(vector[0],vector[2]),mid(vector[1],vector[2])],degree - 1)
return
if not os.path.exists('equidistant'): os.makedirs('equidistant')
texfile = open("equidistant/equidistant_IPF.tex", 'w')
if options.symmetry == 'tetragonal':
texfile.write(generate_tex_tetragonal('header'))
elif options.symmetry == 'cubic':
texfile.write(generate_tex_cubic('header'))
elif options.symmetry == 'hexagonal':
texfile.write(generate_tex_hexagonal('header'))
vector = np.array((options.point1,options.point2,options.point3))
append(vector[0])
append(vector[1])
append(vector[2])
sierpenski(vector,options.degrees)
texfile.write(generate_tex_tetragonal('footer'))
texfile.close()
if options.eulers:
listAngles = np.array(listAngles).reshape(len(listAngles)/3,3)
sorted_idx = np.lexsort(listAngles.T)
sorted_data = listAngles[sorted_idx,:]
# Get unique row mask
row_mask = np.append([True],np.any(np.diff(sorted_data,axis=0),1))
# Get unique rows
uniqueAngles = sorted_data[row_mask]
for i in xrange(len(uniqueAngles)):
print uniqueAngles[i,0],uniqueAngles[i,1],uniqueAngles[i,2]
|
{"/Code/Spherical/__init__.py": ["/Code/Spherical/asciitable.py", "/Code/Spherical/orientation.py", "/Code/Spherical/util.py"]}
|
14,418
|
chakra34/SphericalOrientations
|
refs/heads/master
|
/Code/Spherical/asciitable.py
|
# -*- coding: UTF-8 no BOM -*-
# obtained from https://damask.mpie.de #
import os,sys
import numpy as np
# ------------------------------------------------------------------
# python 3 has no unicode object, this ensures that the code works on Python 2&3
try:
test=isinstance('test', unicode)
except(NameError):
unicode=str
# ------------------------------------------------------------------
class ASCIItable():
"""Read and write to ASCII tables"""
__slots__ = ['__IO__',
'info',
'labeled',
'data',
]
tmpext = '_tmp' # filename extension for in-place access
# ------------------------------------------------------------------
def __init__(self,
name = None,
outname = None,
buffered = False, # flush writes
labeled = True, # assume table has labels
readonly = False, # no reading from file
):
self.__IO__ = {'output': [],
'buffered': buffered,
'labeled': labeled, # header contains labels
'tags': [], # labels according to file info
'readBuffer': [], # buffer to hold non-advancing reads
'dataStart': 0,
}
self.__IO__['inPlace'] = not outname and name and not readonly
if self.__IO__['inPlace']: outname = name + self.tmpext # transparently create tmp file
try:
self.__IO__['in'] = (open( name,'r') if os.access( name, os.R_OK) else None) if name else sys.stdin
except TypeError:
self.__IO__['in'] = name
try:
self.__IO__['out'] = (open(outname,'w') if (not os.path.isfile(outname) or
os.access( outname, os.W_OK)
) and
(not self.__IO__['inPlace'] or
not os.path.isfile(name) or
os.access( name, os.W_OK)
) else None) if outname else sys.stdout
except TypeError:
self.__IO__['out'] = outname
self.info = []
self.tags = []
self.data = []
self.line = ''
if self.__IO__['in'] is None \
or self.__IO__['out'] is None: raise IOError # complain if any required file access not possible
# ------------------------------------------------------------------
def _transliterateToFloat(self,
x):
try:
return float(x)
except:
return 0.0
# ------------------------------------------------------------------
def _removeCRLF(self,
string):
try:
return string.replace('\n','').replace('\r','')
except:
return string
# ------------------------------------------------------------------
def _quote(self,
what):
"""quote empty or white space-containing output"""
import re
return '{quote}{content}{quote}'.format(
quote = ('"' if str(what)=='' or re.search(r"\s",str(what)) else ''),
content = what)
# ------------------------------------------------------------------
def close(self,
dismiss = False):
self.input_close()
self.output_flush()
self.output_close(dismiss)
# ------------------------------------------------------------------
def input_close(self):
try:
if self.__IO__['in'] != sys.stdin: self.__IO__['in'].close()
except:
pass
# ------------------------------------------------------------------
def output_write(self,
what):
"""aggregate a single row (string) or list of (possibly containing further lists of) rows into output"""
if not isinstance(what, (str, unicode)):
try:
for item in what: self.output_write(item)
except:
self.__IO__['output'] += [str(what)]
else:
self.__IO__['output'] += [what]
return self.__IO__['buffered'] or self.output_flush()
# ------------------------------------------------------------------
def output_flush(self,
clear = True):
try:
self.__IO__['output'] == [] or self.__IO__['out'].write('\n'.join(self.__IO__['output']) + '\n')
except IOError:
return False
if clear: self.output_clear()
return True
# ------------------------------------------------------------------
def output_clear(self):
self.__IO__['output'] = []
# ------------------------------------------------------------------
def output_close(self,
dismiss = False):
try:
if self.__IO__['out'] != sys.stdout: self.__IO__['out'].close()
except:
pass
if dismiss and os.path.isfile(self.__IO__['out'].name):
os.remove(self.__IO__['out'].name)
elif self.__IO__['inPlace']:
os.rename(self.__IO__['out'].name, self.__IO__['out'].name[:-len(self.tmpext)])
# ------------------------------------------------------------------
def head_read(self):
"""
get column labels
by either reading the first row or,
if keyword "head[*]" is present, the last line of the header
"""
import re,shlex
try:
self.__IO__['in'].seek(0)
except:
pass
firstline = self.__IO__['in'].readline().strip()
m = re.search('(\d+)\s+head', firstline.lower()) # search for "head" keyword
if m: # proper ASCIItable format
if self.__IO__['labeled']: # table features labels
self.info = [self.__IO__['in'].readline().strip() for i in range(1,int(m.group(1)))]
self.tags = shlex.split(self.__IO__['in'].readline()) # store tags found in last line
else:
self.info = [self.__IO__['in'].readline().strip() for i in range(0,int(m.group(1)))] # all header is info ...
else: # other table format
try:
self.__IO__['in'].seek(0) # try to rewind
except:
self.__IO__['readBuffer'] = [firstline] # or at least save data in buffer
while self.data_read(advance = False, respectLabels = False):
if self.line[0] in ['#','!','%','/','|','*','$']: # "typical" comment indicators
self.info_append(self.line) # store comment as info
self.data_read() # wind forward one line
else: break # last line of comments
if self.__IO__['labeled']: # table features labels
self.tags = self.data # get tags from last line in "header"...
self.data_read() # ...and remove from buffer
if self.__IO__['labeled']: # table features tags
self.__IO__['tags'] = list(self.tags) # backup tags (make COPY, not link)
try:
self.__IO__['dataStart'] = self.__IO__['in'].tell() # current file position is at start of data
except IOError:
pass
# ------------------------------------------------------------------
def head_write(self,
header = True):
"""write current header information (info + labels)"""
head = ['{}\theader'.format(len(self.info)+self.__IO__['labeled'])] if header else []
head.append(self.info)
if self.__IO__['labeled']: head.append('\t'.join(map(self._quote,self.tags)))
return self.output_write(head)
# ------------------------------------------------------------------
def head_getGeom(self):
"""interpret geom header"""
identifiers = {
'grid': ['a','b','c'],
'size': ['x','y','z'],
'origin': ['x','y','z'],
}
mappings = {
'grid': lambda x: int(x),
'size': lambda x: float(x),
'origin': lambda x: float(x),
'homogenization': lambda x: int(x),
'microstructures': lambda x: int(x),
}
info = {
'grid': np.zeros(3,'i'),
'size': np.zeros(3,'d'),
'origin': np.zeros(3,'d'),
'homogenization': 0,
'microstructures': 0,
}
extra_header = []
for header in self.info:
headitems = list(map(str.lower,header.split()))
if len(headitems) == 0: continue # skip blank lines
if headitems[0] in list(mappings.keys()):
if headitems[0] in list(identifiers.keys()):
for i in range(len(identifiers[headitems[0]])):
info[headitems[0]][i] = \
mappings[headitems[0]](headitems[headitems.index(identifiers[headitems[0]][i])+1])
else:
info[headitems[0]] = mappings[headitems[0]](headitems[1])
else:
extra_header.append(header)
return info,extra_header
# ------------------------------------------------------------------
def head_putGeom(self,info):
"""translate geometry description to header"""
self.info_append([
"grid\ta {}\tb {}\tc {}".format(*info['grid']),
"size\tx {}\ty {}\tz {}".format(*info['size']),
"origin\tx {}\ty {}\tz {}".format(*info['origin']),
"homogenization\t{}".format(info['homogenization']),
"microstructures\t{}".format(info['microstructures']),
])
# ------------------------------------------------------------------
def labels_append(self,
what,
reset = False):
"""add item or list to existing set of labels (and switch on labeling)"""
if not isinstance(what, (str, unicode)):
try:
for item in what: self.labels_append(item)
except:
self.tags += [self._removeCRLF(str(what))]
else:
self.tags += [self._removeCRLF(what)]
self.__IO__['labeled'] = True # switch on processing (in particular writing) of tags
if reset: self.__IO__['tags'] = list(self.tags) # subsequent data_read uses current tags as data size
# ------------------------------------------------------------------
def labels_clear(self):
"""delete existing labels and switch to no labeling"""
self.tags = []
self.__IO__['labeled'] = False
# ------------------------------------------------------------------
def labels(self,
tags = None,
raw = False):
"""
tell abstract labels.
"x" for "1_x","2_x",... unless raw output is requested.
operates on object tags or given list.
"""
from collections import Iterable
if tags is None: tags = self.tags
if isinstance(tags, Iterable) and not raw: # check whether list of tags is requested
id = 0
dim = 1
labelList = []
while id < len(tags):
if not tags[id].startswith('1_'):
labelList.append(tags[id])
else:
label = tags[id][2:] # get label
while id < len(tags) and tags[id] == '{}_{}'.format(dim,label): # check successors
id += 1 # next label...
dim += 1 # ...should be one higher dimension
labelList.append(label) # reached end --> store
id -= 1 # rewind one to consider again
id += 1
dim = 1
else:
labelList = self.tags
return labelList
# ------------------------------------------------------------------
def label_index(self,
labels):
"""
tell index of column label(s).
return numpy array if asked for list of labels.
transparently deals with label positions implicitly given as numbers or their headings given as strings.
"""
from collections import Iterable
if isinstance(labels, Iterable) and not isinstance(labels, str): # check whether list of labels is requested
idx = []
for label in labels:
if label is not None:
try:
idx.append(int(label)-1) # column given as integer number?
except ValueError:
label = label[1:-1] if label[0] == label[-1] and label[0] in ('"',"'") else label # remove outermost quotations
try:
idx.append(self.tags.index(label)) # locate string in label list
except ValueError:
try:
idx.append(self.tags.index('1_'+label)) # locate '1_'+string in label list
except ValueError:
idx.append(-1) # not found...
else:
try:
idx = int(labels)-1 # offset for python array indexing
except ValueError:
try:
labels = labels[1:-1] if labels[0] == labels[-1] and labels[0] in ('"',"'") else labels # remove outermost quotations
idx = self.tags.index(labels)
except ValueError:
try:
idx = self.tags.index('1_'+labels) # locate '1_'+string in label list
except ValueError:
idx = None if labels is None else -1
return np.array(idx) if isinstance(idx,Iterable) else idx
# ------------------------------------------------------------------
def label_dimension(self,
labels):
"""
tell dimension (length) of column label(s).
return numpy array if asked for list of labels.
transparently deals with label positions implicitly given as numbers or their headings given as strings.
"""
from collections import Iterable
if isinstance(labels, Iterable) and not isinstance(labels, str): # check whether list of labels is requested
dim = []
for label in labels:
if label is not None:
myDim = -1
try: # column given as number?
idx = int(label)-1
myDim = 1 # if found has at least dimension 1
if self.tags[idx].startswith('1_'): # column has multidim indicator?
while idx+myDim < len(self.tags) and self.tags[idx+myDim].startswith("%i_"%(myDim+1)):
myDim += 1 # add while found
except ValueError: # column has string label
label = label[1:-1] if label[0] == label[-1] and label[0] in ('"',"'") else label # remove outermost quotations
if label in self.tags: # can be directly found?
myDim = 1 # scalar by definition
elif '1_'+label in self.tags: # look for first entry of possible multidim object
idx = self.tags.index('1_'+label) # get starting column
myDim = 1 # (at least) one-dimensional
while idx+myDim < len(self.tags) and self.tags[idx+myDim].startswith("%i_"%(myDim+1)):
myDim += 1 # keep adding while going through object
dim.append(myDim)
else:
dim = -1 # assume invalid label
idx = -1
try: # column given as number?
idx = int(labels)-1
dim = 1 # if found has at least dimension 1
if self.tags[idx].startswith('1_'): # column has multidim indicator?
while idx+dim < len(self.tags) and self.tags[idx+dim].startswith("%i_"%(dim+1)):
dim += 1 # add as long as found
except ValueError: # column has string label
labels = labels[1:-1] if labels[0] == labels[-1] and labels[0] in ('"',"'") else labels # remove outermost quotations
if labels in self.tags: # can be directly found?
dim = 1 # scalar by definition
elif '1_'+labels in self.tags: # look for first entry of possible multidim object
idx = self.tags.index('1_'+labels) # get starting column
dim = 1 # is (at least) one-dimensional
while idx+dim < len(self.tags) and self.tags[idx+dim].startswith("%i_"%(dim+1)):
dim += 1 # keep adding while going through object
return np.array(dim) if isinstance(dim,Iterable) else dim
# ------------------------------------------------------------------
def label_indexrange(self,
labels):
"""
tell index range for given label(s).
return numpy array if asked for list of labels.
transparently deals with label positions implicitly given as numbers or their headings given as strings.
"""
from collections import Iterable
start = self.label_index(labels)
dim = self.label_dimension(labels)
return np.hstack([range(c[0],c[0]+c[1]) for c in zip(start,dim)]) \
if isinstance(labels, Iterable) and not isinstance(labels, str) \
else range(start,start+dim)
# ------------------------------------------------------------------
def info_append(self,
what):
"""add item or list to existing set of infos"""
if not isinstance(what, (str, unicode)):
try:
for item in what: self.info_append(item)
except:
self.info += [self._removeCRLF(str(what))]
else:
self.info += [self._removeCRLF(what)]
# ------------------------------------------------------------------
def info_clear(self):
"""delete any info block"""
self.info = []
# ------------------------------------------------------------------
def data_rewind(self):
self.__IO__['in'].seek(self.__IO__['dataStart']) # position file to start of data section
self.__IO__['readBuffer'] = [] # delete any non-advancing data reads
self.tags = list(self.__IO__['tags']) # restore label info found in header (as COPY, not link)
self.__IO__['labeled'] = len(self.tags) > 0
# ------------------------------------------------------------------
def data_skipLines(self,
count):
"""wind forward by count number of lines"""
for i in range(count):
alive = self.data_read()
return alive
# ------------------------------------------------------------------
def data_read(self,
advance = True,
respectLabels = True):
"""read next line (possibly buffered) and parse it into data array"""
import shlex
self.line = self.__IO__['readBuffer'].pop(0) if len(self.__IO__['readBuffer']) > 0 \
else self.__IO__['in'].readline().strip() # take buffered content or get next data row from file
if not advance:
self.__IO__['readBuffer'].append(self.line) # keep line just read in buffer
self.line = self.line.rstrip('\n')
if self.__IO__['labeled'] and respectLabels: # if table has labels
items = shlex.split(self.line)[:len(self.__IO__['tags'])] # use up to label count (from original file info)
self.data = items if len(items) == len(self.__IO__['tags']) else [] # take entries if label count matches
else:
self.data = shlex.split(self.line) # otherwise take all
return self.data != []
# ------------------------------------------------------------------
def data_readArray(self,
labels = []):
"""read whole data of all (given) labels as numpy array"""
from collections import Iterable
try:
self.data_rewind() # try to wind back to start of data
except:
pass # assume/hope we are at data start already...
if labels is None or labels == []:
use = None # use all columns (and keep labels intact)
labels_missing = []
else:
if isinstance(labels, str) or not isinstance(labels, Iterable): # check whether labels are a list or single item
labels = [labels]
indices = self.label_index(labels) # check requested labels ...
dimensions = self.label_dimension(labels) # ... and remember their dimension
present = np.where(indices >= 0)[0] # positions in request list of labels that are present ...
missing = np.where(indices < 0)[0] # ... and missing in table
labels_missing = np.array(labels)[missing] # labels of missing data
columns = []
for i,(c,d) in enumerate(zip(indices[present],dimensions[present])): # for all valid labels ...
# ... transparently add all components unless column referenced by number or with explicit dimension
columns += list(range(c,c + \
(d if str(c) != str(labels[present[i]]) else \
1)))
use = np.array(columns) if len(columns) > 0 else None
self.tags = list(np.array(self.tags)[use]) # update labels with valid subset
self.data = np.loadtxt(self.__IO__['in'],usecols=use,ndmin=2)
return labels_missing
# ------------------------------------------------------------------
def data_write(self,
delimiter = '\t'):
"""write current data array and report alive output back"""
if len(self.data) == 0: return True
if isinstance(self.data[0],list):
return self.output_write([delimiter.join(map(self._quote,items)) for items in self.data])
else:
return self.output_write( delimiter.join(map(self._quote,self.data)))
# ------------------------------------------------------------------
def data_writeArray(self,
fmt = None,
delimiter = '\t'):
"""write whole numpy array data"""
for row in self.data:
try:
output = [fmt % value for value in row] if fmt else list(map(repr,row))
except:
output = [fmt % row] if fmt else [repr(row)]
self.__IO__['out'].write(delimiter.join(output) + '\n')
# ------------------------------------------------------------------
def data_append(self,
what):
if not isinstance(what, (str, unicode)):
try:
for item in what: self.data_append(item)
except:
self.data += [str(what)]
else:
self.data += [what]
# ------------------------------------------------------------------
def data_set(self,
what, where):
"""update data entry in column "where". grows data array if needed."""
idx = -1
try:
idx = self.label_index(where)
if len(self.data) <= idx:
self.data_append(['n/a' for i in range(idx+1-len(self.data))]) # grow data if too short
self.data[idx] = str(what)
except(ValueError):
pass
return idx
# ------------------------------------------------------------------
def data_clear(self):
self.data = []
# ------------------------------------------------------------------
def data_asFloat(self):
return list(map(self._transliterateToFloat,self.data))
# ------------------------------------------------------------------
def microstructure_read(self,
grid,
type = 'i',
strict = False):
"""read microstructure data (from .geom format)"""
def datatype(item):
return int(item) if type.lower() == 'i' else float(item)
N = grid.prod() # expected number of microstructure indices in data
microstructure = np.zeros(N,type) # initialize as flat array
i = 0
while i < N and self.data_read():
items = self.data
if len(items) > 2:
if items[1].lower() == 'of': items = np.ones(datatype(items[0]))*datatype(items[2])
elif items[1].lower() == 'to': items = np.arange(datatype(items[0]),1+datatype(items[2]))
else: items = list(map(datatype,items))
else: items = list(map(datatype,items))
s = min(len(items), N-i) # prevent overflow of microstructure array
microstructure[i:i+s] = items[:s]
i += len(items)
return (microstructure, i == N and not self.data_read()) if strict else microstructure # check for proper point count and end of file
|
{"/Code/Spherical/__init__.py": ["/Code/Spherical/asciitable.py", "/Code/Spherical/orientation.py", "/Code/Spherical/util.py"]}
|
14,419
|
chakra34/SphericalOrientations
|
refs/heads/master
|
/Code/Spherical/__init__.py
|
# -*- coding: UTF-8 no BOM -*-
"""Main aggregator"""
import os
from .asciitable import ASCIItable # noqa
from .orientation import Quaternion, Rodrigues, Symmetry, Orientation # noqa
from .util import extendableOption # noqa
|
{"/Code/Spherical/__init__.py": ["/Code/Spherical/asciitable.py", "/Code/Spherical/orientation.py", "/Code/Spherical/util.py"]}
|
14,420
|
chakra34/SphericalOrientations
|
refs/heads/master
|
/Code/unitcell.py
|
#!/usr/bin/env python
# line [thinvectorstyle] (O)(px)
# line [thinvectorstyle] (O)(py)
# # line [thinvectorstyle] (O)(pz)
# special | \path #1 -- #2 node[at end, below] {$ x $}; | (O)(px)
# special | \path #1 -- #2 node[at end, below] {$ y $}; | (O)(py)
# special | \path #1 -- #2 node[at end, above] {$ z $}; | (O)(pz)
import sys,os,math
from optparse import OptionParser
unitcell_choices = ['cubic','hexagonal']
parser = OptionParser(usage='%prog [options]', description = """
Generate vector-based crystal unit overlays from Euler angles.
Angles are specified either directly as argument, resulting in a single file with name derived from the orientation and lattice,
or by scanning through an EDAX/TSL unitcell file from which a batch of unitcells located at the respective positions is produced.
Requires a working setup of 'sketch' (by Gene Ressler) plus 'LaTeX' with 'TikZ' extension.
Column headings need to have names 'phi1', 'Phi', 'phi2'.
$Id: unitcell.py 474 2017-03-10 19:31:50Z p.eisenlohr $
""")
parser.add_option('-u', '-t', '--unitcell', type='string', metavar = 'string',
dest='unitcell',
help='type of unit cell [%s]'%(','.join(unitcell_choices)))
parser.add_option('-n', '--name', type='string', metavar = 'string',
dest='name',
help='filename of output')
parser.add_option('-e', '--eulers', type='float', nargs=3, metavar = 'float float float',
dest='eulers',
help='3-1-3 Euler angles in degrees [%default]')
parser.add_option('-r', '--radians', action='store_true',
dest='radians',
help='Euler angles in radians [%default]')
parser.add_option('-c', '--covera', type='float', metavar = 'float',
dest='ca',
help='c over a ratio [ideal]')
parser.add_option('-o', '--opacity', type='float', metavar = 'float',
dest='opacity',
help='opacity level [%default]')
parser.add_option('-a', '--axes', action='store_true',
dest='axes',
help='show all axes [%default]')
parser.add_option('--globalaxes', action='store_true',
dest='globalaxes',
help='show global axes [%default]')
parser.add_option('--localaxes', action='store_true',
dest='localaxes',
help='show local axes [%default]')
parser.add_option('--vector', type='float', nargs=3, metavar = 'float float float',
dest='vector',
help='draw a lattice vector')
parser.add_option('-p', '--perspective', action='store_true',
dest='perspective',
help='perspective view [%default]')
parser.add_option('-y', '--eye', type='float', nargs=3, metavar = 'float float float',
dest='eye',
help='position of eye on scene [%default]')
parser.add_option( '--up', type='float', nargs=3, metavar = 'float float float',
dest='up',
help='vector corresponding to up direction [%default]')
parser.add_option('-f', '--figure', action='store_true',
dest='figure',
help='produce LaTeX figure compatible file instead of PDF [%default]')
parser.add_option('-k', '--keep', action='store_true',
dest='keep',
help='keep intermediate files [%default]')
parser.add_option('-b', '--batch', type='string', metavar = 'string',
dest='batchfile',
help='EDAX/TSL unitcell file')
parser.add_option('-l', '--label', action='store_true',
dest='label',
help='mark batch processed unit cells by number [%default]')
parser.add_option('-s', '--scale', type='float', metavar = 'float',
dest='scale',
help='scale of diagonal bounding box in batch file [%default]')
parser.add_option('-v', '--verbose', action='store_true',
dest='verbose',
help='verbose output')
parser.set_defaults(unitcell = 'cubic',
batchfile = None,
eulers = [0.0,0.0,0.0],
ca = None,
opacity = 0.8,
scale = 7,
globalaxes = False,
localaxes = False,
axes = False,
perspective = False,
line = None,
eye = [0.0,0.0,1.0],
up = [-1.0,0.0,0.0],
figure = False,
keep = False,
radians = False,
label = False,
verbose = False,
)
(options, args) = parser.parse_args()
if options.unitcell not in unitcell_choices:
parser.error('"%s" not a valid choice for unitcell [%s]'%(options.unitcell,','.join(unitcell_choices)))
if options.axes: options.globalaxes = options.localaxes = options.axes
if not options.ca: options.ca = {'cubic':1,'hexagonal':1.633}[options.unitcell]
opacity = max(0.0,min(1.0,options.opacity))
if options.perspective:
options.perspective = 'view((%f,%f,%f),(0,0,0),[%f,%f,%f]) then perspective(%f)'%((5.0+options.scale)*options.eye[0],\
(5.0+options.scale)*options.eye[1],\
(5.0+options.scale)*options.eye[2],\
options.up[0],\
options.up[1],\
options.up[2],\
80.0/options.scale**0.4)
else:
options.perspective = 'view((%f,%f,%f),(0,0,0),[%f,%f,%f]) then scale(%f)'%(options.scale*options.eye[0],\
options.scale*options.eye[1],\
options.scale*options.eye[2],\
options.up[0],\
options.up[1],\
options.up[2],\
20.0/options.scale)
coords = {
'x':[4,1], # column 4 positive
'y':[3,1], # column 3 positive
}
header = """
def O (0,0,0)
def J [0,0,1]
def px [1,0,0]+(O)
def py [0,1,0]+(O)
def pz [0,0,1]+(O)
def globalSystemAxes
{{
line[color=black,line width=0.5pt] (O)(px)
line[color=black,line width=0.5pt] (O)(py)
line[color=black,line width=0.5pt] (O)(pz)
special |
\path #1 -- #2 node[color=black,font=\\footnotesize,pos=1.25] {{$x$}};
\path #1 -- #3 node[color=black,font=\\footnotesize,pos=1.25] {{$y$}};
\path #1 -- #4 node[color=black,font=\\footnotesize,pos=1.25] {{$z$}};
| (O)(px)(py)(pz)
}}
def localSystemAxes
{{
line[color=red,line width=1.5pt] (O)(px)
line[color=red,line width=1.5pt] (O)(py)
line[color=red,line width=1.5pt] (O)(pz)
special |
\path #1 -- #2 node[color=red,font=\\footnotesize,pos=1.25] {{$x$}};
\path #1 -- #3 node[color=red,font=\\footnotesize,pos=1.25] {{$y$}};
\path #1 -- #4 node[color=red,font=\\footnotesize,pos=1.25] {{$z$}};
| (O)(px)(py)(pz)
}}
def unitcell_hexagonal
{{
def n 6
def ca {ca}
sweep[cull=false,line width={linewidth}pt,fill=white,draw=black,fill opacity={opacity}]
{{n<>,rotate(360/n,(O),[J])}} line (1,0,-ca/2)(1,0,ca/2)
}}
def unitcell_cubic
{{
def n 4
def ca {ca}
sweep[cull=false,line width={linewidth}pt,fill=white,draw=black,fill opacity={opacity}]
{{n<>,rotate(360/n,(O),[J])}} line (0.5,0.5,-ca/2)(0.5,0.5,ca/2)
}}
"""
rotation = """
def EulerRotation_{0}_{1}_{2}
rotate({0},[0,0,1]) then
rotate({1},rotate({0},[0,0,1])*[1,0,0]) then
rotate({2},rotate({1},rotate({0},[0,0,1])*[1,0,0])*[0,0,1])
"""
unitcell = "put {{ [[EulerRotation_{euler[0]}_{euler[1]}_{euler[2]}]] then translate([{dx},{dy},0]) }} {{unitcell_{celltype}}}"
vector = "put {{ [[EulerRotation_{euler[0]}_{euler[1]}_{euler[2]}]] then translate([{dx},{dy},0]) }} {{ line[color=blue,line width=2pt] (O)({vector}) }}"
localaxes = "put {{ [[EulerRotation_{euler[0]}_{euler[1]}_{euler[2]}]] then translate([{dx},{dy},0]) then scale(1.25) }} {{ {{localSystemAxes}} }}"
globalaxes = '{globalSystemAxes}'
label = "special |\\node at #1 {%i};|(%f,%f,0)"
view = """
put { %s }
{
%s
}
"""
footer = """
global { language tikz }
"""
if options.batchfile == None or not os.path.isfile(options.batchfile):
if options.radians:
options.eulers = map(math.degrees,options.eulers)
options.eulers = map(lambda x: x%360.,options.eulers) # Euler angles between 0 and 360 deg
filename = options.name if options.name else 'unitcell_{0}_{1}_{2}_{3}'.format(options.unitcell,*map(lambda x:int(round(x)),options.eulers))
cmd = header.format(ca=options.ca,
linewidth=40/options.scale,
opacity=options.opacity,
)
cmd += rotation.format(*map(lambda x:int(round(x)),options.eulers))
cmd += view %(options.perspective,
(globalaxes if options.globalaxes else '') + \
(localaxes.format(euler = map(lambda x:int(round(x)),options.eulers),
dx = 0.0,dy = 0.0,) if options.localaxes else '') + \
(vector.format(euler = map(lambda x:int(round(x)),options.eulers),
dx = 0.0, dy = 0.0,
vector = ','.join(map(str,options.vector))) if options.vector else '') + \
unitcell.format(euler = map(lambda x:int(round(x)),options.eulers),
dx = 0.0, dy = 0.0,
celltype = options.unitcell,
),
)
cmd += footer
else:
filename = 'unitcell_%s_%s'%(options.unitcell,os.path.basename(os.path.splitext(options.batchfile)[0]))
offset = 0 if os.path.splitext(options.batchfile)[1].lower() == '.ang' else 1
with open(options.batchfile) as batchFile:
content = [line for line in batchFile.readlines() if line.find('#') != 0]
dataset = [map(float,line.split(None if content[0].find(',') < 0 else ',')[offset:offset+5]) for line in content]
print len(dataset)
boundingBox = [
[coords['x'][1]*dataset[0][coords['x'][0]],
coords['y'][1]*dataset[0][coords['y'][0]],
] ,
[coords['x'][1]*dataset[0][coords['x'][0]],
coords['y'][1]*dataset[0][coords['y'][0]],
] ,
]
for point in dataset[1:]:
x = coords['x'][1]*point[coords['x'][0]]
y = coords['y'][1]*point[coords['y'][0]]
if boundingBox[0][0] > x:
boundingBox[0][0] = x
if boundingBox[1][0] < x:
boundingBox[1][0] = x
if boundingBox[0][1] > y:
boundingBox[0][1] = y
if boundingBox[1][1] < y:
boundingBox[1][1] = y
print '---------------------------------'
print boundingBox
print '---------------------------------'
centre = [
(boundingBox[0][0]+boundingBox[1][0])/2.0,
(boundingBox[0][1]+boundingBox[1][1])/2.0,
]
scale = options.scale / \
math.sqrt( (boundingBox[1][0]-boundingBox[0][0])*(boundingBox[1][0]-boundingBox[0][0])+
(boundingBox[1][1]-boundingBox[0][1])*(boundingBox[1][1]-boundingBox[0][1]) )
rotations = {}
cells = []
labels = []
counter = 0
for point in dataset:
counter += 1
x = coords['x'][1]*point[coords['x'][0]]
y = coords['y'][1]*point[coords['y'][0]]
if options.radians:
point[:3] = map(math.degrees,point[:3])
eulers = map(lambda x:str(int(round(x))),point[:3])
rotations['#'.join(eulers)] = rotation.format(*eulers)
cells.append(cell.format(euler=eulers,
dx=scale*(x-centre[0]),
dy=scale*(y-centre[1]),
celltype=options.unitcell)
)
if options.label:
labels.append(label % (counter,
scale*(x-centre[0]),
scale*(y-centre[1]),
))
print len(rotations),'rotations'
cmd = header.format(ca=options.ca,
linewidth=80/options.scale,
opacity=options.opacity
)
cmd += '\n'.join(rotations.values())
cmd += view %(options.perspective,
options.axes,
'\n'.join(cells),
'\n'.join(labels),
)
cmd += footer
with open(filename+'.sk','w') as sk:
sk.write(cmd)
verbosity = '' if options.verbose else '&>/dev/null'
if options.figure:
os.system('sketch -o %s.tex %s.sk %s'%(filename,filename,verbosity))
if not options.keep:
os.remove(filename+'.sk')
else:
os.system('sketch -Tb -o %s.tex %s.sk %s'%(filename,filename,verbosity)) # use tightly bound (-Tb) paper output format
os.system('pdflatex %s.tex 1>/dev/null'%(filename)) # ignore run time messages of pdflatex
if not options.keep:
os.remove(filename+'.sk')
os.remove(filename+'.tex')
os.remove(filename+'.log')
os.remove(filename+'.aux')
|
{"/Code/Spherical/__init__.py": ["/Code/Spherical/asciitable.py", "/Code/Spherical/orientation.py", "/Code/Spherical/util.py"]}
|
14,421
|
chakra34/SphericalOrientations
|
refs/heads/master
|
/Code/Spherical/util.py
|
# -*- coding: UTF-8 no BOM -*-
# obtained from https://damask.mpie.de #
# damask utility functions
import sys,time,random,threading,os,subprocess,shlex
import numpy as np
from optparse import Option
class bcolors:
"""
ASCII Colors (Blender code)
https://svn.blender.org/svnroot/bf-blender/trunk/blender/build_files/scons/tools/bcolors.py
http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python
"""
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
DIM = '\033[2m'
UNDERLINE = '\033[4m'
def disable(self):
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
self.FAIL = ''
self.ENDC = ''
self.BOLD = ''
self.UNDERLINE = ''
# -----------------------------
def srepr(arg,glue = '\n'):
"""joins arguments as individual lines"""
if (not hasattr(arg, "strip") and
hasattr(arg, "__getitem__") or
hasattr(arg, "__iter__")):
return glue.join(srepr(x) for x in arg)
return arg if isinstance(arg,str) else repr(arg)
# -----------------------------
def croak(what, newline = True):
"""writes formated to stderr"""
sys.stderr.write(srepr(what,glue = '\n') + ('\n' if newline else ''))
sys.stderr.flush()
# -----------------------------
def report(who = None,
what = None):
"""reports script and file name"""
croak( (emph(who)+': ' if who else '') + (what if what else '') )
# -----------------------------
def emph(what):
"""boldens string"""
return bcolors.BOLD+srepr(what)+bcolors.ENDC
# -----------------------------
class extendableOption(Option):
"""
used for definition of new option parser action 'extend', which enables to take multiple option arguments
taken from online tutorial http://docs.python.org/library/optparse.html
"""
ACTIONS = Option.ACTIONS + ("extend",)
STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
def take_action(self, action, dest, opt, value, values, parser):
if action == "extend":
lvalue = value.split(",")
values.ensure_value(dest, []).extend(lvalue)
else:
Option.take_action(self, action, dest, opt, value, values, parser)
|
{"/Code/Spherical/__init__.py": ["/Code/Spherical/asciitable.py", "/Code/Spherical/orientation.py", "/Code/Spherical/util.py"]}
|
14,427
|
Kyungpyo-Kang/EV
|
refs/heads/master
|
/EV/urls.py
|
from django.contrib import admin
from django.urls import path
import Main.views
import Community.views
import Introduce.views
import Member.views
import Recommand.views
urlpatterns = [
path('admin/', admin.site.urls),
path('', Main.views.index, name='index'),
path('login/', Member.views.login, name='login'),
path('join/', Member.views.join, name='join'),
path('login_pro/', Member.views.login_pro, name='login_pro'),
path('join_pro/', Member.views.join_pro, name='join_pro'),
path('community/', Community.views.community, name='community'),
path('logout/', Member.views.logout, name='logout'),
path('recommand/', Recommand.views.recommand, name='recommand'),
]
|
{"/EV/urls.py": ["/Community/views.py", "/Member/views.py", "/Recommand/views.py"], "/Member/views.py": ["/Member/models.py"]}
|
14,428
|
Kyungpyo-Kang/EV
|
refs/heads/master
|
/Member/views.py
|
from django.shortcuts import render, redirect
from .models import Member
from django.contrib.auth.models import User
from django.contrib import auth
def login(request):
return render(request, 'login.html')
def join(request):
return render(request, 'join.html')
def join_pro(request):
if request.method == "POST":
if request.POST['password1'] == request.POST['password2']:
user = User.objects.create_user(
username = request.POST['member_id'], password= request.POST['password1']
)
member = Member()
member.user = user
member.member_name = request.POST['member_name']
member.member_email = request.POST['member_email']
member.save()
auth.login(request, user)
return redirect('index')
return render(request, 'join.html')
def login_pro(request):
if request.method == 'POST':
userId = request.POST['userId']
userPw = request.POST['userPw']
user = auth.authenticate(request, username=userId, password=userPw)
if user is not None:
auth.login(request, user)
return redirect('index')
else:
return render(request, 'login.html', {'error': 'username or password is incorrect.'})
else:
return render(request, 'login.html')
def logout(request):
auth.logout(request)
return redirect('index')
|
{"/EV/urls.py": ["/Community/views.py", "/Member/views.py", "/Recommand/views.py"], "/Member/views.py": ["/Member/models.py"]}
|
14,429
|
Kyungpyo-Kang/EV
|
refs/heads/master
|
/Member/models.py
|
from django.db import models
from django.contrib.auth.models import User
class Member(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
member_name = models.CharField(max_length=50)
member_email = models.CharField(max_length=50)
|
{"/EV/urls.py": ["/Community/views.py", "/Member/views.py", "/Recommand/views.py"], "/Member/views.py": ["/Member/models.py"]}
|
14,430
|
Kyungpyo-Kang/EV
|
refs/heads/master
|
/Recommand/views.py
|
from django.shortcuts import render
def recommand(request):
return render(request, 'recommand.html')
|
{"/EV/urls.py": ["/Community/views.py", "/Member/views.py", "/Recommand/views.py"], "/Member/views.py": ["/Member/models.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.