changeset 49:83078930ae66

introduction of the argument parser
author Reimar Bauer <rb.proj AT googlemail DOT com>
date Wed, 04 Jun 2008 10:13:10 +0200
parents 3dfa6a13ba3c
children 6122e5bb9332
files data/plugin/action/arnica_slides.py data/plugin/parser/text_x_arnica.py
diffstat 2 files changed, 80 insertions(+), 69 deletions(-) [+]
line wrap: on
line diff
--- a/data/plugin/action/arnica_slides.py	Tue Jun 03 11:00:21 2008 +0200
+++ b/data/plugin/action/arnica_slides.py	Wed Jun 04 10:13:10 2008 +0200
@@ -368,8 +368,7 @@
             # XXX Check that all lists have same length
             idx = images.index(target)
 
-            image_for_webnail = int(request.form.get("image_for_webnail", [0])[0])
-
+            image_for_webnail = (request.form.get("image_for_webnail", [0])[0])  is 'True'
             if not image_for_webnail:
                 web['src'] = getAttachUrl(request.getScriptname(), pagename, target)
             else:
--- a/data/plugin/parser/text_x_arnica.py	Tue Jun 03 11:00:21 2008 +0200
+++ b/data/plugin/parser/text_x_arnica.py	Wed Jun 04 10:13:10 2008 +0200
@@ -92,7 +92,7 @@
 
 import os, re
 from random import randint
-from MoinMoin import caching, wikiutil
+from MoinMoin import caching, macro, wikiutil
 from MoinMoin.action import AttachFile
 from MoinMoin.packages import packLine
 from MoinMoin.Page import Page
@@ -107,6 +107,26 @@
 
 parser_name = __name__.split('.')[-1]
 
+def macro_arnica(macro, target_page=u'', sort_by_date=False, sort_by_name=True, sort_by_alias=False,
+                 album=False, album_name=u'album', front_image=u'', template_itemlist=False,
+                 reverse_sort=False, border_thick=int(1), columns=int(4), filter=u'.', mode=int(1), help=False,
+                 show_text=True, show_date=True, show_tools=True, only_items=False,
+                 image_for_webnail=False, renew=False,
+                 thumbnail_width=int(128), webnail_width=int(640), text_width=int(128)):
+    """ macro to initialize all default parameters for arnica """
+
+    from inspect import getargspec
+    args, varargs, varkw, defaults = getargspec(macro_arnica)
+    # XXX find the proper method do get the real values
+    defaults = (target_page, sort_by_date, sort_by_name, sort_by_alias,
+                 album, album_name, front_image, template_itemlist,
+                 reverse_sort, border_thick, columns, filter, mode, help,
+                 show_text, show_date, show_tools, only_items,
+                 image_for_webnail, renew,
+                 thumbnail_width, webnail_width, text_width)
+
+    return (args[1:], defaults)
+
 # ToDo may be move to wikiutil
 def get_exif_info(file_name):
     """ gets exif info from image file
@@ -127,49 +147,29 @@
     """ arnica parser """
     extensions = '*.jpg'
     def __init__(self, raw, request, **kw):
-        # list of optional arguments for the parser starts here
-        self.target_page = ''
-        self.sort_by_date = '0'
-        self.sort_by_name = '1'
-        self.sort_by_alias = '0'
-        self.album = '0'
-        self.album_name = 'album'
-        self.front_image = ''
-        self.template_itemlist = '0'
-        self.reverse_sort = '0'
-        self.border_thick = '1'
-        self.columns = '4'
-        self.filter = '.'
-        self.mode = '1'
-        self.help = '0'
-        self.show_text = '1'
-        self.show_date = '1'
-        self.show_tools = '1'
-        self.only_items = '0'
-        self.image_for_webnail = '0'
-        self.renew = '0'
-        self.thumbnail_width = '128'
-        self.webnail_width = '640'
-        self.text_width = '140'
-        # list of optional arguments for the parser ends here
-
-        # get the paraemters
-        test = kw.get('format_args', '')
-        if test:
-            for arg in kw.get('format_args', '').split(','):
-                if arg.find('=') > -1:
-                    key, value = arg.split('=')
-                    setattr(self, key, wikiutil.escape(value.strip(), quote=1))
-        # calc
-        self.width = str(int(self.thumbnail_width) + int(self.text_width))
-
         self.pagename = request.page.page_name
         self.raw = raw
         self.request = request
         self.form = None
         self._ = request.getText
 
-        self.outer_table_style = ' border="%s"' % self.border_thick
+        macro = self._make_macro()
+        args = kw.get('format_args', '')
+        try:
+            settings = wikiutil.invoke_extension_function(macro.request, macro_arnica, args, [macro])
+        except ValueError, err:
+            self.request.write(
+                   "arnica: %s" % err.args[0])
+            return
+
+        keys, values = settings
+        for i in range(len(keys)):
+            setattr(self, keys[i], values[i])
+
+        # calc
+        self.width = str(self.thumbnail_width + self.text_width)
+
+        self.outer_table_style = ' border="%d"' % self.border_thick
         self.inner_table_style = ' style="border-style:none; margin:10px;"'
         self.td_style = ' align="center" style="padding:0; margin:2px 2px; border-style:none"'
 
@@ -181,6 +181,18 @@
         self.description = [] # array of description
         self.webimg = [] # array of images for forms
 
+    def _make_macro(self):
+        """Test helper"""
+        from MoinMoin.parser.text import Parser
+        from MoinMoin.formatter.text_html import Formatter
+        p = Parser("##\n", self.request)
+        p.formatter = Formatter(self.request)
+        p.formatter.page = Page(self.request, self.pagename)
+        self.request.formatter = p.formatter
+        p.form = self.request.form
+        m = macro.Macro(p)
+        return m
+
     def show_tools_restricted(self, this_target):
         """ show only tools to users with enough rights
         @param this_target: image
@@ -269,7 +281,7 @@
 
     def show_alias_mode2(self, idx):
         """ view mode 2 alias text is on righthand of image """
-        if self.show_text == '1':
+        if self.show_text:
             return '''
 <td valign="top" width="%(text_width)s" %(style)s>
  %(this_alias)s
@@ -282,7 +294,7 @@
 
     def show_date_mode2(self, idx):
         """ view mode 2 selection for date """
-        if self.show_date == '1':
+        if self.show_date:
             return '''<td%(style)s><p>%(this_exif_date)s</p></td>''' % {
                       "style": self.td_style,
                       "this_exif_date": self.exif_date[idx]}
@@ -291,7 +303,7 @@
 
     def show_tools_mode2(self, idx):
         """ view mode 2 selection for tools """
-        if self.show_tools == '1':
+        if self.show_tools:
             return "<td align=""center""%(style)s> %(tools)s </td>" % {
                 "style": self.td_style,
                 "tools": self.tools_html(idx)}
@@ -332,7 +344,7 @@
 
     def show_tools_mode1(self, idx):
         """ view mode 1 selection of tools """
-        if self.show_tools == '1':
+        if self.show_tools:
             text = "<tr><td align=""center""%(style)s>%(tools)s </td></tr>" % {
                 "style": self.td_style,
                 "tools": self.tools_html(idx)}
@@ -342,7 +354,7 @@
 
     def show_date_mode1(self, idx):
         """ view mode 1 selection of date """
-        if self.show_date == '1':
+        if self.show_date:
             return '''
 <tr>
 <td%(style)s>%(this_exif_date)s</td>
@@ -354,7 +366,7 @@
 
     def show_alias_mode1(self, idx):
         """ view mode 1 alias text below image """
-        if self.show_text == '1':
+        if self.show_text:
             return '''
 <tr>
 <td width="%(thumbnail_width)s" %(style)s> %(this_alias)s</td>
@@ -509,11 +521,11 @@
         image_dict = {}
         quotes = self.get_quotes()
 
-        if self.only_items == '1':
+        if self.only_items:
             files = quotes['image']
             all_files = [attfile for attfile in files if os.path.exists(os.path.join(path, attfile))]
 
-            if self.sort_by_alias == '1':
+            if self.sort_by_alias:
                 alias_text = quotes['alias']
                 i = 0
                 for attfile in all_files:
@@ -526,13 +538,13 @@
         else:
             all_files = os.listdir(path)
 
-        if self.filter != '.':
+        if self.filter != u'.':
             all_files = [attfile for attfile in all_files if re.match(self.filter, attfile)]
 
-        if self.sort_by_name == '1' and self.only_items == '0':
+        if self.sort_by_name and self.only_items is False:
             all_files.sort()
 
-        if self.sort_by_date == '1':
+        if self.sort_by_date:
             for attfile in all_files:
                 infile = os.path.join(path, attfile)
                 ft_file = "%s%s" % (str(os.path.getmtime(infile)), str(randint(0, 65535)))
@@ -543,7 +555,7 @@
 
         image_dict.clear()
 
-        if self.reverse_sort == '1':
+        if self.reverse_sort:
             all_files.reverse()
 
         if all_files:
@@ -576,26 +588,26 @@
         webf = os.path.join(arena_dir, webnail)
         thumbf = os.path.join(arena_dir, thumbnail)
 
-        if self.renew == '1':
+        if self.renew:
             cache_web.remove()
             cache_thumb.remove()
 
         if not cache_web.exists() or not cache_thumb.exists():
             im_obj = Image.open(imagef)
             if not cache_web.exists():
-                if not self.image_for_webnail == '1':
-                    im_obj.thumbnail((int(self.webnail_width), int(self.webnail_width)), Image.ANTIALIAS)
+                if not self.image_for_webnail:
+                    im_obj.thumbnail((self.webnail_width, self.webnail_width), Image.ANTIALIAS)
                     im_obj.save(webf, image_type)
 
             if not cache_thumb.exists():
-                im_obj.thumbnail(((int(self.thumbnail_width)), ((int(self.thumbnail_width)))),
-                               Image.ANTIALIAS)
+                im_obj.thumbnail((self.thumbnail_width, self.thumbnail_width), Image.ANTIALIAS)
                 im_obj.save(thumbf, image_type)
 
     def format(self, formatter):
         """ does the format """
+
         _ = self._
-        if self.help == '1':
+        if self.help:
             self.print_help()
             return
 
@@ -607,7 +619,7 @@
             self.request.write(_("No matching image file found!"))
             return
 
-        if self.template_itemlist == '1':
+        if self.template_itemlist:
             self.request.write(_("""
             Copy the following listitems into the script.
             Replace alias with the label you want.
@@ -619,8 +631,8 @@
                                    'alias': 'alias'
                                     })
 
-        COLUMNS = min([int(self.columns), len(self.full)])
-        if self.album == '1':
+        COLUMNS = min([self.columns, len(self.full)])
+        if self.album:
             COLUMNS = 1
 
         data = TupleDataset()
@@ -634,38 +646,38 @@
         for image in self.full:
             i = self.full.index(image)
             self.create_thumbnail_and_webnail(image, self.web[i], self.thumb[i], self.imgtype[i])
-            if self.album == '0':
-                if self.image_for_webnail == '1':
+            if not self.album:
+                if self.image_for_webnail:
                     self.webimg = self.full
                 else:
                     self.webimg = self.web
 
-                if self.mode == '1':
+                if self.mode == 1:
                     text = self.mode1_html(i)
 
-                if self.mode == '2':
+                if self.mode == 2:
                     text = self.mode2_html(i)
 
                 if col_count <= COLUMNS:
                     result.append(''.join(text))
 
-                if col_count == COLUMNS and self.album == '0':
+                if col_count == COLUMNS and not self.album:
                     col_count = 0
                     data.addRow(tuple(result))
                     result = []
 
                 col_count += 1
 
-        if result and self.album == '0':
+        if result and not self.album:
             for i in range(COLUMNS - col_count + 1):
                 result.append('')
 
-        if self.album == '1':
+        if self.album:
             front_image = self.front_image or self.full[0]
             try:
                 i = self.full.index(front_image)
                 self.create_thumbnail_and_webnail(image, self.web[i], self.thumb[i], self.imgtype[i])
-                if self.image_for_webnail == '1':
+                if self.image_for_webnail:
                     self.webimg = self.full
                 else:
                     self.webimg = self.web