diff options
author | Aleksey Lim <alsroot@member.fsf.org> | 2009-02-25 22:39:04 (GMT) |
---|---|---|
committer | Aleksey Lim <alsroot@member.fsf.org> | 2009-03-02 06:32:18 (GMT) |
commit | a14cb239a4c84cf7d69a679c9f68f94d76ee74d6 (patch) | |
tree | 5b39109e446bf7fcde979a4382f0fbe2d84b07e9 | |
parent | 05419416978cd3115defbbda3118cb8444495f30 (diff) |
Add book.py
-rw-r--r-- | GUI_Components/Compound_Widgets/Base_Widgets/Readonly_Textbox.py | 13 | ||||
-rw-r--r-- | GUI_Components/Compound_Widgets/Gallery_View.py | 30 | ||||
-rw-r--r-- | GUI_Components/Compound_Widgets/Reading_View.py | 29 | ||||
-rw-r--r-- | GUI_Components/Edit_Pane.py | 67 | ||||
-rw-r--r-- | GUI_Components/Format_Pane.py | 5 | ||||
-rw-r--r-- | GUI_Components/Image_Pane.py | 59 | ||||
-rw-r--r-- | Processing/Article_Builder.py | 10 | ||||
-rw-r--r-- | Processing/IO_Manager.py | 342 | ||||
-rw-r--r-- | Processing/MediaWiki_Helper.py | 2 | ||||
-rw-r--r-- | activity.py | 25 | ||||
-rw-r--r-- | book.py | 74 | ||||
-rw-r--r-- | document.py | 5 | ||||
-rw-r--r-- | edit.py | 9 | ||||
-rw-r--r-- | library.py | 6 |
14 files changed, 269 insertions, 407 deletions
diff --git a/GUI_Components/Compound_Widgets/Base_Widgets/Readonly_Textbox.py b/GUI_Components/Compound_Widgets/Base_Widgets/Readonly_Textbox.py index 08cae3e..489c08a 100644 --- a/GUI_Components/Compound_Widgets/Base_Widgets/Readonly_Textbox.py +++ b/GUI_Components/Compound_Widgets/Base_Widgets/Readonly_Textbox.py @@ -5,7 +5,6 @@ import gtk import pango
import cPickle
from GUI_Components.Compound_Widgets.Base_Widgets.Textbox import Textbox
-from Processing.IO_Manager import IO_Manager
SELECT_SENTENCE, SELECT_PARAGRAPH, SELECT_SECTION, FULL_EDIT = range(4)
@@ -43,22 +42,12 @@ class Readonly_Textbox( Textbox ): self.event_handlers.append(self.connect("move-cursor", self.move_cursor, None))
self.event_handlers.append(self.connect("button-release-event", self.unclicked_event, None))
self.event_handlers.append(self.connect("drag_data_get", self.drag_data_get_event, None))
- self.event_handlers.append(self.connect("drag-data-received", self.drag_data_received, None))
self.event_handlers.append(self.connect("drag-motion", self.drag_motion, None))
def drag_motion(self, widget, context, x, y, timestamp, data):
context.drag_status(gtk.gdk.ACTION_COPY, timestamp)
return True
- def drag_data_received(self, widget, context, x, y, selection_data, info, time, data):
- data_received_type = str(selection_data.type)
- if data_received_type == "article":
- data = cPickle.loads(str(selection_data.data))
- title = data[0]
- theme = data[1]
- article = IO_Manager().load_article(title, theme)
- self.set_article(article)
-
def clicked_event(self, widget, event, data):
if event.type == gtk.gdk._2BUTTON_PRESS or event.type == gtk.gdk._3BUTTON_PRESS:
self.stop_emission("button_press_event")
@@ -177,4 +166,4 @@ class Readonly_Textbox( Textbox ): selection_data.set(atom, 8, string)
self.stop_emission("drag-data-get")
self.set_editable(False)
-
\ No newline at end of file +
diff --git a/GUI_Components/Compound_Widgets/Gallery_View.py b/GUI_Components/Compound_Widgets/Gallery_View.py index b505169..cefe772 100644 --- a/GUI_Components/Compound_Widgets/Gallery_View.py +++ b/GUI_Components/Compound_Widgets/Gallery_View.py @@ -3,11 +3,12 @@ import pygtk pygtk.require('2.0')
import gtk
import cPickle
-from Processing.IO_Manager import IO_Manager
+import logging
+
from GUI_Components.Compound_Widgets.Base_Widgets.Editable_Textbox import Editable_Textbox
from Processing.Article.Article_Data import *
from Processing.Article.Article import Article
-import logging
+import book
logger = logging.getLogger('infoslicer')
@@ -30,7 +31,6 @@ class Gallery_View( gtk.HBox ): """
def __init__(self):
- self.theme = None
self.image_list = []
gtk.HBox.__init__(self)
@@ -59,11 +59,7 @@ class Gallery_View( gtk.HBox ): self.image_drag_container.pack_start(self.imagebox, expand=False)
self.image_drag_container.pack_start(self.caption, expand=False)
- self.articlemenu = gtk.combo_box_new_text()
- self.articlemenu.connect("changed", self.source_selected, None)
-
image_container = gtk.VBox()
- image_container.pack_start(self.articlemenu, expand=False)
image_container.pack_start(gtk.Label(" "))
image_container.pack_start(self.image_drag_container, expand=False)
image_container.pack_start(gtk.Label(" "))
@@ -90,12 +86,7 @@ class Gallery_View( gtk.HBox ): self.get_next_item(right_button, None)
self.source_article_id = 0
- if self.theme == None:
- self.caption.set_text("No theme has been selected, please return to the lirary")
- def insert_new_theme(self, widget, entry):
- pass
-
def get_next_item(self, button, param):
if self.image_list == []:
if self._source_article and self._source_article.article_title:
@@ -147,22 +138,9 @@ class Gallery_View( gtk.HBox ): def set_image_list(self, image_list):
logger.debug("validagting image list")
- self.image_list = IO_Manager().validate_image_list(image_list)
+ self.image_list = book.wiki.validate_image_list(image_list)
logger.debug(self.image_list)
- def source_selected(self, combobox, param):
- if combobox.get_active_text() == None :
- return
- if self.theme == None:
- logger.debug("no theme set, defaulting to Wikipedia Articles")
- self.theme = "Wikipedia Articles"
- if self._source_article.article_title == combobox.get_active_text():
- return
- self._source_article = IO_Manager().load_article(combobox.get_active_text(), self.theme)
- self.set_image_list(self._source_article.image_list)
- self.get_first_item()
-
-
def drag_begin_event(self, widget, context, data):
self.imagebox.drag_source_set_icon_pixbuf(self.imagebuf)
diff --git a/GUI_Components/Compound_Widgets/Reading_View.py b/GUI_Components/Compound_Widgets/Reading_View.py index 9480be6..787f6a9 100644 --- a/GUI_Components/Compound_Widgets/Reading_View.py +++ b/GUI_Components/Compound_Widgets/Reading_View.py @@ -3,7 +3,6 @@ import pygtk pygtk.require('2.0')
import gtk
from GUI_Components.Compound_Widgets.Base_Widgets.Readonly_Textbox import Readonly_Textbox
-from Processing.IO_Manager import IO_Manager
import logging
logger = logging.getLogger('infoslicer')
@@ -19,17 +18,11 @@ class Reading_View( gtk.VBox ): articles which can be selected.
If an article is selected in the combobox, the readonly_textbox will
be set to display the newly selected article.
- The articles are loaded using IO_Manager
"""
def __init__(self):
gtk.VBox.__init__(self)
- self.articlemenu = gtk.combo_box_new_text()
- self.articlemenu.connect("changed", self.source_selected, None)
- self.pack_start(self.articlemenu, False, False, 1)
- self.articlemenu.show()
-
self.articlewindow = gtk.ScrolledWindow()
self.articlewindow.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
self.pack_start(self.articlewindow)
@@ -39,28 +32,6 @@ class Reading_View( gtk.VBox ): self.articlewindow.add(self.textbox)
self.textbox.show()
- def source_selected(self, combo, data):
- title = combo.get_active_text()
- if title == "Select a source article from this menu" or title == None:
- return
- if self.textbox.get_article() == None or self.textbox.get_article().article_title == title:
- return
- if combo.get_active != 0:
- model = combo.get_model()
- firstiter = model.get_iter_first()
- firstvalue = model.get_value(firstiter, 0)
- logger.debug(firstvalue)
- if firstvalue == "Select a source article from this menu":
- combo.remove_text(0)
-
- if self.textbox.get_article() != None:
- theme = "Wikipedia Articles"
- try:
- newarticle = IO_Manager().load_article(title, theme)
- self.textbox.set_article(newarticle)
- except Exception, e:
- elogger.debug('source_selected: %s' % e)
-
def set_sentence_selection_mode(self):
self.textbox.set_mode(0)
diff --git a/GUI_Components/Edit_Pane.py b/GUI_Components/Edit_Pane.py index ead04b1..ae13188 100644 --- a/GUI_Components/Edit_Pane.py +++ b/GUI_Components/Edit_Pane.py @@ -10,7 +10,6 @@ from sugar.graphics.toolcombobox import ToolComboBox from GUI_Components.Compound_Widgets.Reading_View import Reading_View from GUI_Components.Compound_Widgets.Editing_View import Editing_View from Processing.Article.Article import Article -from Processing.IO_Manager import IO_Manager logger = logging.getLogger('infoslicer') @@ -34,13 +33,28 @@ class Edit_Pane(gtk.HBox): gtk.HBox.__init__(self) self.toolitems = [] + readarticle_box = gtk.VBox() + readarticle_box.show() + + labeleb = gtk.EventBox() + labeleb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#EEEEEE")) + readarticle_box.pack_start(labeleb, False, False, 0) + labeleb.show() + + self.articletitle = gtk.Label() + self.articletitle.set_justify(gtk.JUSTIFY_CENTER) + labeleb.add(self.articletitle) + self.articletitle.show() + """ Create reading and editing panels """ self.readarticle = Reading_View() - self.pack_start(self.readarticle) + self.readarticle.set_size_request(gtk.gdk.screen_width()/2, -1) self.readarticle.show() - + readarticle_box.pack_start(self.readarticle) + self.pack_start(readarticle_box, False) + self.editarticle = Editing_View() self.pack_start(self.editarticle) self.editarticle.show() @@ -76,51 +90,20 @@ class Edit_Pane(gtk.HBox): self.editarticle.set_section_selection_mode() #logger.debug(current_selection) - """ - Grab source article from IO manager and set up as editing source. - """ def set_source_article(self, article): if self.readarticle.textbox.get_article() == article: return - # Populate the drop down menu with the articles in the current theme - article_theme = article.article_theme - article_title = article.article_title - if article_title == None: - article_title = "" - """ Grab media wiki pages from default wikipedia theme """ - titles = IO_Manager().get_pages_in_theme(_("Wikipedia Articles")) - self.readarticle.articlemenu.get_model().clear() - """ Check user has downloaded some source articles """ - if titles != []: - self.readarticle.articlemenu.append_text(_("Select a source article from this menu")) - if article_title == "": - buf = article.getBuffer() - start = buf.get_start_iter() - end = buf.get_end_iter() - buf.delete(start, end) - buf.insert(buf.get_start_iter(), _("You can choose a Wikipedia article to copy from by selecting it from the drop-down menu above.")) - buf.insert(buf.get_end_iter(), _("If you want to download more articles from Wikipedia, you can do this in the Library tab.")) - else: - buf = article.getBuffer() - buf.insert(buf.get_start_iter(), _("You have not downloaded any articles from Wikipedia. You can download new articles in the Library tab.")) - - i = 0 - selectionindex = 0 - for title in titles: - self.readarticle.articlemenu.append_text(title) - i = i + 1 - if title == article_title: - selectionindex = i - - self.readarticle.articlemenu.set_active(selectionindex) - - # Set the read article as appropriate. + + self.articletitle.set_markup( + "<span size='medium'><b> %s </b> %s</span>" % \ + (_("Article:"), article.article_title)) + self.readarticle.textbox.set_article(article) def set_working_article(self, article): if self.editarticle.textbox.get_article() == article: return - self.editarticle.articletitle.set_markup("<span size='medium'><b> %s </b> %s \n<b> %s </b> %s</span>" % \ - (_("Theme:"), article.article_theme, _("Article:"), article.article_title)) + self.editarticle.articletitle.set_markup( + "<span size='medium'><b> %s </b> %s</span>" % \ + (_("Article:"), article.article_title)) self.editarticle.textbox.set_article(article) - self.editarticle.article_theme = _("Wikipedia Articles") diff --git a/GUI_Components/Format_Pane.py b/GUI_Components/Format_Pane.py index 8ad43f3..72c04b6 100644 --- a/GUI_Components/Format_Pane.py +++ b/GUI_Components/Format_Pane.py @@ -49,6 +49,7 @@ class Format_Pane(Editing_View): def set_working_article(self, article): if self.textbox.get_article() == article: return - self.articletitle.set_markup("<span size='medium'><b> %s </b> %s \n<b> %s </b> %s</span>" % \ - (_("Theme:"), article.article_theme, _("Article:"), article.article_title)) + self.articletitle.set_markup( + "<span size='medium'><b> %s </b> %s</span>" % \ + (_("Article:"), article.article_title)) self.textbox.set_article(article) diff --git a/GUI_Components/Image_Pane.py b/GUI_Components/Image_Pane.py index 9c45bce..f5a3023 100644 --- a/GUI_Components/Image_Pane.py +++ b/GUI_Components/Image_Pane.py @@ -8,7 +8,6 @@ from gettext import gettext as _ from GUI_Components.Compound_Widgets.Editing_View import Editing_View from GUI_Components.Compound_Widgets.Gallery_View import Gallery_View from Processing.Article.Article import Article -from Processing.IO_Manager import IO_Manager logger = logging.getLogger('infoslicer') @@ -27,8 +26,24 @@ class Image_Pane(gtk.HBox): gtk.HBox.__init__(self) self.toolitems = [] + gallery_box = gtk.VBox() + gallery_box.show() + + labeleb = gtk.EventBox() + labeleb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#EEEEEE")) + gallery_box.pack_start(labeleb, False, False, 0) + labeleb.show() + + self.articletitle = gtk.Label() + self.articletitle.set_justify(gtk.JUSTIFY_CENTER) + labeleb.add(self.articletitle) + self.articletitle.show() + self.gallery = Gallery_View() - self.pack_start(self.gallery) + self.gallery.set_size_request(gtk.gdk.screen_width()/2, -1) + gallery_box.pack_start(self.gallery) + + self.pack_start(gallery_box, False) self.editarticle = Editing_View() self.pack_start(self.editarticle) self.editarticle.show_all() @@ -38,23 +53,22 @@ class Image_Pane(gtk.HBox): def set_source_article(self, source): if self.gallery._source_article == source: return - logger.debug("source received. title: %s, theme: %s" % - (source.article_title, source.article_theme)) + + logger.debug("source received. title: %s" % source.article_title) current = self.gallery._source_article self.gallery._source_article = source + + self.articletitle.set_markup( + "<span size='medium'><b> %s </b> %s</span>"% \ + (_("Article:"), source.article_title)) + if source and source.article_title: - source.article_theme = _("Wikipedia Articles") - if current: - if current.article_title == source.article_title and current.article_theme == source.article_theme: - logger.debug("same") - return self.gallery.current_index = 0 if source.image_list != []: logger.debug("setting images") self.gallery.set_image_list(source.image_list) self.gallery.get_first_item() - self.gallery.theme = _("Wikipedia Articles") self.gallery.source_article_id = source.source_article_id logger.debug(source.image_list) else: @@ -68,22 +82,11 @@ class Image_Pane(gtk.HBox): def set_working_article(self, article): if self.editarticle.textbox.get_article() == article: return - logger.debug("working received, title %s theme %s " % - (article.article_title, article.article_theme)) - self.editarticle.articletitle.set_markup("<span size='medium'><b> %s </b> %s \n<b> %s </b> %s</span>"% \ - (_("Theme:"), article.article_theme, _("Article:"), article.article_title)) - if article == None: - article = Article() + + logger.debug("working received, title %s" % article.article_title) + + self.editarticle.articletitle.set_markup( + "<span size='medium'><b> %s </b> %s</span>"% \ + (_("Article:"), article.article_title)) + self.editarticle.textbox.set_article(article) - if article.article_theme == None: - article.article_theme = _("My Articles") - theme_list = IO_Manager().get_pages_in_theme(_("Wikipedia Articles")) - self.gallery.theme = _("Wikipedia Articles") - count = -1 - self.gallery.articlemenu.get_model().clear() - - for item in theme_list: - count += 1 - self.gallery.articlemenu.append_text(item) - if self.gallery._source_article != None and item == self.gallery._source_article.article_title: - self.gallery.articlemenu.set_active(count) diff --git a/Processing/Article_Builder.py b/Processing/Article_Builder.py index 276be4c..bc59d14 100644 --- a/Processing/Article_Builder.py +++ b/Processing/Article_Builder.py @@ -4,7 +4,6 @@ from BeautifulSoup import Tag from NewtifulSoup import NewtifulStoneSoup as BeautifulStoneSoup
from Processing.Article.Article_Data import *
import re
-import IO_Manager
import logging
logger = logging.getLogger('infoslicer')
@@ -20,14 +19,15 @@ class Article_Builder: This class converts between DITA and article_data representation of articles. Badly in need of refactoring!
"""
-
-
+
+ def __init__(self, workingDir):
+ self.workingDir = workingDir
def get_article_from_dita(self, dita):
"""
This method takes an article in DITA format as input, parses the DITA, and outputs the corresponding article_data object
"""
- workingDir = IO_Manager.IO_Manager().workingDir
+ workingDir = self.workingDir
self.sentences = []
has_shortdesc = False
input = BeautifulStoneSoup(dita)
@@ -160,7 +160,7 @@ class Article_Builder: It calls the getData method of the article class to get the article_data representation of the article.
It then constructs the corresponding DITA representation of the article.
"""
- workingDir = IO_Manager.IO_Manager().workingDir
+ workingDir = self.workingDir
article_data = article.getData()
output = BeautifulStoneSoup("<?xml version='1.0' encoding='utf-8'?><!DOCTYPE reference PUBLIC \"-//IBM//DTD DITA IBM Reference//EN\" \"ibm-reference.dtd\"><reference><title>%s</title><prolog></prolog></reference>" % article_data.article_title)
current_ref = output.reference
diff --git a/Processing/IO_Manager.py b/Processing/IO_Manager.py index 9ffcb3f..d349ab2 100644 --- a/Processing/IO_Manager.py +++ b/Processing/IO_Manager.py @@ -1,16 +1,19 @@ # Copyright (C) IBM Corporation 2008
import gtk
+import shutil
+import re
+import logging
+import os
+import urllib
+from gettext import gettext as _
+
from BeautifulSoup import Tag
from NewtifulSoup import NewtifulStoneSoup as BeautifulStoneSoup
-import os, platform, urllib
from Article_Builder import Article_Builder
from Processing.Article.Article import Article
from MediaWiki_Helper import MediaWiki_Helper, PageNotFoundError
from MediaWiki_Parser import MediaWiki_Parser
-import shutil
-import re
-import logging
logger = logging.getLogger('infoslicer')
elogger = logging.getLogger('infoslicer::except')
@@ -33,43 +36,14 @@ class theme_exists_error(Exception): def __str__(self):
return repr(self.parameter)
-
"""
This class sits between the GUI and the back end (handling
-mediawiki communication and raw pages/theme/article modifications)
+mediawiki communication and raw pages/article modifications)
"""
class IO_Manager:
-
- def __init__(self):
- running_on = platform.system()
- if running_on == "Windows":
- # On Windows, used to save to a data subfolder of the folder that contains this code
- #self.workingDir = os.path.join(__file__.rsplit("\\", 1)[0], "Data")
- # but better to write to user home with os.getenv("USERPROFILE") or os.path.expanduser("~")
- self.workingDir = os.path.join(os.getenv("USERPROFILE"), ".slicedata")
- elif running_on == "Linux":
- if "olpc" in platform.platform().lower():
- from sugar.activity import activity
- # On Sugar, save to the data subfolder of the app directory
- self.workingDir = os.path.join(activity.get_activity_root(), "data")
- logger.debug("Activity root is: %s" %
- str(activity.get_activity_root()))
- logger.debug("Data folder is: %s" % self.workingDir)
- else:
- # On Linux, save to a .slicedata subdir of the user's homedir
- self.workingDir = os.path.join(os.getenv("HOME"), ".slicedata")
- self.proxies = {}
- proxy_file = os.path.join(os.path.split(os.path.split(__file__)[0])[0], 'proxy.cfg')
- if os.access(proxy_file, os.F_OK):
- proxy_file_handle = open(proxy_file, "r")
- for line in proxy_file_handle.readlines():
- parts = line.split(':', 1)
- #logger.debug("setting " + parts[0] + " proxy to " + parts[1])
- self.proxies[parts[0].strip()] = parts[1].strip()
- proxy_file_handle.close()
- if self.proxies == {}:
- self.proxies = None
-
+ def __init__(self, foo):
+ pass
+
def clean_title(self, title):
"""
removes non-alphanumeric chars from titles and lowercases it
@@ -79,79 +53,32 @@ class IO_Manager: logger.debug("Output: " + output)
return output
- def install_library(self):
- if platform.system() == "Linux" and "olpc" in platform.platform().lower():
- file_list = [('Lion (from en.wikipedia.org)', os.path.join(os.path.split(__file__)[0], "demolibrary", "lion-wikipedia.dita"), 'Wikipedia Articles'), ('Tiger (from en.wikipedia.org)', os.path.join(os.path.split(__file__)[0], "demolibrary", "tiger-wikipedia.dita"), 'Wikipedia Articles'), ('Giraffe (from en.wikipedia.org)', os.path.join(os.path.split(__file__)[0], "demolibrary", "giraffe-wikipedia.dita"), 'Wikipedia Articles'), ('Giraffe', os.path.join(os.path.split(__file__)[0], "demolibrary", "giraffe-blank.dita"), 'My Articles'), ('Zebra (from en.wikipedia.org)', os.path.join(os.path.split(__file__)[0], "demolibrary", "zebra-wikipedia.dita"), 'Wikipedia Articles')]
- for file in file_list:
- if file[2] not in self.get_themes():
- logger.debug("install library: creating theme %s" %
- file[2])
- self.add_theme_to_library(file[2])
- logger.debug("install library: opening %s" % file[1])
- open_file = open(file[1], "r")
- contents = open_file.read()
- open_file.close()
- if contents:
- logger.debug("install library: content read sucessfully")
- logger.debug("install library: saving page %s" % file[0])
- self.save_page(file[0], contents, file[2], get_images=True)
- logger.debug("install library: save successful")
-
- def __add_page_to_library(self, title, path, theme="My Articles"):
- """
- Adds a page to the library. If a theme is specified it is added to that theme, otherwise it is put into the 'No Assigned Theme' theme.
+ def __add_page_to_library(self, title, path):
+ """
+ Adds a page to the library.
@param title: The title of the article to add to library.
@param path: The path of the article to add to library.
- @param theme: Which theme to store the article in. (Optional, defaults to No Assigned Theme).
"""
try:
#change to relative path
path = path.replace(os.path.join(self.workingDir, ""), "", 1)
- map = self.load_map(theme)
+ map = self.load_map()
existing_entry = map.find("topicref", attrs={"navtitle" : title})
if existing_entry != None:
existing_entry.extract()
map.map.append(Tag(map, "topicref", [("href", path), ("navtitle", title)]))
- self.save_map(theme, map)
+ self.save_map(map)
except Exception, e:
elogger.debug('__add_page_to_library: %s' % e)
- self.add_theme_to_library(theme)
- self.__add_page_to_library(title, path, theme)
+ self.__add_page_to_library(title, path)
- def add_theme_to_library(self, theme):
- """
- Adds themes to the library.
- @param theme: Theme to add.
- @raise theme_exists_error: If trying to add theme that already exists.
- """
- try:
- map = self.load_map("Library")
- # Ensure theme does not exist
- if map.find(attrs={"navtitle" : theme}) == None:
- # create a new entry in the library for the theme
- map.map.append(Tag(map, "topicref", [("format", "ditamap"), ("href", "%s.ditamap" % self.clean_title(theme)), ("navtitle", theme)]))
- # save the theme file
- self.__create_map(theme)
- else:
- raise theme_exists_error("Theme already exists")
- self.save_map("Library", map)
- except theme_not_found_error, e:
- elogger.debug('add_theme_to_library: %s' % e)
- # this error is caused by failing to open the library, so create the library and try again
- self.__create_map("Library")
- self.add_theme_to_library(theme)
-
- def __create_map(self, map_name):
- """
- Creates a new map for the specified theme name.
- @param map_name: name of map theme.
- """
- self.save_map(map_name, BeautifulStoneSoup(\
+ def __create_map(self):
+ return BeautifulStoneSoup(\
'<?xml version="1.0" encoding="utf-8"?>\
<!DOCTYPE map PUBLIC "-//IBM//DTD DITA IBM Map//EN" "ibm-map.dtd">\
- <map title="%s">\
- </map>' % map_name))
+ <map title="footheme">\
+ </map>')
def download_wiki_article(self, title, theme, wiki=None, statuslabel = None):
"""
@@ -191,16 +118,15 @@ class IO_Manager: # file.write(contents)
# file.close()
- def get_pages_in_theme(self, theme):
+ def get_pages(self):
"""
- Returns a list of all pages in the specified theme.
- @param theme: Theme to query
+ Returns a list of all pages
@return: List of dictionaries containing page 'path' and 'title'.
"""
try:
- map = self.load_map(theme)
+ map = self.load_map()
except Exception, e:
- elogger.debug('get_pages_in_theme: %s' % e)
+ elogger.debug('get_pages: %s' % e)
return []
output = []
for page in map.map.findAll("topicref"):
@@ -208,22 +134,6 @@ class IO_Manager: output.sort()
return output
- def get_themes(self):
- """
- Returns a list of all themes stored in the library.
- @return: List of theme names.
- """
- try:
- map = self.load_map("Library")
- output = []
- for theme in map.findAll("topicref"):
- output.append(theme["navtitle"])
- output.sort()
- return output
- except Exception, e:
- elogger.debug('get_themes: %s' % e)
- return []
-
def get_unique_article_ID(self):
"""
Creates and maintains a file to record the last unique article ID issued.
@@ -300,35 +210,38 @@ class IO_Manager: image.extract()
return document.prettify()
- def load_map(self, map_name):
+ def load_map(self):
"""
Loads the specified theme map.
- @param map_name: Name of theme map to load
@return: map contents as a Soup
@raise theme_not_found_error: If theme map not found.
"""
- if not os.access(os.path.join(self.workingDir, "%s.ditamap" % self.clean_title(map_name)), os.F_OK):
- raise theme_not_found_error("Theme '" + map_name + "' not found")
- file = open(os.path.join(self.workingDir, "%s.ditamap" % self.clean_title(map_name)), "r")
+ filepath = os.path.join(self.workingDir, "ditamap")
+
+ if not os.access(filepath, os.F_OK):
+ logger.debug('create new map')
+ return self.__create_map();
+
+ file = open(filepath, "r")
map = BeautifulStoneSoup(file.read())
file.close()
+
return map
- def load_raw_page(self, title, theme):
+ def load_raw_page(self, title):
"""
Returns contents of specified page.
@param title: Title of page to open.
- @param theme: Theme of page to open.
@return: Contents of page.
"""
- theme_map = self.load_map(theme)
- logger.debug(title + theme)
+ theme_map = self.load_map()
+ logger.debug(title)
page_location = theme_map.find("topicref", attrs={ "navtitle" : title })
if page_location != None:
page_location = page_location['href']
else:
- raise page_not_found_error("No match for " + title + " in " + theme)
+ raise page_not_found_error("No match for " + title)
#if not os.access(page_location, os.F_OK):
if os.access(os.path.join(self.workingDir, page_location), os.F_OK):
@@ -340,58 +253,19 @@ class IO_Manager: page.close()
return output
- def load_page(self, title, theme):
- return Article_Builder().get_article_from_dita(self.load_raw_page(title, theme))
+ def load_page(self, title):
+ return Article_Builder(self.workingDir).get_article_from_dita(
+ self.load_raw_page(title))
- def copy_page(self, title, fromtheme, totheme):
- """
- Copys a page from one theme to another. If no title specified, all pages in theme are moved.
- @param page_title: Title of page to move. (Optional, defaults to None)
- @param from_theme: Source theme.
- @param to_theme: Destination theme.
- """
- logger.debug("COPY PAGE %s FROM %s TO %s" %
- (title, fromtheme, totheme))
- article = self.load_raw_page(title, fromtheme)
- self.save_page(title, article, totheme, overwrite=False)
-
- def load_article(self, title, theme):
+ def load_article(self, title):
"""
loads the specified article
"""
- article_data = self.load_page(title, theme)
+ article_data = self.load_page(title)
article = Article(article_data)
article.article_title = title
- article.article_theme = theme
return article
- def move_page(self, from_theme, to_theme, page_title = None):
- """
- Moves a page from one theme to another. If no title specified, all pages in theme are moved.
- @param page_title: Title of page to move. (Optional, defaults to None)
- @param from_theme: Source theme.
- @param to_theme: Destination theme.
- """
- try:
- from_map = self.load_map(from_theme)
- to_map = self.load_map(to_theme)
- if page_title == None:
- pages = from_map.findAll("topicref")
- else:
- pages = [from_map.find("topicref", attrs={"navtitle" : page_title})]
- if pages == [None] or pages == []:
- raise exception("not found")
- for page in pages:
- to_map.map.append(page)
- self.save_map(to_theme, to_map)
- for page in pages:
- page.extract()
- self.save_map(from_theme, from_map)
- except Exception, e:
- elogger.debug('move_page: %s' % e)
- # Shouldn't ever happen
- pass
-
def __open_URL(self, url):
"""
retrieves content from specified url
@@ -399,8 +273,8 @@ class IO_Manager: urllib._urlopener = self.New_URL_Opener()
try:
logger.debug("opening " + url)
- logger.debug("proxies: " + str(self.proxies))
- doc = urllib.urlopen(url, proxies=self.proxies)
+ logger.debug("proxies: " + str(proxies))
+ doc = urllib.urlopen(url, proxies=proxies)
output = doc.read()
doc.close()
logger.debug("url opened succesfully")
@@ -408,12 +282,12 @@ class IO_Manager: except IOError, e:
elogger.debug('__open_URL: %s' % e)
- def page_exists(self, title, theme):
+ def page_exists(self, title):
"""
boolean check if an article exists
"""
try:
- map = self.load_map(theme)
+ map = self.load_map()
if map.find("topicref", attrs={"navtitle" : title}) != None:
return True
else:
@@ -422,127 +296,83 @@ class IO_Manager: elogger.debug('page_exists: %s' % e)
return False
- def theme_exists(self, theme):
+ def remove_page(self, page):
"""
- boolean check if a theme exists
- """
- themes = self.get_themes()
- if theme in themes:
- return True
- else:
- return False
-
- def remove_page(self, page, theme):
- """
- Removes specified page from the specified theme.
+ Removes specified page from the specified.
@param page: Page to remove
- @param theme: Containing theme
"""
- if theme == "Downloaded Articles":
- return
- theme_map = self.load_map(theme)
+ theme_map = self.load_map()
entry = theme_map.find("topicref", attrs={"navtitle" : page})
try:
os.remove(entry['href'])
except Exception, e:
elogger.debug('remove_page: %s' % e)
entry.extract()
- self.save_map(theme, theme_map)
-
- def remove_theme(self, theme):
- """
- Removes specified theme, moving all articles in it to the 'No Assigned Theme' theme.
- @param theme: Theme to remove
- """
- try:
- #Just remove map from library at the moment
- #self.move_pages(theme, "No Assigned Theme")
- library = self.load_map("Library")
- entry = library.find("topicref", attrs={"navtitle" : theme})
- if entry != None:
- os.remove(os.path.join(self.workingDir, entry['href']))
- entry.extract()
- self.save_map("Library", library)
- except Exception, e:
- # Trying to remove a theme that doesn't exist, so pretend it worked.
- elogger.debug('remove_theme: %s' % e)
+ self.save_map(theme_map)
- def rename_page(self, theme, old_title, new_title):
+ def rename_page(self, old_title, new_title):
"""
- renames specified page in specified theme
+ renames specified page
"""
try:
- map = self.load_map(theme)
+ map = self.load_map()
page = map.find("topicref", attrs={"navtitle" : old_title})
if page != None:
page['navtitle'] = new_title
- self.save_map(theme, map)
+ self.save_map(map)
except Exception, e:
elogger.debug('rename_page: %s' % e)
- def rename_theme(self, old_name, new_name):
- """
- renames specified theme
- """
- library = self.load_map("Library")
- entry = library.find("topicref", attrs={"navtitle" : old_name})
- if entry != None and library.find("topicref", attrs={"navtitle" : new_name}) == None:
- self.add_theme_to_library(new_name)
- theme = self.load_map(entry['navtitle'])
- theme.map['name'] = new_name
- self.save_map(new_name, theme)
- self.remove_theme(old_name)
-
def save_article(self, article, overwrite = True):
"""
wrapper method for save_page to allow saving article objects
"""
title = article.article_title
- theme = article.article_theme
- if title != None and theme != None:
- contents = Article_Builder().get_dita_from_article(article)
- self.save_page(title, contents, theme, overwrite)
+ if title != None:
+ contents = Article_Builder(self.workingDir).get_dita_from_article(
+ article)
+ self.save_page(title, contents, overwrite)
else:
- raise theme_not_found_error("Theme or title not specified")
+ raise theme_not_found_error("Title not specified")
- def save_map(self, map_name, map_data):
+ def save_map(self, map_data):
"""
Saves the specified map.
- @param map_name: Name of map
@param map_data: Contents of map
"""
if not os.path.exists(self.workingDir):
os.makedirs(self.workingDir, 0777)
- map = open(os.path.join(self.workingDir, "%s.ditamap" % self.clean_title(map_name)), "w")
+ map = open(os.path.join(self.workingDir, "ditamap"), "w")
map.write(map_data.prettify())
map.close()
- def save_page(self, title, contents, theme="Downloaded Articles", overwrite=True, get_images=False, statuslabel=None):
+ def save_page(self, title, contents, get_images=False, statuslabel=None):
"""
- Saves the specified page contents as specified title (in optional specified theme).
+ Saves the specified page contents as specified title.
@param title: Title to save as.
@param contents: Contents to save.
- @param theme: Theme to save in.
- @param overwrite: Boolean to specify overwrite if file already exists.
"""
- unique=2
- new_title = self.clean_title(title) + "-" + self.clean_title(theme)
+ new_title = self.clean_title(title)
if get_images:
contents = self.image_handler(contents, title, statuslabel)
+
directory = os.path.join(self.workingDir, self.clean_title(title))
+
if not os.path.exists(directory):
- os.makedirs(directory, 0777)
- if overwrite == False:
- while os.access(os.path.join(directory, "%s.dita" % new_title), os.F_OK):
- new_title = self.clean_title(title) + str(unique)
- unique += 1
- contents = contents.replace('<prolog>', '<prolog>\n<resourceid id="%d" />' % self.get_unique_article_ID(), 1)
+ os.makedirs(directory, 0777)
+
+ contents = contents.replace(
+ '<prolog>', '<prolog>\n<resourceid id="%d" />'
+ % self.get_unique_article_ID(), 1)
+
file = open(os.path.join(directory, "%s.dita" % new_title), "w")
file.write(contents)
file.close()
- self.__add_page_to_library(title, os.path.join(directory, "%s.dita" % new_title), theme)
+ self.__add_page_to_library(title, os.path.join(directory, "%s.dita" % new_title))
+
logger.debug("Page saved to - " + os.path.join(directory, "%s.dita" %
new_title))
+
return os.path.join(directory, "%s.dita" % new_title)
def validate_image_list(self, image_list):
@@ -563,4 +393,22 @@ class IO_Manager: return image_list
class New_URL_Opener(urllib.FancyURLopener):
- version = "Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"
+ version = "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1b2)" \
+ "Gecko/20081218 Gentoo Iceweasel/3.1b2"
+
+# http proxy
+
+proxies = {}
+
+proxy_file = os.path.join(os.path.split(os.path.split(__file__)[0])[0], 'proxy.cfg')
+
+if os.access(proxy_file, os.F_OK):
+ proxy_file_handle = open(proxy_file, "r")
+ for line in proxy_file_handle.readlines():
+ parts = line.split(':', 1)
+ #logger.debug("setting " + parts[0] + " proxy to " + parts[1])
+ proxies[parts[0].strip()] = parts[1].strip()
+ proxy_file_handle.close()
+
+if proxies == {}:
+ proxies = None
diff --git a/Processing/MediaWiki_Helper.py b/Processing/MediaWiki_Helper.py index a15f4d0..acfc74d 100644 --- a/Processing/MediaWiki_Helper.py +++ b/Processing/MediaWiki_Helper.py @@ -38,7 +38,7 @@ content based on a number of parameters such as URL, Title, Revision. class MediaWiki_Helper:
def __init__(self):
- self.proxies = IO_Manager.IO_Manager().proxies
+ self.proxies = IO_Manager.proxies
def resolveTitle(self, title, wiki=defaultWiki):
"""Check if a wiki article exists using the mediawiki api. Follow redirects.
diff --git a/activity.py b/activity.py index 4b6188e..c5d7c5e 100644 --- a/activity.py +++ b/activity.py @@ -22,6 +22,7 @@ from sugar.activity.activity import ActivityToolbox from shared import SharedActivity import library import edit +import book gtk.gdk.threads_init() gtk.gdk.threads_enter() @@ -29,14 +30,23 @@ gtk.gdk.threads_enter() class InfoslicerActivity(SharedActivity): def __init__(self, handle): self.notebook = gtk.Notebook() + self.notebook.show() + self.notebook.props.show_border = False + self.notebook.props.show_tabs = False + SharedActivity.__init__(self, self.notebook, 'SERVICE', handle) self.connect('init', self._init_cb) self.connect('tube', self._tube_cb) - self.notebook.show() - self.notebook.props.show_border = False - self.notebook.props.show_tabs = False + def read_file(self, filepath): + pass + + def write_file(self, filepath): + pass + + def _init_cb(self, sender): + book.init() self.library = library.View() self.library.show() @@ -61,15 +71,6 @@ class InfoslicerActivity(SharedActivity): toolbox.set_current_toolbar(1) - def read_file(self, filepath): - pass - - def write_file(self, filepath): - pass - - def _init_cb(self, sender): - pass - def _tube_cb(self, activity, tube_conn, initiating): pass @@ -0,0 +1,74 @@ +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +import os +import gtk +import logging +from gettext import gettext as _ + +from sugar.activity.activity import get_bundle_path, get_activity_root + +from Processing.IO_Manager import IO_Manager + +logger = logging.getLogger('infoslicer') + +wiki = None +custom = None + +class Book(IO_Manager): + def __init__(self, preinstalled, dirname): + IO_Manager.__init__(self, 0) + self.workingDir = os.path.join(get_activity_root(), dirname) + + if not os.path.exists(self.workingDir): + os.makedirs(self.workingDir, 0777) + + for i in preinstalled: + filepath = os.path.join(get_bundle_path(), 'Processing', + 'demolibrary', i[1]) + + logger.debug("install library: opening %s" % filepath) + open_file = open(filepath, "r") + contents = open_file.read() + open_file.close() + + logger.debug("install library: saving page %s" % i[0]) + self.save_page(i[0], contents, get_images=True) + logger.debug("install library: save successful") + + pages = self.get_pages() + if pages: + self.article = self.load_article(pages[0]) + else: + self.article = Article() + +class WikiBook(Book): + def __init__(self): + PREINSTALLED = [ + (_('Lion (from en.wikipedia.org)'), "lion-wikipedia.dita"), + (_('Tiger (from en.wikipedia.org)'), "tiger-wikipedia.dita"), + (_('Giraffe (from en.wikipedia.org)'), "giraffe-wikipedia.dita"), + (_('Zebra (from en.wikipedia.org)'), "zebra-wikipedia.dita") ] + Book.__init__(self, PREINSTALLED, 'data/book') + +class CustomBook(Book): + def __init__(self): + PREINSTALLED = [ + (_('Giraffe'), "giraffe-blank.dita") ] + Book.__init__(self, PREINSTALLED, 'tmp/book') + +def init(): + global wiki, custom + wiki = WikiBook() + custom = CustomBook() diff --git a/document.py b/document.py index 204d34f..c9f75bb 100644 --- a/document.py +++ b/document.py @@ -14,6 +14,11 @@ from gettext import gettext as _ +from Processing.Article.Article import Article + +source = Article() +working = Article() + def read_file(self, file_path): logger.debug("reading the file") """ @@ -22,6 +22,8 @@ from sugar.activity.activity import ActivityToolbox from GUI_Components.Edit_Pane import Edit_Pane from GUI_Components.Format_Pane import Format_Pane from GUI_Components.Image_Pane import Image_Pane +import document +import book TABS = (Edit_Pane(), Image_Pane(), @@ -63,6 +65,8 @@ class Toolbar(gtk.Toolbar): for i in tab.toolitems: self.insert(i, -1) + txt_toggle.set_active(True) + def _toggle_cb(self, widget, toggles): for tab in TABS: for i in tab.toolitems: @@ -73,9 +77,12 @@ class Toolbar(gtk.Toolbar): else: another = toggles[0] == widget and 1 or 0 toggles[another].set_active(False) - toggles[another].stop_emission('toggled') index = int(not another) for i in TABS[index].toolitems: i.show() + + TABS[index].set_source_article(book.wiki.article) + TABS[index].set_working_article(book.custom.article) + self.edit.set_current_page(index) @@ -23,9 +23,10 @@ from sugar.graphics.toolcombobox import ToolComboBox from GUI_Components.Compound_Widgets.Library_View import Library_View from GUI_Components.Compound_Widgets.toolbar import WidgetItem -class View(Library_View): +class View(gtk.EventBox): #Library_View): def __init__(self): - Library_View.__init__(self) + gtk.EventBox.__init__(self) + #Library_View.__init__(self) """ @@ -71,6 +72,7 @@ class Toolbar(gtk.Toolbar): def __init__(self, library): gtk.Toolbar.__init__(self) self.library = library + return wikimenu = ToolComboBox(label_text=_('Get article from:')) wikimenu.combo.connect('changed', self._wikimenu_changed_cb) |