tidy up __init__.py

This commit is contained in:
Damien Elmes 2011-03-13 22:06:17 +09:00
parent 103871a5b1
commit fbb7fe8a3e
4 changed files with 60 additions and 134 deletions

View file

@ -1,61 +1,57 @@
# Copyright: Damien Elmes <anki@ichi2.net>
# License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html
import os, sys, shutil
import os, sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
appName="Anki"
appVersion="1.99"
appWebsite="http://ankisrs.net/"
appWiki="http://ichi2.net/anki/wiki/"
appWiki="http://ankisrs.net/wiki/"
appHelpSite="http://ankisrs.net/docs/"
appIssueTracker="http://code.google.com/p/anki/issues/list"
appForum="http://groups.google.com/group/ankisrs/topics"
appReleaseNotes="http://ankisrs.net/changes.html"
appDonate="http://ankisrs.net/support/"
mw = None # will be set in init
modDir=os.path.dirname(os.path.abspath(__file__))
runningDir=os.path.split(modDir)[0]
mw = None # set on init
# py2exe
if hasattr(sys, "frozen"):
sys.path.append(modDir)
modDir = os.path.dirname(sys.argv[0])
# Dialog manager
# Dialog manager - manages modeless windows
##########################################################################
class DialogManager(object):
def __init__(self):
self.modelessDialogs = {}
from aqt import addcards, cardlist
self._dialogs = {
"AddCards": (addcards.AddCards, None),
"CardList": (cardlist.EditDeck, None),
"Graphs": (self.graphProxy, None)
}
def registerDialog(self, name, klass):
self.modelessDialogs[name] = (klass, None)
def open(self, name, obj):
self.modelessDialogs[name] = (
self.modelessDialogs[name][0], obj)
def open(self, name, *args):
(creator, instance) = self._dialogs[name]
if instance:
instance.activateWindow()
instance.raise_()
return instance
else:
instance = creator(*args)
self._dialogs[name][1] = instance
return instance
def close(self, name):
self.modelessDialogs[name] = (
self.modelessDialogs[name][0], None)
def get(self, name, *args):
(klass, obj) = self.modelessDialogs[name]
if obj:
obj.activateWindow()
obj.raise_()
return obj
else:
return klass(*args)
self._dialogs[name] = (
self._dialogs[name][0], None)
def closeAll(self):
for (n, (klass, obj)) in self.modelessDialogs.items():
if obj:
obj.forceClose = True
obj.close()
for (n, (creator, instance)) in self._dialogs.items():
if instance:
instance.forceClose = True
instance.close()
self.close(n)
# since we load the graphs dynamically, we need a proxy for this
@ -63,14 +59,9 @@ class DialogManager(object):
import graphs
return graphs.intervalGraph(*args)
def registerDialogs(self):
self.registerDialog("AddCards", addcards.AddCards)
self.registerDialog("CardList", cardlist.EditDeck)
self.registerDialog("Graphs", self.graphProxy)
dialogs = DialogManager()
# App initialisation
# Splash screen
##########################################################################
class SplashScreen(object):
@ -110,6 +101,9 @@ color: #13486c;
self.splash.finish(obj)
self.finished = True
# App initialisation
##########################################################################
class AnkiApp(QApplication):
def event(self, evt):
@ -120,31 +114,17 @@ class AnkiApp(QApplication):
return QApplication.event(self, evt)
def run():
import config
mustQuit = False
global mw
# home on win32 is broken
mustQuit = False
if sys.platform == "win32":
# use appdata if available
if 'APPDATA' in os.environ:
oldConf = os.path.expanduser("~/.anki/config.db")
oldPlugins = os.path.expanduser("~/.anki/plugins")
os.environ['HOME'] = os.environ['APPDATA']
else:
oldConf = None
os.environ['HOME'] = "c:\\anki"
# make and check accessible
try:
os.makedirs(os.path.expanduser("~/.anki"))
except:
pass
try:
os.listdir(os.path.expanduser("~/.anki"))
except:
oldConf = None
os.environ['HOME'] = "c:\\anki"
# check accessible again
try:
os.makedirs(os.path.expanduser("~/.anki"))
except:
@ -153,45 +133,23 @@ def run():
os.listdir(os.path.expanduser("~/.anki"))
except:
mustQuit = True
if (oldConf and os.path.exists(oldConf) and not os.path.exists(
oldConf.replace("config.db", "config.db.old"))):
try:
shutil.copy2(oldConf,
os.path.expanduser("~/.anki/config.db"))
shutil.copytree(oldPlugins,
os.path.expanduser("~/.anki/plugins"))
except:
pass
os.rename(oldConf, oldConf.replace("config.db",
"config.db.old"))
# setup paths for forms, icons
sys.path.append(modDir)
# jpeg module
# on osx we'll need to add the qt plugins to the search path
rd = runningDir
if sys.platform.startswith("darwin") and getattr(sys, 'frozen', None):
rd = os.path.abspath(runningDir + "/../../..")
QCoreApplication.setLibraryPaths(QStringList([rd]))
# create the app
app = AnkiApp(sys.argv)
QCoreApplication.setApplicationName("Anki")
if mustQuit:
QMessageBox.warning(
None, "Anki", "Can't open APPDATA, nor c:\\anki.\n"
"Please try removing foreign characters from your username.")
sys.exit(1)
import forms
splash = SplashScreen(3)
import anki
if anki.version != appVersion:
print "You have libanki %s, but this is ankiqt %s" % (
anki.version, appVersion)
print "\nPlease ensure versions match."
return
# parse args
import optparse
parser = optparse.OptionParser()
@ -200,7 +158,7 @@ def run():
default=os.path.expanduser("~/.anki"))
(opts, args) = parser.parse_args(sys.argv[1:])
# configuration
# setup config
import aqt.config
conf = aqt.config.Config(
unicode(os.path.abspath(opts.config), sys.getfilesystemencoding()))
@ -211,26 +169,16 @@ def run():
translationPath = "/usr/share/qt4/translations/"
if translationPath:
long = conf['interfaceLang']
if long == "ja_JP":
# qt is inconsistent
long = long.lower()
short = long.split('_')[0]
qtTranslator = QTranslator()
if qtTranslator.load("qt_" + long, translationPath) or \
qtTranslator.load("qt_" + short, translationPath):
app.installTranslator(qtTranslator)
if conf['alternativeTheme']:
app.setStyle("plastique")
# load main window
import aqt.main
#ui.importAll()
#ui.dialogs.registerDialogs()
splash.update()
import aqt.main
mw = aqt.main.AnkiQt(app, conf, args, splash)
app.exec_()
if __name__ == "__main__":

View file

@ -9,8 +9,7 @@ import anki
from anki.facts import Fact
from anki.errors import *
from anki.utils import stripHTML, parseTags
from aqt.ui.utils import saveGeom, restoreGeom, saveSplitter, restoreSplitter
from aqt import ui
from aqt.utils import saveGeom, restoreGeom, saveSplitter, restoreSplitter
from anki.sound import clearAudioQueue
from anki.hooks import addHook, removeHook

View file

@ -9,12 +9,10 @@ from PyQt4.QtWebKit import QWebPage
import time, types, sys, re
from operator import attrgetter, itemgetter
import anki, anki.utils, aqt.forms
from aqt import ui
from anki.utils import fmtTimeSpan, parseTags, hasTag, addTags, delTags, \
stripHTMLAlt, ids2str
from aqt.ui.utils import saveGeom, restoreGeom, saveSplitter, restoreSplitter
from aqt.ui.utils import saveHeader, restoreHeader, saveState, \
restoreState, applyStyles
from aqt.utils import saveGeom, restoreGeom, saveSplitter, restoreSplitter, \
saveHeader, restoreHeader, saveState, restoreState, applyStyles
from anki.errors import *
from anki.db import *
from anki.stats import CardStats

View file

@ -2,8 +2,8 @@
# -*- coding: utf-8 -*-
# License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html
import os, sys, re, types, gettext, stat, traceback, inspect, signal
import shutil, time, glob, tempfile, datetime, zipfile, locale
import os, sys, re, stat, traceback, signal
import shutil, time, tempfile, zipfile
from operator import itemgetter
from PyQt4.QtCore import *
@ -13,16 +13,10 @@ from PyQt4 import pyqtconfig
QtConfig = pyqtconfig.Configuration()
from anki import Deck
from anki.errors import *
from anki.sound import hasSound, playFromText, clearAudioQueue, stripSounds
from anki.utils import addTags, parseTags, canonifyTags, \
stripHTML, checksum
from anki.stdmodels import BasicModel
from anki.hooks import runHook, addHook, removeHook, _hooks, wrap
from anki.deck import newCardOrderLabels, newCardSchedulingLabels
from anki.deck import revCardOrderLabels, failedCardOptionLabels
import anki.lang
import anki.deck
from anki.utils import addTags, parseTags, canonifyTags, stripHTML, checksum
from anki.hooks import runHook, addHook, removeHook
import anki.consts
import aqt, aqt.utils, aqt.view, aqt.help, aqt.status, aqt.facteditor
from aqt.utils import saveGeom, restoreGeom, showInfo, showWarning, \
@ -53,7 +47,6 @@ class AnkiQt(QMainWindow):
self.setLang()
self.setupStyle()
self.setupFonts()
self.setupBackupDir()
self.setupProxy()
self.setupMainWindow()
self.setupDeckBrowser()
@ -708,10 +701,6 @@ counts are %d %d %d
# Deck loading & saving: backend
##########################################################################
def setupBackupDir(self):
anki.deck.backupDir = os.path.join(
self.config.configPath, "backups")
def loadDeck(self, deckPath, sync=True, interactive=True, uprecent=True):
"Load a deck and update the user interface. Maybe sync."
self.reviewingStarted = False
@ -948,7 +937,6 @@ Debug info:\n%s""") % traceback.format_exc(), help="DeckErrors")
return
self.deck = DeckStorage.Deck(path)
self.deck.initUndo()
self.deck.addModel(BasicModel())
self.deck.save()
if register:
self.updateRecentFiles(self.deck.path)
@ -1534,11 +1522,11 @@ not be touched.""") %
def setupStudyScreen(self):
self.mainWin.buttonStack.hide()
self.mainWin.newCardOrder.insertItems(
0, QStringList(newCardOrderLabels().values()))
0, QStringList(anki.consts.newCardOrderLabels().values()))
self.mainWin.newCardScheduling.insertItems(
0, QStringList(newCardSchedulingLabels().values()))
0, QStringList(anki.consts.newCardSchedulingLabels().values()))
self.mainWin.revCardOrder.insertItems(
0, QStringList(revCardOrderLabels().values()))
0, QStringList(anki.consts.revCardOrderLabels().values()))
self.connect(self.mainWin.optionsHelpButton,
SIGNAL("clicked()"),
lambda: QDesktopServices.openUrl(QUrl(
@ -1956,15 +1944,6 @@ learnt today")
def onPrefs(self):
aqt.preferences.Preferences(self, self.config)
def onReportBug(self):
QDesktopServices.openUrl(QUrl(aqt.appIssueTracker))
def onForum(self):
QDesktopServices.openUrl(QUrl(aqt.appForum))
def onReleaseNotes(self):
QDesktopServices.openUrl(QUrl(aqt.appReleaseNotes))
def onAbout(self):
aqt.about.show(self)
@ -2143,6 +2122,8 @@ it to your friends.
def setLang(self):
"Set the user interface language."
import locale, gettext
import anki.lang
try:
locale.setlocale(locale.LC_ALL, '')
except:
@ -2177,8 +2158,9 @@ it to your friends.
##########################################################################
def setupSync(self):
if not self.config['syncDisableWhenMoved']:
anki.deck.Deck.checkSyncHash = lambda self: True
print "setupSync()"
#if not self.config['syncDisableWhenMoved']:
# anki.deck.Deck.checkSyncHash = lambda self: True
def syncDeck(self, interactive=True, onlyMerge=False, reload=True):
"Synchronise a deck with the server."
@ -2492,8 +2474,6 @@ This deck already exists on your computer. Overwrite the local copy?"""),
self.connect(m.actionGraphs, s, self.onShowGraph)
self.connect(m.actionEditLayout, s, self.onCardLayout)
self.connect(m.actionAbout, s, self.onAbout)
self.connect(m.actionReportbug, s, self.onReportBug)
self.connect(m.actionForum, s, self.onForum)
self.connect(m.actionStarthere, s, self.onStartHere)
self.connect(m.actionImport, s, self.onImport)
self.connect(m.actionExport, s, self.onExport)
@ -2511,7 +2491,6 @@ This deck already exists on your computer. Overwrite the local copy?"""),
self.connect(m.actionOpenPluginFolder, s, self.onOpenPluginFolder)
self.connect(m.actionEnableAllPlugins, s, self.onEnableAllPlugins)
self.connect(m.actionDisableAllPlugins, s, self.onDisableAllPlugins)
self.connect(m.actionReleaseNotes, s, self.onReleaseNotes)
self.connect(m.actionStudyOptions, s, self.onStudyOptions)
self.connect(m.actionDonate, s, self.onDonate)
self.connect(m.actionRecordNoiseProfile, s, self.onRecordNoiseProfile)
@ -2802,9 +2781,10 @@ to work with this version of Anki."""))
self.rebuildPluginsMenu()
def registerPlugin(self, name, updateId):
src = os.path.basename(inspect.getfile(inspect.currentframe(1)))
self.registeredPlugins[src] = {'name': name,
'id': updateId}
return
# src = os.path.basename(inspect.getfile(inspect.currentframe(1)))
# self.registeredPlugins[src] = {'name': name,
# 'id': updateId}
def checkForUpdatedPlugins(self):
pass
@ -3255,4 +3235,5 @@ It can take a long time. Proceed?""")):
def setupBackups(self):
# set backups
anki.deck.numBackups = self.config['numBackups']
print "setupBackups()"
#anki.deck.numBackups = self.config['numBackups']